I if have inputs like this one, but those 2 inputs are repeating themselves multiple times. So it could be:
<input name="Gpodaciogolubu[]" type="text">
<input name="Gpodaciogolubu_godina[]" type="number">
<input name="Gpodaciogolubu[]" type="text">
<input name="Gpodaciogolubu_godina[]" type="number">
<input name="Gpodaciogolubu[]" type="text">
<input name="Gpodaciogolubu_godina[]" type="number">
...
Is it possible to use while or foreach loop to get both values at the same time and insert it both in database like:
"INSERT INTO database (field1, filed2) VALUES ('$_POST["Gpodaciogolubu"]','$_POST["Gpodaciogolubu_godina"]')"
I'm coding in PHP/MySQL
First build an array of rows to insert:
$rows = []; // or array() in PHP 5.3 and older
$l = count($_POST['Gpodaciofolubu']);
for( $i=0; $i<$l; $i++) {
$rows[] = "("
."'".mysql_real_escape_string($_POST['Gpodaciofolubu'][$i])."', "
.intval($_POST['Gpodaciofolubu_godina'][$i]) // since you have `type="number"`
.")";
}
Then batch insert them:
mysql_query("insert into `database` (`field1`, `field2`) values ".implode(",",$rows));
This assumes, of course, that you're using the mysql extension. This assumption is based on the complete lack of any attempt to sanitize your input.
Related
Here is a example of what my form looks like.
<div>
<input name="address[1][name]" type="text">
<input name="address[1][street]" type="text">
<input name="address[1][city]" type="text">
<input name="address[1][phone]" type="text">
</div>
<div>
<input name="address[2][name]" type="text">
<input name="address[2][street]" type="text">
<input name="address[2][city]" type="text">
<input name="address[2][phone]" type="text">
</div>
...
I'd like to increment the data obtained from each block in PHP and increment it into my database with MySQL.
What is the best way to achieve this ?
I know it generates arrays, but I do not know how to deal with the "double-bracket" method (the form "aaa[x][bbb]" probably has a proper name, which I do not know, I'm sorry).
Thanks.
If you want to iterate over all fields using double brackets, the best structure to use are nested foreach's:
$formdata = $_POST['address'];
foreach($formdata as $group)
{
$SQLFields = array();
$SQLValues = array();
foreach($group as $field => $value)
{
// Here you have each individual field inside each group, so you can
// build the fields of the INSERT statement.
$SQLFields[] = $field;
$SQLValues[] = $value;
}
// Now assemble everything, and your INSERT is ready.
$SQL = "insert into table (".
implode(", ", $SQLFields).
") values ('".
implode("', '", $SQLValues).
"')";
// Run the SQL statement the way you want.
}
I think you are looking for something like this:
$data = $_POST['address'];
foreach($data as $address) {
//your address-object (name, street, city, phone)
var_dump($address);
//Add your sql-query in here and DO NOT forget to escape your received data
}
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 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.
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.
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.