Inserting an array to mysql using php - php

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 )

Related

Insert Checkbox Array into Multiple MySQL table Columns with PHP

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.

PHP foreach Construct Confusion

I am having a hard time wrapping my head around the foreach construct. I have found numerous examples of course, but I never seem to be able to adapt them to my needs.
Please consider this working example I have:
I am collecting two dates in an HTML form:
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" name="FirstAGMDate" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" name="MinutesInspectedFromDate" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
On submit the values are being pushed to the mysql database with a PDO prepared statement:
if (isset($_POST['submit'])) {
$sql = "UPDATE jobsinglevalues SET Date = :FirstAGMDate WHERE FormId = 0;
UPDATE jobsinglevalues SET Date = :MinutesInspectedFromDate WHERE FormId = 1;";
$sth = $db->prepare($sql);
$sth->execute(array(':FirstAGMDate'=>($_POST['FirstAGMDate']), ':MinutesInspectedFromDate'=>($_POST['MinutesInspectedFromDate'])));
}
This works no problem, but it's not very clever when I need to repeat this for a dozen inputs. What I want to do is achieve this with only one line of sql; looping for each <input type="text" name="Value" />.
How can I place this into a foreach loop?
In my head it works like this:
On submit each input updates the value in the database based on FormId, which increments by 1 each loop starting at 0. FormId is not a primary key, it simply mirrors the order in which the form elements are displayed.
Update - working example
if (isset($_POST['submit'])) {
$FormId = 0;
foreach($_POST['Value'] as $avalue){
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId";
$sth = $db->prepare($sql);
$sth->execute(array(':Value'=>($avalue), ':FormId'=>($FormId)));
++$FormId;
}
}
This seems to logically work to me! Is the correct solution similar? Please let me know if I need to clarify anything.
Thankyou,
Sam
Let's start by making sure all our values are in an array after posted; if you don't care about the keys you can just use name="Values[]", but I'll use name="Value[FirstAGMDate]" etc so we know what key a value belongs to.
<form method="post">
<legend>Minutes and Records</legend>
<label for="FirstAGMDate">First AGM Date (only if known)</label>
<input type="text" id="FirstAGMDate" name="Value[FirstAGMDate]" value="2014-01-01" />
<label for="MinutesInspectedFromDate">Minutes Inspected From Date</label>
<input type="text" id="MinutesInspectedFromDate" name="Value[MinutesInspectedFromDate]" value="2014-01-02" />
<input type="submit" name="submit" />
</form>
Now we can process the posted array of values. If we want to do something with the key, we can use foreach($_POST['Value'] as $akey => $avalue), if we are only interested in the values then foreach($_POST['Value'] as $avalue) suffices.
$sql = "UPDATE jobsinglevalues SET Date = :Value WHERE FormId = :FormId;";
$sth = $db->prepare($sql);
foreach($_POST['Value'] as $akey => $avalue) {
$sth->execute(array(':Value' => $avalue, ':FormId'=> $FormId ));
++$FormId;
}
[edit] As per edit-suggestion by #AravindKishore, creating the prepared statement is better done before the loop. Prepare once, enjoy forever.

Inserting auto incremented fields into a SQL database

I have some simple PHP code that will generate new text boxes with the naming scheme of 'car_init$i' and 'car_num$i'. Where $i = 1 and I use i++ to increment it up. The problem I'm having is that while a user can have a maximum of 70 text boxes generated, it can be any number between 1 and 70. So I can have 46 text boxes as an example on a page if the user wanted just 46. So I would have car_num1, car_num2, car_init1, car_init2, etc. as my form names.
Car_ID would be my auto-incremented primary key, and I'd have 2 columns car_num and car_init. Is it possible to do something like this: INSERT INTO dbo (car_init, car_num) VALUES (car_init$i, car_num$i) and then use $i = 1 and i++ to increment it while adding all the values to new rows? Car_id = 1 would contain car_num1 and car_init1 information in their respective columns, Car_id = 2 would contain car_num2 and car_init2 information, and so on and so forth.
EDIT:
So this is the code I have now:
$car_num = $_POST["car_num"];
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
}
What happens is every time I add to my database, only the last thing I entered gets inputted. So if I have 3 cars needed, that's 6 text boxes, but only the last text boxes on the page are the ones that get inputted.
EDIT 2: This is how my text boxes are generated. All text boxes have it the way you said, using the 'car_init[]' and 'car_num[]'.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$i = 1;
while ($i <= $_POST['carAmount'] AND $i <= 70) {
// Now print the text box to the screen
echo "<b>$i</b>. Car Initial: <input type=\"text\" class='element text small' name=\"car_init[]\" maxlength='4' id='car_init[]' /> ";
echo "Number: <input type=\"text\" class='element text small' name=\"car_num[]\" maxlength='6' id='car_num[]' /><br>";
$i++;
}
}
Ah, I think I got it.
This is a problem:
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
}
I assume you're then running the query $sql? If so, that is running only the last value $sql contained! You need to:
foreach($_POST['car_init'] as $key => $car_init)
{
// your insert query
$sql = "INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')";
// actually run the query!
}
Change your html to something like this:
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
<input name="car_init[]" />
Then in php, your variable will be an array!
$_POST['car_init'] // is an array!
Loop through those and do multiple INSERTs.
foreach ($_POST['car_init'] as $car_num => $car_init) {
// "INSERT INTO dbo (car_init, car_num) VALUES ('$car_init', $car_num)"
}
Edit based on your updates:
INSERT INTO CustBill_cars (C_ID, car_init, car_num) VALUES ('1', '".$car_init."', '".$car_num[$key]."')"
Use PDO with prepared statements instead of using string interpolation. You seem to be susceptible to sql injection attacks.

how do you store multiple rows and column array in mysql

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>";
}

Inserting Multiple Rows with PHP & MySQL

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.

Categories