php enquiry form - part filled from database - php

Afternoon,
Wondering if anyone can help me. Using tables in a database I've got a form which is pre populated (from the content in the database) depending on the page the user has come in from when an enquiry is made.
Eg. if the user has come in from product A page and clicked on the 'enquiry' button from item c, the enquiry form is already pre populated with the name 'product A' and 'item c'
index.php?id=1&pack=13
This is fine if the user comes in from a product page, however if the user clicks on the enquiry button at a higher level page how do I get just the product name to appear in the form? I would have thought it would have been as simple to just change the code to
index.php?id=1
However that doesn't work - the form is completing blank when doing this.
My php knowledge is very limited therefore any help is hugely appreciated.
The db table I'm wanting to target is say 'Bob', within this table I want to target the id of the individual items which selects the name of the item. This currently works as:
$query = mysql_query("SELECT Bob.Name, Bob_Packages.Name FROM Bob, Bob_Packages WHERE Bob.Id=Bob_Packages.Bob_Id AND Bob.ID = '".$id."' AND Bob_Packages.Id = '".$pack."'");
However I now only want 'Bob.Name' for this particular 'enquiry' link. My brain is frying!!
Many thanks,
Motley
Hi Dalionzo,
Thanks for your reply. However not really sure if it does help me out. In the current enquiry php page I have:
<?php {
$query = mysql_query("SELECT Bobs.Name, Bob_Packages.Name FROM Bobs, Bob_Packages WHERE Bobs.Id=Bob_Packages.Bob_Id AND Bobs.ID = '".$id."' AND Bob_Packages.Id = '".$pack."'");
$result = mysql_fetch_array($query);
echo $result[0];
}
?>
It's basically just the Bobs.Id I want pulling through. I gave what you supplied a try and an error was returned.
Any ideas? Thanks very much.

In your query you're checking for
id=$id AND packages.id=$pack
This means, that if the query is missing one from the URL, it won't find anything at all!
So, what you have to do, is check if one of them is missing, and then create different queries using that
<?php
$query = "SELECT Bob.Name, Bob_Packages.Name FROM Bob, Bob_Packages WHERE Bob.Id=Bob_Packages.Bob_Id";
if($_GET['id'] != '') {
$query .= " AND Bob.ID = '".$id."'";
}
if($_GET['pack'] != '') {
$query .= " AND Bob_Packages.Id = '".$pack."'";
}
mysql_query($query);
?>
Hope this helps you out!
P.S. I haven't tested this...

Related

Write to a php file via wordpress

I've built a web page that is able to send text messages to employees at the company where I work. With new employees being added and removed on a constant basis, I want to integrate this app with wordpress where the employees can be managed without editing the code.
Each post would contain the user's name and phone number. The name would be pulled in on the webpage as an option for the user to contact. When the form is submitted, it would go to a php form that runs an if/else to find the employee and match that employee with their phone number like so:
//Who the text message is to, Establish their phone #
if($employee == 'brad'):
$text_to[] = '+15555555555';
elseif ($employee == 'mary'):
$text_to[] = '+15555555555';
elseif ($employee == 'tom'):
$text_to[] = '+15555555555';
elseif ($employee == 'bill'):
$text_to[] = '+15555555555';
elseif ($employee == 'joe'):
endif;
I want to be able to not only pull these names from wordpress via a loop to display onto my page, but also to be able to add or remove the new entries, along with their phone number, to this php contact form.
I know how to loop through the wordpress posts to display the names on the page. I want to know if it's possible to also use this data to modify this contact form, and if so, how to set this up. Each time someone edits the wordpress entry for Joe, the PHP form gets this update so that when Joe is sent a message, it finds his phone number and sends him the message.
Any help is greatly appreciated. I should also note that I'm using Twilio to send the texts messages.
The use of a DMBS works well, but is not the only solution.
include 'users.inc'; // flat file creating array $userList
which could be an array( ofArrays ) for complex structures
[assume $userList = array($user => $phone, ...); ]
then foreach( $userList as $user => $phone ) { // process($user, $phone); }
Kudos for trying to solve a simple problem yourself. It's obvious that you are new to the idea of databases, and quite frankly, you're doing this the wrong way.
Let's talk about how your initial approach can be improved:
Each post would contain the user's name and phone number.
Perhaps instead of posts, we have one database table to store employee information.
You'll find tons of information on databases and how to use them with your wordpress account with a simple google search.
I want to be able to not only pull these names from wordpress via a loop to display onto my page, but also to be able to add or remove the new entries, along with their phone number, to this php contact form.
Again, if you had a database to store employee information, this is basic.
For example, an employees database table may have the following columns:
id
name
phone
created_at
updated_at
Since PHP has built in functions for communicating with a MYSQL database (which is most likely what WordPress is already using), you can do things like:
Get all employee data
SELECT * FROM employees
Get a certain employee's data
SELECT * FROM employees WHERE name = '$name'
$name is a variable that can be set via POST request from a WordPress form
Update a certain employee's data
UPDATE employees SET phone = '+15555555555' WHERE name = '$name'
Remove a certain employee's data
DELETE FROM employees WHERE id = 5
You are also able to do things like:
SELECT * FROM employees WHERE created_at > '3/1/2015'
Which will return all employees that were added after 3/1/15.
So everything that you all suggested was helpful. I may have not been as clear as I could have that I really needed the creation/editing/deletion of entries to be done via wordpress posts. I was able to set it up like this by doing the following:
//pull variables from html form input. Employee variables are post ID's that I will then be able to use to retrieve the post_content which contains their phone numbers
$employee1 = $_POST['employeeName1'];
$employee2 = $_POST['employeeName2'];
$employee3 = $_POST['employeeName3'];
$customMsg = $_POST["textMessage"];
//Create array from above variables and exclude any that lack post data
$employees = array($employee1, $employee2, $employee3);
$setEmployeeIDs = array();
foreach ($employees as $employee) {
if (!empty($employee)) {
$setEmployeeIDs[] = $employee;
}
}
$servername = "xxxx";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Get array of Phone Numbers connected to each ID and add to array
$sql = "SELECT * FROM wp_posts WHERE ID IN (".implode(',',$setEmployeeIDs).")";
$result = $conn->query($sql);
$phoneNumbers = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$phoneNumbers[] = $row["post_content"] ;
}
} else {
echo "0 results";
}
$conn->close();
So to sum it up, I used wordpress to publish/edit/delete that data as posts, then sent the ID's selected from the webpage to the php form, and then was able to retrieve the phone numbers from the SQL database using Raphael's direction.

Database always receiving same IDs

I hope this is not a bad question. I've been trying to understand what I'm doing wrong but I can't.
I'm pretty new to php and mysql so I'm really confused...
I have this database (I will attach a mysql workbench model screenshot)
And I'm trying to insert the sales into sale and print_for_sale tables. The queries seem to be working and the data shows up in phpmyadmin. No error pops up. However the sale user in the sale table is always the same id. Even if I use a different user login. And in the print_for_sale table the fk_sale_id is always the same id. And the price_print_for_sale is always the same as well. That is not supposed to happen. What am I doing wrong?
Can anyone help me?
Thank you!
Here is my php code:
<?php
session_start();
$user_id = $_SESSION['user_id'];
print_r($_POST);
$id_print= $_POST['print_id'];
include('database.php');
$bought_sizes=$_POST['sizes'];
$number_of_bought_sizes= count($bought_sizes);
//header('location:index.php?area=printstore');
$sqlinsertsale = "insert into sale
(fk_sale_user,
fk_payment_id)
values(".$user_id.", 1)";
//payment is not yet defined so I'm using 1 just to try.
mysql_query($sqlinsertsale);
for($i=0; $i< $number_of_bought_sizes; $i++){
$selectmultiple = "select *
from print_has_size
inner join size on fk_size_id = size_id
inner join print on fk_print_id = print_id
where print_id =".$id_print."";
$resultmultiple = mysql_query($selectmultiple);
$linemultiple = mysql_fetch_assoc($resultmultiple);
$size_price = $linemultiple["size_price"];
$selectsale = "select *
from sale";
$resultsale = mysql_query($selectsale);
$linesale = mysql_fetch_assoc($resultsale);
$sale_id = $linesale["sale_id"];
//$sale_id = mysql_insert_id();
/*PARA CADA 1 DOS TAMNHO*/
$sqlinsertprintforsale = "insert into print_for_sale
(fk_sale_id,
price_print_for_sale)
values(".$sale_id.", ".$size_price.")";
mysql_query($sqlinsertprintforsale);
}
?>
I'm also going to attach a screenshot of the selection page so you can see the markup in case it helps.
Edit:
(I'm adding the php code from where I check the user login)
<?php
session_start();
include('database.php');
$user=mysql_real_escape_string($_POST['user_login']);
$pass=mysql_real_escape_string($_POST['user_pass']);
$sql="select user_id, user_name
from user
where
user_login='".$user."'
and user_pass = MD5('".$pass."')";
echo $sql;
$result = mysql_query($sql);
$num_of_regs = mysql_num_rows($result);
echo "<br>".$num_of_regs;
if($num_of_regs!=1) {
header('location:index.php?login=done');
}
else {
$line = mysql_fetch_assoc($result);
$user_name = $line['user_name'];
$user_id = $line['user_id'];
$_SESSION['user_name'] = $user_name;
$_SESSION['user_id'] = $user_id;
header('location:index.php');
}
?>
And I did a log out system too.
<?php
session_start();
session_destroy();
header('location:index.php');
?>
Now I noticed that the sale table is not receiving data..
Only the print_for sale is. Wrong data still. Same IDs... Why? :(
This is the only error message that I get when I used the code
ini_set('display_errors', true); error_reporting(E_ALL);
Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /Applications/XAMPP/xamppfiles/htdocs/printstore/database.php on line 7
Added
echo $_SESSION['user_id'];
And this is my output for user 1:
And for user 2:
it seems to be ok, it recognizes user 1 and 2.
Table sale is not being refreshed when I make a "new purchase" and table print_for_sale is refreshed with the same sale id. Always 3 (as shown in the screenshot)
I deleted every row from sale in phpmyadmin and tried again. It's working. Sale table seems to be working fine. The only problem now is the table print_for_sale which even when I use a different user (and it shows up ok in the sale table), it still shows the same sale_id and the same price_print_price which is always 25). And in this case I never selected anything costing 25. -
Give this a shot. It seems that you're getting the same result because you never loop through your results. Also make sure that your field names are exactly the same as your field names in your DB.
$selectsale = "select *
from sale";
$resultsale = mysql_query($selectsale);
while($linesale = mysql_fetch_assoc($resultsale))
{
$sale_id = $linesale["sale_id"];
}
when you logout you should destroy your sessions
I assume you have a logout page like logout.php. In it you should set below lines. If you don't do that session values can't change.
<?php
session_start();
session_destroy();
?>
Also if you store your user id on a session variable, only closing all browser windows than reopen and login will help you.
Extra info for you future code life: WHY PDO http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059

Receiving errors on empty GET variable

Im building an application that shows off various types of records for my team as a whole. to start this is the menu (some with $_GET information on them)
The html menu that brings up this page looks like this:
<li>WEB department
<ul>
<li>Mike</li>
<li>Deidre</li>
</ul>
</li>
The webpage that pulls the web data, the important part is this below
$pullWebTeamData = "SELECT * FROM tlm_accounts WHERE type_of_account = 'WEB' ;";
$pullWebTeamDataDoIt = mysqli_query($c2d, $pullWebTeamData) or die ("could not pull WEB team data" . mysqli_error($c2d));
then further down the page i output the data i want. For example
while($row = mysqli_fetch_array($pullWebTeamDataDoIt)){
//do stuff here - - - **this part never changes**
}
Then this pulls all the records for the web team as a whole. In this fashion i thought "hmm it'd be even more useful if I can display the records for each of the teams members individually.
Obviously, im not going to make an individual page for ALL the members of the company so i thought of re-purposing this page so that if a GET variable equals a persons name, that certain data is shown.
here is the code
$tstname= $_GET['tstname'];
if($tstname == "Mike"){
$pullWebTeamData = "SELECT * FROM tlm_accounts WHERE type_of_account = 'WEB' ;";
$pullWebTeamDataDoIt = mysqli_query($c2d, $pullWebTeamData) or die ("could not pull WEB team data" . mysqli_error($c2d));
} elseif ($tstname == "Deidre"){
$pullWebTeamData = "SELECT * FROM tlm_accounts WHERE type_of_account = 'WEB' ;";
$pullWebTeamDataDoIt = mysqli_query($c2d, $pullWebTeamData) or die ("could not pull WEB team data" . mysqli_error($c2d));
} else {
$pullWebTeamData = "SELECT * FROM tlm_accounts WHERE type_of_account = 'WEB' ;";
$pullWebTeamDataDoIt = mysqli_query($c2d, $pullWebTeamData) or die ("could not pull WEB team data" . mysqli_error($c2d));
}
Now although it pulls the data I want(named get link or normal web link), the problem is that on page load, if the person clicks the regular web page link that doesn't have $_GET information attached. It throws an error because at that point the "$_GET" in:
$tstname= $_GET['tstname'];
doesnt exist. How can i make it so that if the "$_GET" doesnt exist. to just ignore it?
Feels like i should know this....lol anyways,
i tried things like
if(!empty($testname)){ do stuff }
or if($testname) //since this equals to true if not empty...
etc but to no avail. Hope I was clear. any tips/help etc i humbly appreciate.
Thanks in advanced.
use isset
if(isset($_GET['tstname'])) {
// do your stuff
}
Use ternary operator for setting the variable.
$tstname= !empty($_GET['tstname'])? $_GET['tstname']: ' ';
or
$tstname= isset($_GET['tstname'])? $_GET['tstname']: ' ';
$tstname= isset($_GET['tstname'])?$_GET['tstname']:'';

Edit mysql database from "GET" index.php?id=XX

I'm currently learning PHP. I've code a simple bucketlist script with a admin panel, sessions etc just to see if I can do it.
The last page I am coding is the "edit.php" & "editone.php" I have a table which returns all data within the database "ID, Goal & Rating" my fourth column returns "EDIT" as a link which will link off to: editone.php?id=xx
editone.php currently is not a page. For the life of me I cannot figure out how I code the editone so I can grab the data and UPDATE mysql. I'm almost there just cannot piece together the puzzle.
Here's the core of my code for the edit page.
<?php
while ($query_row = mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>".$query_row['id']."</td><td>". $query_row['goals']."</td><td><span class='label label-inverse'>". $query_row['rating']."</span></td><td><a href='editone.php?id=".$query_row['id']."'>Edit</a></td>";
echo "<tr>";
}
?>
Any assistance would be really appreciated.
Send all the parameters through POST method to editone page. I mean in your edit page, you are getting all the variables from database. You can show them in a form having a submit button and of type "POST". So now when someone submits, it goes to editone.php page.
Get all the variables first through $_POST method. Then write a update query.
$sql = "UPDATE tablename SET goals = '$goal', rating='$rating' WHERE id = $id";
make sure to escape your post variables as said in the comment.
This is how should be your PDO Update statement.
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// new data
$goals = 'Some goals';
$rating = 'whatever rating';
$id = 3;
// query
$sql = "UPDATE tablename
SET goals=?, rating=?
WHERE id=?";
$q = $conn->prepare($sql);
$q->execute(array($goals,$rating,$id));
If I understood you correctly, what you want is a page that first displays a single row (so it can be edited) and then saves it once you're done. So you start out by writing the HTML form with no data in it.
Next, you read the ID from the query string:
<?php
$rowId = $_GET['id'];
and then query for the data:
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "SELECT goals, rating FROM tablename WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($rowId));
$row = $query->fetch();
Now, you can use the data to populate your form. This gets you about halfway there. :-)
You'll want the actual save to be in response to a POST request, not GET. There's a long and somewhat complicated explanation on why that is, but the simplified version is that you use POST whenever you're making changes for the user, and GET when you're just reading data -- there's a bunch of browser and proxy behavior and whatnot tied to these assumptions, so it's a good idea to start doing things the right way early on.
When you process the POST request -- you can do it on the same page -- you'll have the updated form values for grabs, and you can use them to update your database:
// This can be a hidden field on the form...
$rowId = $_POST['id'];
$goals = $_POST['goals'];
$rating = $_POST['rating'];
// database connection example borrowed from Abhishek
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$sql = "UPDATE tablename SET goals = ?, rating = ? WHERE id = ?";
$query = $conn->prepare($sql);
$query->execute(array($goals, $rating, $rowId));
After this, your database should be updated. To finish things off, you'll probably want to redirect back to the page to make sure the form can't be double-submitted accidentally.
I haven't covered quite everything here, a bit on purpose. It's more fun when there are some blanks to fill in. :-)
You probably want your second <tr> to be </tr>.
The most common solution is to use an html form. The input values of this form are a select with the id in query string. When a submit button is pressed to save this, make a update. But I want share with you a good and complete web 2.0 example.

PHP to Update MySQL Database Table

First off, just wanted to say I'm a novice at this type of coding, although I'm hopeful that I'll eventually make sense of it all with a little guidance.
I have a MySQL database table (promotion) that stores a bunch of redemption codes for various products (for a give away contest). The idea is, the first person to enter the redemption code wins the product, and their info should be stored in the "promotion" table.
The table's columns are: redeem_id (Auto Increment field), redeem_code, redeemer_email, redeemer_first_name, redeemer_last_name, and redeem_date_time.
Initially, the redeem_id and redeem_code fields are the only ones with any data. What I'd like to happen is when a user enters their information (name, email, etc) and submit a redemption code, their info will populate the rest of the row for that particular code. If anyone else tries to submit a code that has already been redeemed, they should receive an error message - likewise for an invalid code (i.e. a code that does not exist in the table).
The PHP code I have so far is:
<?php
function get_promotion_by_redeem_code($redeem_code)
{
$sql = "SELECT * FROM promotion WHERE redeem_code= '".mysql_real_escape_string($redeem_code)."'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
return $row;
}
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).", redeemer_first_name=".mysql_real_escape_string($first_name).", redeemer_last_name=".mysql_real_escape_string($last_name).", redeem_date_time=NOW(), WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
$insert = mysql_query($query);
return $insert;
}
$email=$_POST['e_mail'];
$first_name=$_POST['f_name'];
$last_name=$_POST['l_name'];
$redeem_code=$_POST['v_code'];
$connection = mysql_connect('localhost', 'db', 'pw');
mysql_select_db('db', $connection);
$promotion = get_promotion_by_redeem_code($redeem_code);
if ($promotion) {
if (!$promotion['redeemer_email']) {
redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code);
echo 'Congratulations, you have successfully claimed this item!';
} else {
echo 'Sorry, this item has already been redeemed.';
}
} else {
echo 'Sorry, you have entered an incorrect claim code. Please use your browser\'s back button to try again.';
}
mysql_close($connection);
?>
It works as expected when I enter an invalid claim code, or if a code's row has been previously populated.
When it doesn't work, is when someone goes to redeem the item for the first time. Essentially, it will show the "Congratulations" message, however the table doesn't get updated for the submitted information. Therefore, no matter how many times the correct code is entered, the user will receive the "Congratulations" message.
I'm fairly certain that the error is in the redeem_promotion() function, but I can't figure out where.
You have add an extra comma(,) before WHERE clause. Thats the mistake, i think.
function redeem_promotion($email,$first_name,$last_name,$redeem_date_time,$redeem_code)
{
$query = 'UPDATE promotion
SET redeemer_email=".mysql_real_escape_string($email).",
redeemer_first_name=".mysql_real_escape_string($first_name).",
redeemer_last_name=".mysql_real_escape_string($last_name).",
redeem_date_time=NOW()
WHERE redeem_code=".mysql_real_escape_string($redeem_code)."';
**OR**
$query = "UPDATE promotion
SET redeemer_email='".mysql_real_escape_string($email)."',
redeemer_first_name='".mysql_real_escape_string($first_name)."',
redeemer_last_name='".mysql_real_escape_string($last_name)."',
redeem_date_time=NOW()
WHERE redeem_code='".mysql_real_escape_string($redeem_code)."'";
$insert = mysql_query($query);
return $insert;
}

Categories