My current form submits data to two different tables, and I want the auto_incremented value from one table to also be stored in the second table.
<form method="POST" action="addcocktail.php" >
Cocktail Name: <input type="text" name="cocktailname" />
How To: <input type="text" name="howto" />
<br>
<select id="selectingred1" name="selectingred1">
<?php
$sql = "SELECT ingredientID, name FROM tblIngredient ".
"ORDER BY name";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
echo "<option value=\"".$row['ingredientID']."\">".$row['name']."</option>\n ";
}
?>
</select>
<select id="quantity1" name="quantity1">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
<br>
<input type="submit" value="add" />
</form>
addcocktail.php:
<?php include("databasecon.php"); ?>
<?php
mysql_select_db("mwheywood", $con);
//insert cocktail details
$sql="INSERT INTO tblCocktail (name, howto)
VALUES
('$_POST[cocktailname]','$_POST[howto]')";
$sql2="INSERT INTO tblRecipe (ingredientID, quantity)
VALUES
('$_POST[selectingred1]','$_POST[quantity1]'),
('$_POST[selectingred2]','$_POST[quantity2]'),
('$_POST[selectingred3]','$_POST[quantity3]'),
('$_POST[selectingred4]','$_POST[quantity4]')";
if (!mysql_query($sql,$con))
{
die('Error: you fail at life' . mysql_error());
}
echo "cocktail added";
if (!mysql_query($sql2,$con))
{
die('Error: you fail at life' . mysql_error());
}
echo "ingredients added";
mysql_close($con);
?>
so to put it simply, when I submit my form. I want the "cocktailID" of the posted data to "tblCocktail" to also save into "tblRecipe"
after executing the insert query, you can get the insert id if succeeded with mysql_insert_id() function.
Related
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="doctor">
<?php
$con = mysqli_connect("---","---","---","---") or die("Can't Connect to the Database.");
$sql = mysqli_query($con, "SELECT Title, Name, LastName FROM physician");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"doctor1\">" . $row['Title'].' '.$row['Name'].' '.$row['LastName'] . "</option>";
}
?>
</select>
<input type='submit' value="Filter"><br>
</form>
Above is a form I created. I used POST method. This form has a select input tag and it's options are taken from my database. When form is submitted I need to access the value selected by user using $_POST['doctor'] function. But it doesn't give me any value. Can anyone help me?
If the ID for each entry in the "physician" table is stored in a column "PhysicianID", you should try the following code snippet:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="doctor">
<?php
$con = mysqli_connect("---","---","---","---") or die("Can't Connect to the Database.");
$sql = mysqli_query($con, "SELECT PhysicianID, Title, Name, LastName FROM physician");
while ($row = $sql->fetch_assoc()){
echo '<option value="'.$row['PhysicianID'].'">'.$row['Title'].' '.$row['Name'].' '.$row['LastName'].'</option>';
}
?>
</select>
<input type='submit' value="Filter"><br>
</form>
I am working on my project for school and is now stuck on this problem that I hope someone here my point me in the right direction.
I am designing a booking system which uses a web front and MySQL database. I have a few tables: Customers, Seats, Price, Booking and Screening. I am trying to insert data into the booking table from the other tables using there primary keys. however I keep getting the following error message: Incorrect integer value: '' for column 'customerid' at row 1
I have search every where but doesn't seem to get any solution. I have copied my code below.
<?php
$customerid=$_POST['customerid'];
$screeningid=$_POST['screeningid'];
$seatid=$_POST['seatid'];
$priceid=$_POST['priceid'];
$status=$_POST['status'];
$query = "INSERT INTO `booking`(bookingid, customerid, screeningid, seatid, priceid, bookingdate, status)
VALUES(NULL, '". mysql_real_escape_string($customerid)."', '". mysql_real_escape_string($screeningid)."', '". mysql_real_escape_string($seatid)."','". mysql_real_escape_string($priceid)."', 'DateTime()', '". mysql_real_escape_string($status)."')";
$result=mysql_query($query) or die (mysql_error());
// if successfully insert data into database, displays message "Successful".
if($result)
{
echo "<p>success</p>";
echo "<BR>";
}
else
{
echo mysql_error();
}
?>
This is my Form:
<div id="content">
<h2>Enter Booking Details Below</h2>
<form name="reg_form" action="bookingecho.php?action=add type=booking" onsubmit="return validate_reg()" method="POST" >
<table>
<tr>
<td>Customer</td>
<td> <select name="customerid">
<?php
//Perform database query
$query = ("SELECT * FROM customers
ORDER BY customerid DESC");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$customerid = $row['customerid'];
$fname = $row['fname'];
$lname = $row['lname'];
$telephone = $row['telephone'];
//use
echo "<option value>$customerid $fname $lname $telephone</option>";
}
?>
</select></td></tr>
<tr>
<td>Screening</td>
<td> <select name="screeningid">
<?php
//Perform database query
$query = ("SELECT * FROM screening");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$screeningid = $row['screeningid'];
$day = $row['day'];
$screeningdate = $row['screeningdate'];
$filmtitle = $row['filmtitle'];
//use
echo "<option value>$screeningid $day $screeningdate $filmtitle</option>";
}
?>
</select></td></tr>
<tr>
<td>Seat</td>
<td> <select name="seatid">
<?php
//Perform database query
$query = ("SELECT seats.seatid, seats.seatnumber, seats.seatclass
FROM seats
WHERE seatid
NOT IN (SELECT seatid FROM booking
WHERE screeningid = '$screeningid')
ORDER BY `Seats`.`seatid` ASC");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$seatid = $row['seatid'];
$seatnumber = $row['seatnumber'];
$seatclass = $row['seatclass'];
//use
echo "<option value>$seatid $seatnumber $seatclass</option>";
}
?>
</select></td></tr>
<tr>
<td>Concession</td>
<td> <select name="priceid">
<?php
//Perform database query
$query = ("SELECT * FROM price");
$result = mysql_query($query, $connection) or die (mysql_error());
// populate the select options with the results
while ($row = mysql_fetch_assoc($result))
{
//extract column
$priceid = $row['priceid'];
$concession = $row['concession'];
$cost = $row['cost'];
//use
echo "<option value>$priceid $concession $cost</option>";
}
?>
</select></td></tr>
<tr>
<td>Status</td>
<td>
<input type= radio name="status" value="Booked"> Booked
<input type= radio name="status" value="Reserved"> Reserved
</td>
</tr>
</select></td></tr>
</table>
<p align="center">
<td><input type="submit" name="submit" id= "submit" value="Add"/></td>
<input type="reset" value="Reset Form">
</p>
</form>
</div>
Use intval() for integer values.
Use mysql_real_escape_string on strings, Never for integers.
Single quotes around integer values in a mySQL query is optional.
Because intval() guarantees $customerid is an integer value, the quotes are not necessary and will never generate an error.
I have only included the two lines of code directly related to your customer id. The same likely applies to the other values as well.
$customerid=intval($_POST['customerid']);
$query = "INSERT INTO `booking`
(`bookingid`, `customerid`, `screeningid`,`seatid`,`priceid`, `bookingdate`, `status`)
VALUES(NULL,$customerid,'$screeningid','$seatid','$priceid',CURDATE(),'$status')";
Change:
<input name="status" value="Booked" type="radio"> Booked
<input name="status" value="Reserved" type="radio"> Reserved
To:
<input name="status" value="1" type="radio"> Booked
<input name="status" value="2" type="radio"> Reserved
Always submit integer values greater then zero whenever possible. They are easy to validate. To get the text back:
$statuses = array('unknown','booked','reserved')
$strStatus = $statuses[$status];
UPDATE FOREIGN KEY CONSTRAINT ERROR
A CONSTRAINT ERROR says you do not have a customer record for the added booking table. Or the foreign key is wrong. The foreign key is not needed.
You could combine the customer add, lookup and booking INSERT at the same time.
Rather than some sort of login to create or retrieve the customer record get the booking then during the last step in the booking process just ask for the phone number. Personally I do not care if someone were to query the system with my phone number and found out which seat I have. Some might. But asking for a a login in before getting the booking is a nuisance and a road block to finalizing the booking.
What I did was add the security ID
If they want to secure their seats with a password let it be their choice.
If the record does not exist, then ask for their name AFTER the seats are booked.
//$customerid = intval($_POST['customerid']);
$screeningid = intval($_POST['screeningid']);
$seatid = intval($_POST['seatid']);
$priceid = intval($_POST['priceid']);
$status = intval($_POST['status']);
$fname = mysql_real_escape_string($_POST['status']);
$lname = mysql_real_escape_string($_POST['lname']);
$telephone = intval(preg_replace('/[^D]/','',$_POST['telephone']));
//must have UNIQUE Index on `telephone`
$sql = "INSERT INTO `customer` (`customerid`,`fname`, `lname`, `telephone`)
VALUES(NULL,'', '', $telephone)";
$result = mysql_query($sql);
if(mysql_insert_id()){
$customerid = mysql_insert_id();
}
else{
list($customerid, $fname`, $lname,$id) = mysql_fetch_array(mysql_query(
"SELECT `customerid`,`fname`, `lname`, `telephone`,`id`
FROM `customer` WHERE `telephone`=$telephone"),MYSQL_NUM);
}
$query = "INSERT INTO `booking`
(`bookingid`, `customerid`, `screeningid`,`seatid`,`priceid`, `bookingdate`, `status`)
VALUES(NULL,$customerid,$screeningid,$seatid,$priceid,CURDATE(),$status)";
echo <<<EOT
<p>Your seats are booked.</p>
<form action="update.php" method="post">
<label>Last:</label>
<input type="text" name="lname" value="$lname" />
<br/>
<label>First:</label>
<input type="text" name="fname" value="$fname" />
<br/>
<label>Phone:</label>
<input type="tel" name="telephone" value="$telephone" />
<br/>
<p class="footnote">Security ID is optional</p>
<label>Security ID:</label>
<input type="text" name="id" value="$id" />
<br/>
<input type="hidden" name="phone" value="$telephone" />
<br/>
<div class="footnote">
If you want to keep your booking secure then enter a security id.
<br>If blank, no security ID will be necessary to retrieve your seats in the future.
<br/>This can be any number (e.g. PIN) word, or any characters.
<br/>Maximum 16 characters.</p>
<p>Do NOT use an existing high security password (e.g. your banking password)</p>
<h4>If you would like your seats sent to you via text,<br/>Select your mobile carrier<br/>This will also verify you entered the correct phone number</h4>
</div>
<label>Mobile Carrier</label>
<select>
<option value="">No Text / Land Line</option>
<option value="#message.alltel.com">Alltel</option>
<option value="#paging.acswireless.com">Ameritech</option>
<option value="#mmode.com">ATT Wireless</option>
<option value="#bellsouth.cl">Bellsouth</option>
<option value="#myboostmobile.com">Boost</option>
<option value="#mobile.celloneusa.com">CellularOne</option>
<option value="#mobile.mycingular.com">Cingular</option>
<option value="#sms.edgewireless.com">Edge Wireless</option>
<option value="#mymetropcs.com">Metro PCS</option>
<option value="#messaging.nextel.com">Nextel</option>
<option value="#mobile.celloneusa.com">O2</option>
<option value="#mobile.celloneusa.com">Orange</option>
<option value="#qwestmp.com">Qwest</option>
<option value="#pcs.rogers.com">Rogers Wireless</option>
<option value="#messaging.sprintpcs.com">Sprint PCS</option>
<option value="#teleflip.com">Teleflip</option>
</optgroup>
<option value="#msg.telus.com">Telus Mobility</option>
<option value="#email.uscc.net">US Cellular</option>
<option value="#vtext.com">Verizon</option>
</select>
<br/>
<input type="submit" value="Save Changes" />
</form>
EOT;
FORM SNIPPET
label {
width: 5em;
display: inline-block;
text-align: right;
}
.footnote {
margin: .5em 0 .5em 5em;
}
input[type="submit"] {
margin: 1em 6em;
}
h4 {
margin-bottom: 0;
}
<p>Your seats are booked.</p>
<form action="update.php" method="post">
<label>Last:</label>
<input type="text" name="lname" value="$lname" />
<br/>
<label>First:</label>
<input type="text" name="fname" value="$fname" />
<br/>
<label>Phone:</label>
<input type="tel" name="telephone" value="$telephone" />
<br/>
<p class="footnote">Security ID is optional</p>
<label>Security ID:</label>
<input type="text" name="id" value="$id" />
<br/>
<input type="hidden" name="phone" value="$telephone" />
<br/>
<div class="footnote">
If you want to keep your booking secure then enter a security id.
<br>If blank, no security ID will be necessary to retrieve your seats in the future.
<br/>This can be any number (e.g. PIN) word, or any characters.
<br/>Maximum 16 characters.</p>
<p>Do NOT use an existing high security password (e.g. your banking password)</p>
<h4>If you would like your seats sent to you via text,<br/>Select your mobile carrier<br/>This will also verify you entered the correct phone number</h4>
</div>
<label>Mobile Carrier</label>
<select>
<option value="">No Text / Land Line</option>
<option value="#message.alltel.com">Alltel</option>
<option value="#paging.acswireless.com">Ameritech</option>
<option value="#mmode.com">ATT Wireless</option>
<option value="#bellsouth.cl">Bellsouth</option>
<option value="#myboostmobile.com">Boost</option>
<option value="#mobile.celloneusa.com">CellularOne</option>
<option value="#mobile.mycingular.com">Cingular</option>
<option value="#sms.edgewireless.com">Edge Wireless</option>
<option value="#mymetropcs.com">Metro PCS</option>
<option value="#messaging.nextel.com">Nextel</option>
<option value="#mobile.celloneusa.com">O2</option>
<option value="#mobile.celloneusa.com">Orange</option>
<option value="#qwestmp.com">Qwest</option>
<option value="#pcs.rogers.com">Rogers Wireless</option>
<option value="#messaging.sprintpcs.com">Sprint PCS</option>
<option value="#teleflip.com">Teleflip</option>
</optgroup>
<option value="#msg.telus.com">Telus Mobility</option>
<option value="#email.uscc.net">US Cellular</option>
<option value="#vtext.com">Verizon</option>
</select>
<br/>
<input type="submit" value="Save Changes" />
</form>
The error message means you are getting an "empty string" ('') for customerid, which simply means that your first chunk of code is not getting any value at all for that field when the form is submitted.
Here is the problem:
echo "<option value>$customerid $fname $lname $telephone</option>";
The values between <option> and </option> are what will be displayed to the end-user, but they will not be submitted with your form, which means they won't be available to that first chunk of code.
To submit the customerid, you have to put it into the value part:
echo "<option value=$customerid>$customerid $fname $lname $telephone</option>";
You placed apostrophes around $customerid (and other non-string values) when it is actually an integer inside your database. Delete the apostropes (') around all values that are meant to be integers in your database (I have a feeling that is the case for many of your variables). Also please organize your code because it was extremely difficult to look at it without crying :)
<?php
$customerid=mysql_real_escape_string($_POST['customerid']);
$screeningid=$_POST['screeningid'];
$seatid=mysql_real_escape_string($_POST['seatid']);
$priceid=mysql_real_escape_string($_POST['priceid']);
$status=mysql_real_escape_string($_POST['status']);
$query = "INSERT INTO `booking`(bookingid, customerid,
screeningid, seatid, priceid, bookingdate, status)
VALUES (NULL, ". $customerid.", ". $screeningid.", ".
$seatid.", ".$priceid.", 'DateTime()', '".$status."')";
$result=mysql_query($query) or die (mysql_error());
// if successfully insert data into database, displays message "Successful".
if($result)
{
echo "<p>success</p><br>";
}
else
{
echo mysql_error();
}
?>
Also note, DateTime() is a php function, not an SQL command. I left it in the previous code but be aware that you should fix that error.
Let me know if this worked for you.
I created a form which can add more input field for product_name and quantity of the product with the help of jquery, this is the demo where you can add more input field in the form.
the problem is when i submit the form only the last product will submit into my database the rest of the product will not submitted.
this is my query
<?php
if(isset($_POST['submit'])){
//process the form
$date = $_POST["date"];
$customer_name = $_POST["customer_name"];
$product_description = $_POST["product_description"];
$quantity = $_POST["quantity"];
$status = $_POST["status"];
$query = "
INSERT INTO orders (
date, customer_name, product_description, quantity, status
) VALUES (
'$date', '$customer_name', '$product_description',$quantity,$status
)";
$order_set = mysqli_query($connection, $query);
if($order_set){
redirect_to("index.php");
}
} else {
// failed
}
?>
My Form
<form action="order.php" method="post">
<div class="newOrder">
<p><span>Date</span><input type="date" value="2014-12-01" name="date" /></p>
<p><span>Name</span>
<select name="customer_name">
<?php
while($customer = mysqli_fetch_assoc($customers_set)){ ?>
<option><?php echo $customer['customer_name']; ?></option>
<?php } ?>
<?php mysqli_free_result($customers_set); ?>
</select>
</p>
<div id="input_fields">
<p><span>Product Description</span>
<select name="product_description">
<?php
while($product = mysqli_fetch_assoc($product_set)){ ?>
<option><?php echo $product['product_description']; ?></option>
<?php } ?>
<?php mysqli_free_result($product_set); ?>
</select>
<input value="0" type="text" name="quantity" />
</p>
</div>
Add More Product
<p class="radio">
<input type="radio" name="status" value="0" checked />For delivery
<input type="radio" name="status" value="1" />For payment confirmation
<input type="radio" name="status" value="2" />Reserved items
</p>
<input type="submit" name="submit" value="Create Order" />
</div>
</form>
any body have any idea how to submit all product and quantity input in input field will be save in database.
Wrap your values inside your database connection. Consider this from one of my old course. Notice is a different code however working perfectly.
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$when_it_happened = $_POST['whenithappened'];
$how_long = $_POST['howlong'];
$how_many = $_POST['howmany'];
$alien_description = $_POST['aliendescription'];
$what_they_did = $_POST['whattheydid'];
$fang_spotted = $_POST['fangspotted'];
$email = $_POST['email'];
$other = $_POST['other'];
$dbc = mysqli_connect('data.aliensabductedme.com', 'owen', 'aliensrool', 'aliendatabase')
or die('Error connecting to MySQL server.');
$query = "INSERT INTO aliens_abduction (first_name, last_name, when_it_happened, how_long, " .
"how_many, alien_description, what_they_did, fang_spotted, other, email) " .
"VALUES ('$first_name', '$last_name', '$when_it_happened', '$how_long', '$how_many', " .
"'$alien_description', '$what_they_did', '$fang_spotted', '$other', '$email')";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
The input fields have the same name? So I guess thats why only the last one get inserted.
You have to loop the INSERT query foreach product you add, this includes quantity.
You should allso sanitize the input value before you inserting it to a query.
When you inserting multiple queries, you shouldn't do that from the php loop. Is not efficient because you are executing multiple queries instead one or two. You can loop trough the results sent from the form, clean it and prepare it for database insertion, and after that build a query based on that results. Look at here for the inserting multiple rows at once into a database :
(Insert multiple rows with one query MySQL)
you need to use foreach
foreach ($_POST['quantity'] as $quantity) {
//insert code
}
I have a list which is displayed from my database:
<<b>List</b>
<?php
$select = "SELECT * FROM quabits.inregistrare";
$result2 = mysql_query($select);
?>
<form id="raport" name="save">
<table cellspacing='0' cellpadding='0'>
<tr><td>Selectează: </td>
<td><select name="den" id="den" onchange="rulare(this.value)">
<option value="">Selectați un profesor</option>
<?php
while($row=mysql_fetch_array($result2)){
echo "<option value='" . $row['Email'] ."'> " .$row['Nume'] ." ". $row['Prenume'] ."</option>";
}?>
</select>
</td></tr>
</table>
</form>
<input id="save" name="save" type="submit" value="Submit" action="POST"/>
After the drop down menu I put a button to submit.
And after a value is selected and click for submit, I want to save into my database (quabits table inregistrare) the value.
Here I'm lost. Any help ?
If you have a select like the following:
<select name="den" id="den" onchange="rulare(this.value)">
<option value="">Selectați un profesor</option>
.....
</select>
You would retrieve the value of the select using $_REQUEST['den'].
Make sure you add the method type to your form, for example
<form id="raport" name="save" method="POST">
in PHP you would store the POST value:
$den = $_POST['den'];
$den = $_POST['den'];
$link = mysqli_connect("host","user","password","database",3306
$sql = "Insert into table ('fieldname') VALUES ('$den');
mysqli_query($link,$sql);
Very basic solution, but i the question is not very understandable....
I have a page that displays the data of a mysql entry, depending on the link the user clicked ($pagename).. Im wondering how I can create a very basic rating system, that will consist of a form with drop down options of 1 to 5, and when the user submits this value, it posts the data to the corresponding ID of the entry thats currently on the page.
<?php
$pagename = $_GET['name'];
$sql = "SELECT * FROM tblCocktail WHERE name = '$pagename' LIMIT 1";
/*$sql = sprintf(%sql, mysql_real_escape_string($pagename));*/
$result = mysql_query($sql);
if(!$result) {
// error occured
}
$data = mysql_fetch_assoc($result);
echo "<p class=\"paratitle\">".$data["name"]." </p>";
echo "<p class=\"paratitle3\">".$data["howto"]." </p>";
echo "<p class=\"paratitle2\">".$data["ingredient1"]." </p>";
echo "<p class=\"paratitle3\">".$data["quantity1"]." </p>";
echo "<p class=\"paratitle2\">".$data["ingredient2"]." </p>";
echo "<p class=\"paratitle3\">".$data["quantity2"]." </p>";
echo "<p class=\"paratitle2\">".$data["ingredient3"]." </p>";
echo "<p class=\"paratitle3\">".$data["quantity3"]." </p>";
echo "<p class=\"dateadded\">".$data["dateadded"]." </p>";
?>
</div>
</div>
<div id="cont2">
<div id="contentwrap">
<form method="POST" action="addrating.php" >
<input type="hidden" name="cocktailID" value="<?=$data["id"]?>">
<select id="ratinglevel" name="ratinglevel">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
<input type="submit" value="submit" />
</form>
addrating.php:
<?php
mysql_select_db("mwheywood", $con);
//insert cocktail details
$sql="INSERT INTO tblRating (cocktailID, value, counter)
VALUES
('$_POST[id]','$_POST[ratinglevel]','1'";
if (!mysql_query($sql,$con))
{
die('Error: you fail at life' . mysql_error());
}
echo "<p>Thanks for voting</p>"
?>
the table I want to save the rating into is linked via "cocktailID" to the data that is being echo'd in the above code.
and the table structure of "tblRating" is: ratingID, cocktailID, value, counter..
I therefore want the option value to save to the corresponding "cocktailID", in the "value" field, and a "1" posted to the counter field.
-any help is appreciated -matt
Just include the current ID when you send teh form like this
<form method="POST" action="addrating.php" >
<input type="hidden" name="cocktailID" value="<?=$data["id"]?>">
<select id="ratinglevel" name="ratinglevel">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</form>
This will then return the ID along with the form results at which time you will have the cocktailID available
if (isset($_POST['cocktailID']) && isset($_POST['ratinglevel']))
$sql = "INSERT INTO tblRating SET cocktailID = ".mysql_real_escape_string($_POST['cocktailID']).", value = ".mysql_real_escape_string($_POST['ratinglevel']).",counter = 1";
$result = mysql_query($sql);
if(!$result) {
// error occured
}
}