Am having a problem inserting multiple rows of data into a table at once. The following is what i have.When i click on submit, only the last row is inserted with only the first digit of quantity. please help.
html form:
<form method="post" action="insert.php">
<p><input type="text" id="product_id" name="product_id[]"/>
<input type="text" id="quantity" name="quantity[]"/></p>
<p><input type="text" id="product_id" name="product_id[]"/>
<input type="text" id="quantity" name="quantity[]"/></p>
<p><input type="text" id="product_id" name="product_id[]"/>
<input type="text" id="quantity" name="quantity[]"/></p>
<input type="submit" name="submit" value="submit"/>
</form>
insert.php page:
<?php
include 'config/auth.php';//database connection
if(isset($_POST['submit'])){
$product = mysqli_real_escape_string($dbc, $_POST['product_id']);
$quantity = mysqli_real_escape_string($dbc, $_POST['quantity']);
$count = sizeof($product);
for ($i=0; $i < $count; $i++) {
$Inproduct = $product[$i];
$Inquantity = $quantity[$i];
$query = "INSERT INTO sales (product_id, quantity) VALUES ('$Inproduct','$Inquantity')";
$results = mysqli_query($dbc, $query);
}
if ($results) {
echo 'Success';
}
}
?>
the following code worked... thanks #kmdm
$product = $_POST['product_id'];
$quantity = $_POST['quantity'];
$count = sizeof($product);
for ($i=0; $i < $count; $i++) {
$Inproduct = mysqli_real_escape_string($dbc, $product[$i]);
$Inquantity = mysqli_real_escape_string($dbc, $quantity[$i]);
$query = "INSERT INTO sales (product_id, quantity) VALUES ('$Inproduct','$Inquantity')";
$results = mysqli_query($dbc, $query);
}
Related
I have a html form which has 2*12 input fields with name="links[]" and name="ids[]"...
I want to update column 'link' with those 12 links using those 12 ids
I know we need a loop for that.
But don't know how to make the sql query.
$ids=mysqli_real_escape_string($conn, $_POST['ids']);
foreach($ids as $id){....}
$links=mysqli_real_escape_string($conn, $_POST['links']);
foreach($links as $link){....}
$sql="update query.....";
EDIT:
It works with two variables $id and $season but when i add more than two variable like $episode etc. it doesn't work. it doesn't execute other variable only first two are executed and it sets the values of $season to 1 or sometimes 0 of all the entries in the table.
for($i=0 ; $i<count($record['id']); $i++){
$id=mysqli_real_escape_string($conn, $record['id'][$i]);
$season=mysqli_real_escape_string($conn, $record['season'][$i]);
$episode=mysqli_real_escape_string($conn, $record['episode'][$i]);
$rel_id=mysqli_real_escape_string($conn, $record['rel_id'][$i]);
$link=mysqli_real_escape_string($conn, $record['link'][$i]);
//sQl Query
$sql = "UPDATE series SET season='$season' and episode='$episode' and rel_id='$rel_id' and link='$link' WHERE id='$id'";
if ($conn->query($sql) === TRUE) {}
else { echo "Error: " . $sql . "<br>" . $conn->error; };
Try the below code.
<form name="rec" id="rec" method="post">
<input type="text" name="reord[id][]">
<input type="text" name="reord[season][]">
<input type="text" name="reord[episode][]">
<input type="text" name="reord[rel_id][]">
<input type="text" name="reord[link][]">
<br/>
<input type="text" name="reord[id][]">
<input type="text" name="reord[season][]">
<input type="text" name="reord[episode][]">
<input type="text" name="reord[rel_id][]">
<input type="text" name="reord[link][]">
<br/>
<input type="text" name="reord[id][]">
<input type="text" name="reord[season][]">
<input type="text" name="reord[episode][]">
<input type="text" name="reord[rel_id][]">
<input type="text" name="reord[link][]">
</br>
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit'])){
$record = $_POST['reord'];
$id = $season = $episode = $rel_id = $link = '';
for($i=0 ; $i<count($record['id']); $i++){
$id= mysqli_real_escape_string($conn, $record['id'][$i]);
$season=mysqli_real_escape_string($conn, $record['season'][$i]);
$episode=mysqli_real_escape_string($conn, $record['episode'][$i]);
$rel_id=mysqli_real_escape_string($conn, $record['rel_id'][$i]);
$link= mysqli_real_escape_string($conn, $record['link'][$i]);
echo $sql = "UPDATE series SET season='$season' and episode='$episode' and rel_id='$rel_id' and link='$link' WHERE id=$id";
$conn->query($sql);
}
}
?>
$ids=mysqli_real_escape_string($conn, $_POST['ids']);
foreach($ids as $key => $id){
$sql="update tablename set fieldname=value where link=$_POST[links][$key] and id=$id";
}
This might work. If not give me more details.
UPDATE `tablename` SET `fieldname` = CASE
WHEN id = 1 AND xyz = 3 THEN `value 1`
WHEN id = 2 AND xyz = 3 THEN `value 2`
WHEN id = 3 AND xyz = 3 THEN `value 3`
END
In the scenario described I would use SET-WHEN-THEN query
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)
Good day.
<input type="text" name="title">
<input type="text" name="name[]">
<input type="text" name="name[]">
<?php
if(isset($_POST['submit']){
$title = $_POST['title'];
$name = $_POST['name'];
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
}
?>
How can this code work? It should be inserted with same title and different names at the same time. Thank you.
Sample Form
I want the record to be updated as follows:
---------------------------------
|--bookID--|--Title--|--Author--|
|----1-----|---one---|----me----|
|----2-----|---two---|---you----|
---------------------------------
$_POST['name'] is an array with key 0,1 ...
So in your example you ve got:
//This is just an example
foreach($_POST['name'] as $name) {
}
Hope this helps.
Atul Vekariya example is correct but you need to also execute the query in the loop. That's why this example did not work for you.
if(is_array($_POST['name']) && !empty($_POST['name'])) {
foreach($_POST['name'] as $name) {
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
//execute query here. mysqli_query($add) or PDO::query
}
}
Please check below code
if(is_array($_POST['name']) && !empty($_POST['name'])) {
foreach($_POST['name'] as $name) {
$add = "INSERT INTO books (title, name) VALUES ('$title','$name')";
//execute query here. mysqli_query($add) or PDO::query
}
}
After searching different solutions. Here is the one that works. Thank you for all the help.
<?php
include_once 'config/connect.php';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$title = $_POST['title'];
$name = $_POST['name'];
$length = count($name);
$addBook = "INSERT INTO books (title,name) VALUES ";
for($i=0; $i<$length; $i++){
$addBook .= "('$title','$name[$i]'),";
}
$addBook = rtrim($addBook, ',');
if($conn->query($addBook) === TRUE) {
echo "Success";
} else {
echo "Error: ".$addBook."<br>".$conn->error;
}
}
?>
<form action="addBook.php" method="POST">
Title: <input type="text" name="title">
<br/>
Authors: <input type="text" name="name[]"> <input type="text" name="name[]">
<br/>
<input type="submit" name="submit">
</form>
I'm having trouble extracting arrays to insert into the database. My form accepts multiple and dynamic number of inputs so I have the data in an array with inputs phonenos[] and phonetypes[]:
<form name="add" action="" method="POST">
<input name="name" type="text" placeholder="Name"></input><br />
<input name="qty" type="text" placeholder="Qty"></input><br /> -->
<input class="form-control required" name="phonenos[]" maxlength="14" type="text" placeholder="number..."><br>
<select class="form-control" name="phonetypes[]">
<option value="0">Choose a phone type</option>
<option value="Main">Main</option>
<option value="Fax">Fax</option>
<option value="Mobile/Direct">Mobile/Direct</option>
</select>
<div id="addmore">
<input type="button" value="Add More" onClick="addRow(this.form)"></input>
</div>
<input type="submit" value="submit" name="action"></input>
</form>
In my PDO query:
..... first query insertion...
$phonenos = $_POST['phonenos'];
foreach($_POST['phonenos'] as $phoneno) {
$phoneno;
}
$phonetypes = $_POST['phonetypes'];
foreach($_POST['phonetypes'] as $phonetype) {
$phonetype;
}
$sql = 'INSERT INTO phone (p_id, phoneno, phonetype) values (:p_id, :phoneno, :phonetype)';
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phoneno'=>$phoneno,
':phonetype'=>$phonetype
));
So I did a var_dump on variables $phoneno and $phonetype after a submission of multiple phone numbers and it only printed out the last number and type whereas I wanted the entire list that was submitted. How do I get all the data so I can insert it into the database?
If you want all the numbers inserted in the same column, then the best solution I can think is to serialize them before you insert in db.
$phonenos = serialize($_POST['phonenos']);
$phonetypes = serialize($_POST['phonetypes']);
$sql = 'INSERT INTO phone (p_id, phoneno, phonetype) values (:p_id, :phoneno, :phonetype)';
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phoneno'=>$phonenos,
':phonetype'=>$phonetypes
));
I figured out the solution through a for loop.
$phones = $_POST['phones'];
$phonetypes = $_POST['phonetypes'];
for($i = 0, $j = 0; $i <= $phones, $j <= $phonetypes; $i++, $j++) {
$phone = $phones[$i];
$phonetype = $phonetypes[$j];
$sql = "INSERT INTO phone (p_id, phone, phonetype) values (:p_id, :phone, :phonetype)";
$query = $conn->prepare($sql);
$query->execute( array(
':p_id'=>$lastid,
':phone'=>$phone,
':phonetype'=>$phonetype
));
}
I have this code:
<html>
<body>
<form id="myForm" method="post" action="add-data.php">
<input type="submit">
<input type="text" name="pollquestion">
<input type="text" name="polloption1">
<input type="text" name="polloption2">
</form>
Add option
<script>
var optionNumber = 3;
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "polloption"+optionNumber+""; // poll[optionX]
newOption.type = "text";
theForm.appendChild(newOption);
optionNumber++;
}
</script>
</body>
</html>
If i add more inputs i will have something like this:
<input name="pollquestion" type="text">
<input name="polloption1" type="text">
<input name="polloption2" type="text">
<input name="polloption3" type="text">
<input name="polloption4" type="text">
<input name="polloption5" type="text">
<input name="polloption6" type="text">
The php code is something like this:
$qu = $_POST['pollquestion'];
$op1 = $_POST['polloption1'];
$op2 = $_POST['polloption2'];
$query = "INSERT into `".$db_table."` (question, option1, option2) VALUES ('" . $qu . "','" . $op1 . "','" . $op2 . "')";
How can i add this data to mysql for every added row? Thanks!
One way of many...
$query = "INSERT into `$db_table` SET `question` = '".mysql_real_escape_string($_POST['pollquestion'])."'";
foreach (range(1,6) as $idx) {
if (!empty($_POST['polloption'.$idx])) {
$query .= ", `option$idx` = '".mysql_real_escape_string($_POST['polloption'.$idx])."'";
}
}
of course the mysql_real_escape_string is important to avoid http://en.wikipedia.org/wiki/SQL_injection
First, you need to know how many options you're submitting so add another constant input to the form:
<input type="hidden" id="numOptions" name="numOptions"/>
In the addOption() function update its value (before incrementing optionNumber):
document.getElementById( "numOptions" ).value = optionNumber;
On the server side you need to create your query dynamically like so:
$options = array();
$values = array();
$numOptions = intval( $_POST[ "numOptions" ] );
for ( $i = 1; $i <= $numOptions; $i++ )
{
$options[] = "option$i";
$values [] = "'" . mysql_real_escape_string( $_POST[ "polloption$i" ] ) . "'";
}
$query = "INSERT INTO $db_table(" . implode( ',', $options ) . ") VALUES( '" .
implode( ',', $values );
Please mind the escaping of the received strings! very important to prevent SQL injections.
HTML
<input name="title" type="text">
<input name="descr" type="text">
<input name="question[1]" type="text">
<input name="option[1][1]" type="text">
<input name="option[1][2]" type="text">
<input name="option[1][3]" type="text">
<input name="right[1]" type="radio" value=1>
<input name="right[1]" type="radio" value=2>
<input name="right[1]" type="radio" value=3>
<input name="question[2]" type="text">
<input name="option[2][1]" type="text">
<input name="option[2][2]" type="text">
<input name="option[2][3]" type="text">
<input name="right[2]" type="radio" value=1>
<input name="right[2]" type="radio" value=2>
<input name="right[2]" type="radio" value=3>
PHP
$title = mysql_real_escape_string($_POST['title'])
$descr = mysql_real_escape_string($_POST['descr'])
$query = "INSERT into `polls` (title,descr) VALUES ('$title', '$descr')";
$id = $db->query($query);
foreach ($_POST['question'] as $num => $q) {
$q = mysql_real_escape_string($q)
$query = "INSERT into `poll questions` (poll,question) VALUES ($id,'$q')";
$db->query($query);
foreach ($_POST['option'][$num] as $i => $opt) {
$right = ($_POST['right'][$num]) == $i)?1:0;
$opt = mysql_real_escape_string($opt)
$num = intval($num);
$query = "INSERT into `poll options` (poll,num,option,right)
VALUES ($id,$num,'$opt',$right)";
}
}
You can iterate $_POST, matching keys with regular patterns, something like that:
foreach($_POST as $key => $value) {
preg_match('/(\w+)(\d+)/Uis', $key, $m);
if($m[1] == 'polloption') {
// concatenate new values to your query
}
}
Remembering relational databases, you have fixed number of attributes in your table. So you should add fixed number of options.