I'm building a website where people can place orders and this is the first time I've had to insert multiple rows at a time and I'm lost. I know that I need a FOR loop to perform this, but I'm lost as to how to construct the loop. I'm using PHP, MySQL (obviously) with jQuery. I'm using the jQuery to .append() a new select box into the form to allow the client to choose another item.
This is how I usually construct my code to allow users to insert into the database. My question is how and where would I insert a loop that way multiples rows can be submitted all at once without having to insert them one by one. Anything would be helpful, thank you.
<?php
if (isset($_POST['submit'])) {
if (!$_POST['col1'] | !$_POST['col2'] | !$_POST['col3']) { die ("error"); }
if (!get_magic_quotes_gpc()) {
$_POST['col1'] = addslashes ($_POST['col1']);
$_POST['col2'] = addslashes ($_POST['col2']);
$_POST['col3'] = addslashes ($_POST['col3']);
}
$insert = "insert into table (col1, col2, col3) values ('".$_POST['col1']."', '".$_POST['col2']."', '".$_POST['col3']."')";
mysql_query ($insert);
} else {
?>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<table>
<tr>
<td><input type="text" name="col1"></td>
<td><input type="text" name="col2"></td>
<td><input type="text" name="col3"></td>
//I'm using jQuery .append() to insert more text boxes with names (col1, col2, col3) here
</tr>
</table>
<input type="submit" name="submit" value="Submit">
</form>
<?php
}
?>
My confusion is where to put the loop... I know it should be a FOR loop, but I could never get one to work. Thanks again for any help.
Be sure you name your inputs uniquely. But you can name every column like this (see here for example):
<input type="text" name="column1[]" />
<input type="text" name="column2[]" />
<input type="text" name="column3[]" />
That way you can access the columns via PHP using a for loop.
for($i = 0; $i < $n; $i++) // If you have $n rows
{
echo($_POST["column1"][$i]);
echo($_POST["column2"][$i]);
echo($_POST["column3"][$i]);
}
To insert multiple rows into your mySQL database use the following syntax (also: see here).
INSERT INTO
tbl_name (column1, column2, column3)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
Now you should be set to build your SQL query.
First thing you want to avoid is use same set of names. You may want to name them rowNcolM and then extract them where you check post variables.
Related
I am pretty stumped, I thought this would work for sure. I want to insert multiple checkbox values (if selected) into different columns of one table. I was attempting to do this with a for loop and keeping the naming convention consistent so I could utilize the for loop with the checkbox array. Here is php code:
$connection = new mysqli("localhost","root","","employee_db");
if(isset($_POST['check'])){
$check = $_POST['check'];
if($check){
print_r($check);
}else{
echo "nothing checked";
}
for($i=0;$i<sizeof($check);$i++){
$query = "INSERT INTO `checklist_test` (`$check[$i]`) VALUE (`\"$check[$i]\"`)";
$result = mysqli_query($connection,$query);
if(!$result){
die("NOPE <br>" . mysqli_error($connection));
}else{
echo "yup";
}
}
}
And here is the HTML
<form action="" method="post>
<input type="checkbox" name="check[]" value="check1">Check1
<input type="checkbox" name="check[]" value="check2">Check2
<input type="checkbox" name="check[]" value="check3">Check3
<input type="submit" value="submit">
</form>
The MySQL Columns are "id, check1, check2, check3" so SQL should look like:
INSERT INTO `checklist_test` (`id`, `check1`, `check2`, `check3`)
VALUES (NULL, 'test', 'test', 'test');
Appreciater outside P.O.V. that I need thanks!
If you the execute the query inside the loop, you would be executing x number of queries (or inserting x number of rows) rather than inserting into x number of columns. There is really no need to use a loop here since you have a set number of columns.
Use echo statements to print out the queries to see what you are running and you'll see why this isn't working.
You also should never put user input directly into a MySQL query. Read up on SQL injections.
i have this two text fields that ask the user to put in two numbers that are limited to 49 numbers, so that i can have an array of number 1 to 50, or 151 to 200, or 27551 to 27600 any number but a series of 49 consecutive numbers, my problem is i dont know how to put them inside the database, i have no clue i have been searching for everything about inserting arrays but they dont work on my case,
This is my form
<form id="form3" name="form1" method="post" action="">
<p>From:
<input type="text" name="from" id="form_number" class="from" />
- To:
<input type="text" name="to" id="form_number" class="to" />
</p>
<p>Waybill Booklet:
<select name="waybill_booklet[]" id="form_list">
<?php
do {
?>
<option value="<?php echo $row_Booklet['id_waybill_booklet']?>"><?php echo $row_Booklet['booklet_no']?></option>
<?php
} while ($row_Booklet = mysql_fetch_assoc($Booklet));
$rows = mysql_num_rows($Booklet);
if($rows > 0) {
mysql_data_seek($Booklet, 0);
$row_Booklet = mysql_fetch_assoc($Booklet);
}
?>
</select>
</p>
<p>
<input type="hidden" name="status[]" value="4" />
<input type="submit" name="button" id="form_button" value="OK!" />
</p>
</form>
the 49 series of consecutive numbers will be inserted into the database with a foreign key what is chosen from the drop down menu, and a value of 4 that is in the hidden field, so basically there are 4 columns to my table 1 for primary key 1 for the series of numbers and 1 for the foreign key and the last will be the value of the numbers.
This is my php code to get the series of numbers
<?php
$booklet = $_POST['waybill_booklet'];
$status = $_POST['status'];
$from = $_POST['from'];
$to = $_POST['to'];
$number = range($from,$to);
$count = 0;
$myArray = range($from,$to);
while($count<=49){
if($count<49){
echo $myArray[$count]. ", ";
}else{
echo $myArray[$count];
}
$count++;
}
?>
i dont know how to insert the data's
$waybill = mysql_real_escape_string($_POST['waybill_booklet'][0]);
$status = mysql_real_escape_string($_POST['status'][0]);
foreach (range($from, $to) as $number) {
$sql = "INSERT INTO yourTable (id, waybill, status) VALUES($number, '$waybill', '$status')");
mysql_query($sql) or die(mysql_error());
}
You should also switch to PDO or mysqli, so you can use parametrized queries instead of substituting strings into the query. Then you don't need to escape the values like that.
Instead of storing this as an array (since you want to store this as bulk, I assume it will not involve any direct database level aggregation or computation), you can store it as a json string using the json_encode($myArray_series_of_numbers). This gives you the flexibility to store them as a string column and when you retrieve it back, you can use json_decode($model->series_of_numbers_column,true) to get it back as an array for easy computation back in PHP.
Hope this helps
Here is a tutorial on using mysql in php http://www.w3schools.com/php/php_mysql_insert.asp specifically the INSERT command. just build your data into variables instead of echo'ing it and then follow the guide to interact with a database
here is the auto increment tutorial to generate primary ids for each array element http://www.w3schools.com/sql/sql_autoincrement.asp
you can greatly increase the speed of the inserts and do it in one submit by building a multiple insert sql string.. and then using the insert guide above to run it.
INSERT INTO Table ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )
I'm after a little help. I have a page for a user to input upto 10 different rows of information. Dispatch details. I have created a page with my form using a loop..
<?php
session_start();
require("config.php");
require("header.php");
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);
?>
<br><br><br></br>
<form action="insertdispatch.php" method="post">
<body>
<center>
<table>
<tr>
<td><center><b>Ref</td>
<td><b><center>Date</td>
<td><b><center>Service</td>
<td><b> <center>Tracking</td>
</tr>
<?php
$index = 1;
$name = 1;
while($index <= 10){
?>
<td><input type="text"
name="transno<?php echo $index;?>"
id="transno<?php echo $index;?>" />
</td>
<td><input type="text" name="date<?php echo $index;?>"
id="date<?php echo $index;?> "/>
</td>
<td><select name = "service<?php echo $index;?>"><?php
$viewsql = "SELECT * FROM dispatch_service ORDER BY service ASC";
$viewresult = mysql_query($viewsql);
while($row = mysql_fetch_assoc($viewresult)){
?> <option value=<?php echo $row['service'] ;?>>
<?php echo $row['service'] ;?></option>
<?php
}
echo "</select>";?>
<td><input type="text"
name="tracking<?php echo $index;?>"
id="tracking<?php echo $index;?>"/>
</td>
</tr>
<?php $index ++;
}?>
<center>
<td><input type="submit" value="Add Product" />
</form>
</center>
</td>
</tr>
</table>
</center>
<center><a href='javascript:history.back(1);'>Back</a>
</body>
</html>`
I have 10 of each text box, the name of the text box adds the value of index to the end. (with my limited coding experience I am very pleased with myself) so I go to the insertdispatch.php page and the plan is to insert each of these values into my table... now...I have no clue... and I cannot seem to figure out how I am going to do this...
I think I will need to use a loop again.. but I can't seem to figure out how I am going to call each of the $_POST values. I don't really want to use 10 different insert statements, as the form may increase in size. here is what I have so far..
<?php
session_start();
require("config.php");
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("hbt",$db)or do_error("Could not connect to the database");
$index = 1;
while($index <= 10){
$insertsql = "INSERT into dispatch (trans_no, date, service, tracking) values ()";
mysql_query($insertsql);
$index ++;
}
//header("Location: " . $config_basedir . "home.php");
?>
I am not looking for anyone to finish the coding for me, but any tips would be grateful! :)
you can build 1 insert statement that inserts multiple rows:
INSERT into dispatch (trans_no, date, service, tracking) values
(1, '2013-09-12', 'myService1', 'on'),
(1, '2013-09-12', 'myService2', 'on'),
(1, '2013-09-12', 'myService3', 'on'),
(1, '2013-09-12', 'myService4', 'on'),
(1, '2013-09-12', 'myService5', 'on');
Just build this inside your the while, and execute it after the while has finished.
To build this query, you will need to perform the exact same loop as when you are generating the HTML, but now just fetch the values from $_POST instead of create a html field for them...
note while building your HTML, you are firing a static query inside your for loop. since this query is static, the results will also not change, and it is best to execute that query outside of the outer while loop.
(you really should read up more on basic HTML - tehre are lots of mistakes there even before considering the PHP code).
name="transno<?php echo $index;?>"
This is really messy too - you are creating extra work and complication for yourself. Use arrays:
name="transno[]"
If you do exlpicitly want to reference the item again then set the index:
id="transno[<?php echo $index; ?>]"
And at the receiving end....use a single insert statement to add the rows - not 10 seperate ones (it will be much faster).
You've already set up your while loop with $index - you could simply use that to iterate through the POST values, since you set their name attribute with an index. Consider:
$index = 1;
while($index <= 10){
$trans_no = $_POST["transno$index"];
$service = $_POST["service$index"];
$date = $_POST["date$index"];
$tracking = $_POST["tracking$index"];
$insertsql = "INSERT into dispatch (trans_no, date, service, tracking)
VALUES($trans_no, $date, $service, $tracking)";
mysql_query($insertsql);
$index++;}
Though it would be much cleaner to set up your form inputs as arrays, as noted by others here.
Also, please read up on SQL injection. You need to sanitize any user input before it's inserted into a database - otherwise a malign user could wipe your whole database.
I have an array of checkboxes.
<input type="checkbox" name="selection[]" value="move" />
<input type="checkbox" name="selection[]" value="move2" />
<input type="checkbox" name="selection[]" value="move3" />
<input type="checkbox" name="selection[]" value="move4" />
Depending on the number of checkboxes selected, a table with corresponding number of rows is generated.
for($x=0; $x<$N; $x++)
{
echo nl2br("<td><textarea name=art[] rows=10 cols=30></textarea> </td><td><textarea name=science[] rows=10 cols=30></textarea></td></textarea></td><td><textarea name=method[] rows=10 cols=30></textarea></td><td><textarea name=criteria[] rows=10 cols=30></textarea></td></tr>");
}
I cannot tell how many table rows with corresponding columns will be generated each time. So how to write the code to insert each set of row array is a problem. I have tried the
$optionsVal = implode(",", $data);
but that only works to store the selected options and not for the generated table rows and columns.Please can anyone help with this. Thanks in advance
Okay so I think I understand a little better, but perhaps you should relay your question in other terms.
Basically my understanding is that you are accepting an uncertain (within the boundaries of the number of checkboxes you have) number of checkboxes, which there in turn generate a row for each selected check box.
If you want to store these generated rows in mySQL you need to post the data back to the database
$result = mysqli_query($query, $conn);
$row = mysqli_fetch_array($result);
You need to set a $result similar to this, and store your check box values in it
In this example if the end-user hits the save button it inserts the values from the check box into a variable
if(isset($_POST["savebtn"]))
{
//inserting the new information
$id = $_POST[""];
$name = $_POST[""];
//iterate through each checkbox selected
foreach($_POST["checkbox"] as $loc_id)
{
$query = "INSERT INTO table(ID, Loc_Code) VALUES('$id', '$loc_id')";
$result = mysqli_query($query, $conn);
}
?>
This was just kinda taken from another example, but you are way off with the implode, you need to save the results of the php selection to variables first, and then assign them rows in mySQL by looping through the selection
UPDATE:
Okay, so you got them in an array, seelction[] - this is good now you would want to check to see if a certain value is selected...
if (in_array("move2", $_POST['selection'])) { /* move2 was selected */}
then you want to put that into a single string - you were right with the implode method
echo implode("\n", $_POST['selection']);
then echo it out with a foreach loop
foreach ($_POST['selection'] as $selection) {
echo "You selected: $selection <br>";
}
Could someone tell how to write this insert into a database? The below code is an example of what I am trying to accomplish. I want to have a form for families with multiple children. They submit their family names and one id that they will share in the database. See code below...
FORM INPUTS
<input type="text" name="fname[]"/>
<input type="text" name="lname[]"/>
<input type="text" name="fname[]"/>
<input type="text" name="lname[]"/>
<input type="text" name="family_id"/>
This is where I am having troubles. I can submit the family names but only the first(row) "name" is storing the "family_id" as well.
PHP
foreach($_POST['fname'] as $key => $fname) {
$lname = $_POST['lname'][$key];
$family_id = $_POST['family_id'][$key];
$query = mysql_query("INSERT INTO Table (FName, LName, Family_ID ) VALUES ('{$fname}', '{$lname}', $_POST['family_id'])");
}
I appreciate any help!
Missing {} around $_POST['family_id'].
family_id insn't an array.
So the first iteration you get
$_POST['family_id'][0]; // gets the id
The second
$_POST['family_id'][1]; // gets undefined index
To fix it do the following.
Add the following code before foreach loop and concat $family_id to the query like you did with the others.
$family_id = $_POST['family_id'];
Try this:
extract($_POST);
$total=count($fname);
for($i=0;$i<count($total);$i++)
{
$fname=$fname[$i];
$lname=lfname[$i];
$query="INSERT INTO Table (FName, LName, Family_ID ) VALUES ('{$fname}', '{$lname}', $family_id)";
}