Inserting multiple row in database using php form - php

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
}

Related

Inserting an array of checkbox values into a database including unchecked

In the form below, students are selected from student table in my DB. For each student selected a checkbox is checked if the student is absent and left unchecked if the student is present. The form is later on submitted for it to be inserted in the exam_status table in my DB.
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
while($row= $result->fetch_assoc())
{
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="matricule[]" value="<?php echo "$studentmatricule)"; ?>" readonly>
<label>Name</label>
<input type="text" name="name[]" value="<?php echo "{$studentname} {$studentsurname}"; ?>" readonly>
<label > Absent
<input type="checkbox" name="absent[]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
</form>
and my action page "action.php" is as follows
$matricule = $_POST['matricule'];
$absent=$_POST['absent'];
for ($i=0; $i<sizeof($matricule); $i++)
{
if($absent[$i]=='absent')
{
$status='absent';
}else{
$status='present';
}
$query = "INSERT INTO exam_status (student_matricule,status) VALUES ('". $matricule[$i] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
Now the issue is it doesn't just work as i want. the result always gives the first student absent and the rest present. I have tried all i can and have really researched too but with no success at all. Please anyone around to help me out?
Thanks in advance!
<form method="POST" action="action.php">
<?php
$query = "SELECT * from student ORDER BY student_name,student_surname";
$result=mysqli_query($conn,$query);
if(false===$result)
{
printf("error: %s \n",mysqli_error($conn));
}
$index = 0;
while($row= $result->fetch_assoc())
{
$index++;
$studentmatricule = $row['student_matricule'];
$studentname = $row['student_name'];
$studentsurname = $row['student_surname'];
?>
<div id="studentdiv">
<label>Matricule</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][matriculate]" value="<?php echo $studentmatricule; ?>" readonly>
<label>Name</label>
<input type="text" name="studenInfo[<?php echo $index; ?>][name]" value="<?php echo $studentname." ".$studentsurname; ?>" readonly>
<label > Absent
<input type="checkbox" name="studenInfo[<?php echo $index; ?>][status]" value="absent" />
</label>
</div> <br><br>
<?php
}
?>
<input type="submit" name="submit" value="submit">
Update your mail file like this. I have changed the form names into a single array. The reason is the checkbox values won't post to the page when the values are not checked. So its not possible to track which one was checked and which is not if you have same name.
And update your action.php like this,
<?php
$conn = mysqli_connect("localhost","username","password","db_name"); // update this values as per your configuration
$studenInfo = (!empty($_POST['studenInfo'])) ? $_POST['studenInfo'] : [];
foreach($studenInfo as $value ) {
$status = (isset($value['status'])) ? 'absent' : 'present';
$query = "INSERT INTO exam_status (student_name, student_matricule,status) VALUES ('". $value['name'] . "','". $value['matriculate'] . "','". $status . "')";
$result=mysqli_query($conn,$query);
}
?>
I have used my own table schema where i have added student_name in exam_status table for better tracking. Now you can see the values updating correctly. Also we can use bulk insert if we need to insert multiple data (Note : I haved used the bulk insert in this answer, i just followed the way you used)

Insert details of a form in to MySQL Table based on number of selected options

I have a form by which i use to send mails to users.
<form method="post" action="/functions/mails/mailstomysql.php">
<?php
$sql="SELECT UserId, FatherName, FirstName FROM profiles";
echo "<div class='FieldTitle' style='display:none;'>To</div>";
echo "
<div class='ui segment'>
<div class='ui fluid multiple search selection dropdown'>
<input type='hidden' multiple name='ReceiverId[]' required>
<i class='dropdown icon'></i>
<input class='search' tabindex='0'>
<div class='default text'>To</div>
<div class='menu' tabindex='-1'>
"; // list box select command
foreach ($conn->query($sql) as $row){//Array or records stored in $row
echo "
<option class='item' data-value='".$row['UserId']."' value='".$row['UserId']."'>$row[FirstName] s/o $row[FatherName]</option>";
}
echo "
</div>
</div>
</div>
?>
<input type="text" name="MailSubject">
<textarea type="text" name="MailContent"></textarea>
<input id="btnAddRecord" name="submit" type="submit" value="Send">
</form>
This is the SQL Statement that retrieve the data for above form:
$sql="SELECT UserId, FirstName FROM profiles";
And this is the mailtomysql.php file which insert the data into MySQL database.
$ReceiverId=$_POST['ReceiverId'];
$MailSubject=$_POST['MailSubject'];
$MailContent=$_POST['MailContent'];
$sql = "INSERT INTO mails (
`ReceiverId`, `MailSubject`, `MailContent`, `MailRead`, `MailDate`
)
VALUES (
'$ReceiverId', '$MailSubject', '$MailContent', '1', CURRENT_TIMESTAMP()
)";
if ($conn->query($sql) === TRUE) {
echo "Mail sent!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
The above code works awesome and perfect.
My Question
The above mailtomysql.php file insert the selected users from Multiple Selection Box and post the selected user ids to ReceiverId column which i do not want that, instead i want to have row for every selected user.
like:
Now
ReceverId
114, 265, 112
What i want
ReceverId
114
256
112
Why
If a user want to delete the mail then it will delete the mail and other users which are in that mail will not see the mail too because it is deleted by a user.
So once more my question is how to make mailtomysql.php file to make row for every selected users rather than having selected users ids in one row.
Edited:
I used the Semantic-Ui to select the options from the dropdown list, but it is not working.
On form side:
<form method="post" action="/functions/mails/mailstomysql.php">
<select multiple name='ReceiverId[]'>
<?php foreach ($conn->query($sql) as $row){
echo "<option class='item' data-value='".$row['UserId']."' value='".$row['UserId']."'>". $row['FirstName'] . "</option>";
} ?>
</select>
<input type="text" name="MailSubject">
<textarea type="text" name="MailContent"></textarea>
<input id="btnAddRecord" name="submit" type="submit" value="Send">
Make sure the value is set in the option and the name of the select is ReceiverId[].
On the receiving end, this will result into only one query...
$ReceiverIds = $_POST['ReceiverId'];
$values = "";
foreach($ReceiverIds as $receiver){
//don't forget some validation here...
//this is potentially unsafe too since the values are not properly escaped. Perform proper escaping here...
$values .= "('$receiver', '$MailSubject', '$MailContent', '1', CURRENT_TIMESTAMP()
),\n";
}
$values = rtrim($values, ",\n");
$sql = "INSERT INTO mails (
`ReceiverId`, `MailSubject`, `MailContent`, `MailRead`, `MailDate`
)
VALUES
$values";
$success = $conn->query($sql)
foreach($ReceiverId as $item){
$sql = "INSERT INTO mails (
`ReceiverId`, `MailSubject`, `MailContent`, `MailRead`, `MailDate`
)
VALUES (
'$item', '$MailSubject', '$MailContent', '1', CURRENT_TIMESTAMP()
)";
$success = $conn->query($sql)
}`

null column in protection from sql injection

hi i am having a contact form in my website where user can optionaly fill some of the fields and after click on submit button data save in to the database all of this worked fine until i decide to sanitize my code from sql injection as i mentioned at first before trying to sanitize it from sql injection it worked properly as i showed in below code
<form method="Post" action="">
<input type="text" name="name" />name
<select dir="rtl" style="width: 173px;" name="case" >
<option value="" disabled selected hidden>اplease choose</option>
<option value='rent'>rent</option>
<option value='sell'>sell</option>
</select >
<input type="checkbox" name="check1" value='a'>apartment<br>
<input type="submit" value="submit" />
</form>
<?php
include("config.php");
if(isset($_POST['submit'])){
$date_clicked = date('Y-m-d H:i:s');
}
//insert to database
$insert =mysqli_query($connect,"INSERT INTO $db_table VALUES (to simplify code i do not write this part)");
}
?>
now i have to fill all the dropdown lists and checkboxes otherwise it gives error "column '' can not be null". also i can not insert date and time into database it gives the same error. here is my code when i protect it fron sql injection:
<form method="Post" action="">
<input type="text" name="name" />name
<select dir="rtl" style="width: 173px;" name="case" >
<option value="" disabled selected hidden>اplease choose</option>
<option value='rent'>rent</option>
<option value='sell'>sell</option>
</select >
<input type="checkbox" name="check1" value='a'>apartment<br>
<input type="submit" value="submit" />
</form>
<?php
include("config.php");
if(isset($_POST['submit'])){
$date_clicked = date('Y-m-d H:i:s');
}
if(isset($_POST['submit'])){
//insert to database
$query = mysqli_prepare($connect, "INSERT INTO $db_table VALUES (?,?,?,?)");
/* bind parameters for markers */
mysqli_stmt_bind_param( $query, "ssss", $_POST[name],$_POST['check1'],$_POST['case'],$_POST['date_clicked']);
// execute query
if ( mysqli_stmt_execute($query) ) {
echo "Successfully inserted " . mysqli_affected_rows($connect) . " row";
} else {
echo "Error occurred: " . mysqli_error($connect);
}
}
?>
please help me
Make sure that your variables exist. This is necessary because your checkbox, for example, will be null if not checked and that could be a problem for the table you are using. You could set defaults and then insert it.
$name = !empty($_POST['name']) ? $_POST['name'] : '';
$check1 = !empty($_POST['check1']) ? $_POST['check1'] : '';
$case = !empty($_POST['case']) ? $_POST['case'] : '';
$date_clicked = date('Y-m-d H:i:s');
// prepare and bind
$stmt = $connect->prepare("INSERT INTO `$db_table` (`name`, `check1`, `case`, `date_clicked`) VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $name, $check1, $case, $date_clicked);
$stmt->execute();
$stmt->close();

PHP: populated fields and database insert

i have Form what populate fields from database, can you show me php to insert data to database, each score to own row in database (id,name,score)
Updated: whit theis codes it prints like this:
lines updated to database: 7 - James - 15
lines updated to database: 7 - James - 15
lines updated to database: 7 - James - 15
now i use this form:
<form action="insert_action2.php" id="form2" title="form2" method="post">
<table>
<?php
$link = mysqli_connect("localhost", "form", "form", "form");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM form2" ;
$players = $link->query($sql);
while($player = $players->fetch_assoc()){
?>
<tr>
<td>
<input type="text" name="id" id="id" value="<?php echo $player["id"]; ?>">
<input type="text" name="name" id="name" value="<?php echo $player["name"]; ?>">
</td>
<td>
<input type="text" name="score" id="score" size="2" value="<?php echo $player["score"]; ?>">
</td>
</p>
<?php
}
$link->close();
?>
</tr>
</table>
<input type="submit" value="update scores">
</form>
insert to database -insert_action2.php
i have tried couple arrays and foreach but cant get those working right...
<?php
foreach($_POST as $players => $value) {
$id = mysqli_real_escape_string($link, $_POST['id']);
$name = mysqli_real_escape_string($link, $_POST['name']);
$score = mysqli_real_escape_string($link, $_POST['score']);
$sql = "UPDATE form2 SET score='$score', name='$name' WHERE id=$id";
if(mysqli_query($link, $sql)){
echo "lines updated to database: <br>$id - $name - $score <br><br><p><p>";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
mysqli_close($link);
?>
You'll need to use:
$sql = "insert into `form2`(`name`, `score`) VALUES ('{$name}', '{$score}')";
When you use some variable inside a string, you need to scape the variable.
Or use this way:
$sql = "insert into `form2`(`name`, `score`) VALUES ('" . $name . "', '" . $score . "')";

after submit of form, get ID of entry into another table

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.

Categories