I want to insert data in database with dynamic php variable and when I check the script in database I have only one record :(
$low_0 = 0;
$low_1 = 1;
$low_2 = 2;
$nr = 9;
for ($i = 0; $i < $nr; $i++) {
$sql = 'INSERT INTO prognoza_curenta (ora, prognoza, min, max, reg_date)
VALUES (' . "${'low_' . $i}, " . "11," . "22," . "33," . "'$timp')";
echo "$sql" . "<br>";
}
if (mysqli_query($db, $sql)) {
echo 'Data send' . "<br>";
} else {
echo 'Error send.' . mysqli_error($sql) . "<br>";
}
Change your loop to this:
$sql = 'INSERT INTO prognoza_curenta (ora, prognoza, min, max, reg_date) VALUES';
for ($i = 0; $i < $nr; $i++) {
$sql .= ' (' . "${'low_' . $i}, " . "11," . "22," . "33," . "'$timp')";
}
The Solution With prepared Statement:
$stmt = $conn->prepare("INSERT INTO prognoza_curenta (ora, prognoza, min, max, reg_date) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param("sssss", $ora, $prognoza, $min, $max, $reg_date);
// set parameters and execute
for ($i = 0; $i < $nr; $i++) {
$ora= ${'low_' . $i};
$prognoza= "11";
$min= '22';
$max = '33';
$reg_date = $timp;
$stmt->execute();
}
As Suggested by #MarkBaker, This is procedure of prepare statement. Please let me know.
Related
I am trying to insert the data to the database by fetching them first, doing some additions and then setting a condition in the loop, if the value exceeds over > 2200. Inside this if condition, I have a for each loop where it will take all the records fetched and insert into the 2nd table. I am getting it right so far, now the problem is the remaining value from the table fetched, does not insert into the new tables. Please find the screenshot attached (yellow cells). I want to also make them save and inserted in both the tables and assign a value to it.
Code
if (isset($_POST["genRun"])) {
$total_weight = 0;
$i = 1;
$arr = array();
$excess = 0;
mysql_select_db($database_callmtlc_SalmatDB, $callmtlc_SalmatDB);
while($row_FetchRecordRS = mysql_fetch_assoc($FetchRecordRS)) {
$id = $row_FetchRecordRS['ID'];
$carr_ID = $row_FetchRecordRS['CarrierID'];
$address = $row_FetchRecordRS['DeliveryAddress'];
$potzone = $row_FetchRecordRS['Postzone'];
$instruction = $row_FetchRecordRS['DeliveryInstruction'];
$quantity = $row_FetchRecordRS['Quantity'];
$jobID = $row_FetchRecordRS['JobID'];
$jobName = $row_FetchRecordRS['JobName'];
$bundlesize = $row_FetchRecordRS['Bundlesize'];
$bundle = $row_FetchRecordRS['Bundles'];
$items = $row_FetchRecordRS['Items'];
$weight = $row_FetchRecordRS['WeightKgs'];
$suburb = $row_FetchRecordRS['Suburb'];
$num = $row_FetchRecordRS['TotalWeightKgs'];
//$num = $row_FetchRecordRS['TotalWeightKgs'];
$arr[] = array('CarrierID' => $carr_ID, 'DeliveryAddress' => $address, 'Postzone' => $potzone, 'DeliveryInstruction' => $instruction, 'Quantity' => $quantity, 'JobID' => $jobID, 'JobName' => $jobName, 'Bundlesize' => $bundlesize, 'Bundles' => $bundle, 'Items' => $items, 'WeightKgs' => $weight, 'Suburb' => $suburb, 'TotalWeightKgs' => $num);
if ($num + $total > 2200) {
$sqltransitlist = "INSERT INTO TransitList(genID, total) Values ('$i','$total')";
$ResultUpd3 = mysql_query($sqltransitlist, $callmtlc_SalmatDB);
foreach ($arr as $data) {
$sqlquerytest = "INSERT INTO GenerateRun(CarrierID, DeliveryAddress, Postzone,DeliveryInstruction, Quantity, JobID, JobName,
Bundlesize, Bundles, Items, WeightKgs, Suburb, TotalWeightKgs,LodingZoneID) VALUES('"
. $data['CarrierID'] ."','" . $data['DeliveryAddress'] ."','" . $data['Postzone'] . "','" . $data['DeliveryInstruction']. "','" .$data['Quantity'] . "','" . $data['JobID'] . "','" . $data['JobName'] . "','" . $data['Bundlesize']. "','" .$data['Bundles'] . "','" . $data['Items'] . "','" .$data['WeightKgs']. "','" . $data['Suburb']."','" .$num."','" .$i ."')";
$ResultUpd1 = mysql_query($sqlquerytest, $callmtlc_SalmatDB);
}
$arr = array();
$i++;
$total = 0;
} else {
$total += $num;
}
}
// after the loop check if there are some data was not inserted and insert it after the loop is over
if ($total > 0) {
$sqltransitlist = "INSERT INTO TransitList(genID, total) Values ('$i','$total')";
$ResultUpd3 = mysql_query($sqltransitlist, $callmtlc_SalmatDB);
foreach ($arr as $data) {
$sqlquerytest = "INSERT INTO GenerateRun(CarrierID, DeliveryAddress, Postzone,DeliveryInstruction, Quantity, JobID, JobName,
Bundlesize, Bundles, Items, WeightKgs, Suburb, TotalWeightKgs,LodingZoneID) VALUES('"
. $data['CarrierID'] ."','" . $data['DeliveryAddress'] ."','" . $data['Postzone'] . "','" . $data['DeliveryInstruction']. "','" .$data['Quantity'] . "','" . $data['JobID'] . "','" . $data['JobName'] . "','" . $data['Bundlesize']. "','" .$data['Bundles'] . "','" . $data['Items'] . "','" .$data['WeightKgs']. "','" . $data['Suburb']."','" .$num."','" .$i ."')";
echo "$i , $total <br>";
$ResultUpd1 = mysql_query($sqlquerytest, $callmtlc_SalmatDB);
}
}
Output which I am getting it now: (When we add these total, the total is less than the required output)
Required Output: (when we do the loop < 2200, its not saving the value over 2200)
SQL"
and thats the sql :
SELECT UpdatedCsvFiles.ID, UpdatedCsvFiles.CarrierID, UpdatedCsvFiles.DeliveryAddress, UpdatedCsvFiles.Postzone, UpdatedCsvFiles.DeliveryInstruction, UpdatedCsvFiles.Quantity, UpdatedCsvFiles.JobID, UpdatedCsvFiles.JobName, UpdatedCsvFiles.Bundlesize, UpdatedCsvFiles.Bundles, UpdatedCsvFiles.Items, UpdatedCsvFiles.WeightKgs, SuburbPostZone.Suburb, UpdatedCsvFiles.TotalWeightKgs FROM UpdatedCsvFiles LEFT JOIN SuburbPostZone on SuburbPostZone.areaID = UpdatedCsvFiles.CarrierID Where UpdatedCsvFiles.DeliveryAddress != 'PLEASE LEAVE IN WAREHOUSE' GROUP by UpdatedCsvFiles.CarrierID, UpdatedCsvFiles.DeliveryAddress ORDER by UpdatedCsvFiles.CarrierID , SuburbPostZone.Suburb, UpdatedCsvFiles.ID ASC
Here is kind pseudo code:
// select db just once before the loop, you don't need to select db every time in the loop
mysql_select_db($database_callmtlc_SalmatDB, $callmtlc_SalmatDB);
// use while loop
while($row_FetchRecordRS = mysql_fetch_assoc($FetchRecordRS)) {
$id = $row_FetchRecordRS['ID'];
...
if ($num + $total > 2200) {
$sqltransitlist = "INSERT INTO TransitList(genID, total) ...";
$ResultUpd3 = mysql_query($sqltransitlist, $callmtlc_SalmatDB);
foreach ($arr as $data) {
$sqlquerytest = "INSERT INTO GenerateRun(CarrierID ...";
$ResultUpd1 = mysql_query($sqlquerytest, $callmtlc_SalmatDB);
}
$arr = array();
$i++;
$total = 0;
}
$total += $num;
$arr[] = array('CarrierID' => $carr_ID, 'DeliveryAddress'...);
}
// after the loop check if there are some data was not inserted and insert it after the loop is over
if ($total > 0) {
$sqltransitlist = "INSERT INTO TransitList(genID, total) ...";
$ResultUpd3 = mysql_query($sqltransitlist, $callmtlc_SalmatDB);
foreach ($arr as $data) {
$sqlquerytest = "INSERT INTO GenerateRun(CarrierID ...";
$ResultUpd1 = mysql_query($sqlquerytest, $callmtlc_SalmatDB);
}
}
NOTE You should stop using deprecated mysql_* functions. And you should use prepared statements with mysqli or PDO functions to avoid sql injections
How can I prevent SQL injection in PHP?
NOTE After chat some pseudocode to keep here: https://ideone.com/vRr5rA
I have an HTML form that has 2 dynamic fields which are:
<input type="text" name="ingredients[]" placeholder="Ingredients"/></div>
<input type="text" name="quantity[]" placeholder="Quantity"/></div>
Look here this is how the db table should be for those inputs in the form
Ing 1 1001 1KG
Ing 2 1001 2KG
ing 3 1001 3KG
now check the image and you'll see what's happening
DB Ingredients TABLE
I have the recipe-ID in my php file I just want a PDO code that help me to INSERT "ingredients", "quantity" and "$recipe_ID" each one on a row.
<?php
header('Content-type: application/json');
require_once 'db/pdoconnect.php';
if($_POST)
{
$sth = $con->prepare("SELECT `recipeid` FROM Recipes ORDER BY `recipeid` DESC");
$sth->execute();
$previousid = $sth->fetchColumn();
$offset=1;
$generatingid=$previousid+$offset;
$newid=$generatingid;
//print("Last Id=$previousid\n");
//print("New Id=$newid\n");
$title = $_POST['title'];
$preptime = $_POST['preptime'];
$cocktime = $_POST['cocktime'];
$level = $_POST['level'];
$serving = $_POST['serving'];
$recipetype = $_POST['recipetype'];
$intro = $_POST['intro'];
$details = $_POST['details'];
$image = $_POST['image'];
try
{
$stmt = $con->prepare("INSERT INTO Recipes (recipeid,title,preptime,cocktime,level,serving,recipetype,intro,details,recipeimg) VALUES( :newid, :title, :preptime, :cocktime, :level, :serving, :recipetype, :intro, :details, :image)");
$stmt->bindParam(":newid",$newid);
$stmt->bindParam(":title",$title);
$stmt->bindParam(":preptime",$preptime);
$stmt->bindParam(":cocktime",$cocktime);
$stmt->bindParam(":level",$level);
$stmt->bindParam(":serving",$serving);
$stmt->bindParam(":recipetype",$recipetype);
$stmt->bindParam(":intro",$intro);
$stmt->bindParam(":details",$details);
$stmt->bindParam(":image",$image);
if($stmt->execute()) { //check if main query has been executed
$sql = "INSERT INTO Ingredients VALUES";
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$sql .= " (:recipeid" .$i. ", :ingredient" .$i. ", :quantity" .$i. "),";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindParam(':recipeid' .$i , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$i , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$i , $varQnty , PDO::PARAM_STR);
}
if ($sth->execute()) {
$response_array['status'] = 'success';
}
}//END OF FIRST IF STATEMENT
else{
$response_array['status'] = 'error';
}
echo json_encode($response_array); //SEND THE RESPONSE
}//END OF TRY
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
Assuming the table's name shown in the image you posted in your question ingredient_quantity in your database, and you said you already have the recipe-ID PHP Fiddle
<?php
$newid = 'A10';
//considering this is your table shown in the picture
$sql = "INSERT INTO ingredient_quantity VALUES";
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$sql .= " (:newid" .$i. ", :ingredient" .$i. ", :quantity" .$i. "),";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindParam(':newid' .$i , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$i , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$i , $varQnty , PDO::PARAM_STR);
}
$sth->execute();
?>
EDIT 1:
for the above code I have an error as the ingredients[] array starts from 0 and not 1, the final index of the for loop will be undefined, so work around it make the last for loop like the following:
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$j = $i + 1;
$sth->bindParam(':newid' .$j , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$j , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$j , $varQnty , PDO::PARAM_STR);
}
EDIT 2:
You may try doing it with ? placeholders instead of named placeholders like this PHP Fiddle 2:
//considering this is your table shown in the picture
$sql = "INSERT INTO ingredient_quantity VALUES";
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$sql .= " ( ? , ? , ? ) , ";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
$j = 1;
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindValue( $j , $varIng);
$sth->bindValue( $j + 1, $newid);
$sth->bindValue( $j + 2, $varQnty);
$j += 3;
}
$sth->execute();
I have an HTML form that has 2 dynamic fields which are:
<input type="text" name="ingredients[]" placeholder="Ingredients"/></div>
<input type="text" name="quantity[]" placeholder="Quantity"/></div>
Look here this is how the db table should be for those inputs in the form
Ing 1 1001 1KG
Ing 2 1001 2KG
ing 3 1001 3KG
now check the image and you'll see what's happening
DB Ingredients TABLE
I have the recipe-ID in my php file I just want a PDO code that help me to INSERT "ingredients", "quantity" and "$recipe_ID" each one on a row.
<?php
header('Content-type: application/json');
require_once 'db/pdoconnect.php';
if($_POST)
{
$sth = $con->prepare("SELECT `recipeid` FROM Recipes ORDER BY `recipeid` DESC");
$sth->execute();
$previousid = $sth->fetchColumn();
$offset=1;
$generatingid=$previousid+$offset;
$newid=$generatingid;
//print("Last Id=$previousid\n");
//print("New Id=$newid\n");
$title = $_POST['title'];
$preptime = $_POST['preptime'];
$cocktime = $_POST['cocktime'];
$level = $_POST['level'];
$serving = $_POST['serving'];
$recipetype = $_POST['recipetype'];
$intro = $_POST['intro'];
$details = $_POST['details'];
$image = $_POST['image'];
try
{
$stmt = $con->prepare("INSERT INTO Recipes (recipeid,title,preptime,cocktime,level,serving,recipetype,intro,details,recipeimg) VALUES( :newid, :title, :preptime, :cocktime, :level, :serving, :recipetype, :intro, :details, :image)");
$stmt->bindParam(":newid",$newid);
$stmt->bindParam(":title",$title);
$stmt->bindParam(":preptime",$preptime);
$stmt->bindParam(":cocktime",$cocktime);
$stmt->bindParam(":level",$level);
$stmt->bindParam(":serving",$serving);
$stmt->bindParam(":recipetype",$recipetype);
$stmt->bindParam(":intro",$intro);
$stmt->bindParam(":details",$details);
$stmt->bindParam(":image",$image);
if($stmt->execute()) { //check if main query has been executed
$sql = "INSERT INTO Ingredients VALUES";
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$sql .= " (:recipeid" .$i. ", :ingredient" .$i. ", :quantity" .$i. "),";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindParam(':recipeid' .$i , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$i , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$i , $varQnty , PDO::PARAM_STR);
}
if ($sth->execute()) {
$response_array['status'] = 'success';
}
}//END OF FIRST IF STATEMENT
else{
$response_array['status'] = 'error';
}
echo json_encode($response_array); //SEND THE RESPONSE
}//END OF TRY
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
Assuming the table's name shown in the image you posted in your question ingredient_quantity in your database, and you said you already have the recipe-ID PHP Fiddle
<?php
$newid = 'A10';
//considering this is your table shown in the picture
$sql = "INSERT INTO ingredient_quantity VALUES";
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$sql .= " (:newid" .$i. ", :ingredient" .$i. ", :quantity" .$i. "),";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
for($i = 1 ; $i <= count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindParam(':newid' .$i , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$i , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$i , $varQnty , PDO::PARAM_STR);
}
$sth->execute();
?>
EDIT 1:
for the above code I have an error as the ingredients[] array starts from 0 and not 1, the final index of the for loop will be undefined, so work around it make the last for loop like the following:
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$j = $i + 1;
$sth->bindParam(':newid' .$j , $newid , PDO::PARAM_STR);
$sth->bindParam(':ingredient' .$j , $varIng , PDO::PARAM_STR);
$sth->bindParam(':quantity' .$j , $varQnty , PDO::PARAM_STR);
}
EDIT 2:
You may try doing it with ? placeholders instead of named placeholders like this PHP Fiddle 2:
//considering this is your table shown in the picture
$sql = "INSERT INTO ingredient_quantity VALUES";
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$sql .= " ( ? , ? , ? ) , ";
}
// remove the last (,) from the $sql
$sql = rtrim($sql, ',');
$sth = $con->prepare($sql);
// binding parameters
$j = 1;
for($i = 0 ; $i < count($_POST['ingredients']) ; $i++){
$varIng = $_POST['ingredients'][$i];
$varQnty = $_POST['quantity'][$i];
$sth->bindValue( $j , $varIng);
$sth->bindValue( $j + 1, $newid);
$sth->bindValue( $j + 2, $varQnty);
$j += 3;
}
$sth->execute();
I have a MySQL statement that I want to execute and inside this statement I would like to include a for loop to define the columns that data will be entered into etc.
The code I currently have is
$stmt = $conn->prepare('INSERT into DATA ('.
for($i = 0; $i < count($columns); $i++) {
echo $columns[$i];
}
.') VALUES ('.
for($i = 0; $i < count($columns); $i++) {
echo ':'.$columns[$i].' , ';
}
.')');
Obviously this doesn't work but if it was to work also in the second for statement it echos a comma at the end of each loop, which will cause an error for the last loop so also is there a way to fix this to?
Thanks in advance!
Use the join/implode function:
$params = array_map(function($var){return ':'.$var;}, $columns);
$sql = 'INSERT into DATA ('.join(',', $columns).') VALUES ('.join(',', $params).')';
$stmt = $conn->prepare($sql);
Another approach using implode:
$sql = "INSERT into DATA (`" . implode('`,`', $columns) . "`) values (:" . implode(',:', $columns) . ")"
$stmt = $conn->prepare($sql);
Example result:
// Input array
$columns = array('A', 'B', 'C');
// Output
INSERT into DATA(`A`,`B`,`C`) values (:A,:B,:C)
You should create the query outside of the prepare() function to make it easier.
Something like that would be better/clearer :
$count = count ($columns); // Avoid using count in your loop init (Performances)
$query = 'INSERT INTO DATA (' .
for($i = 0; $i < $count; $i++) {
$query .= $columns[$i];
}
$query .= ') VALUES (';
for($i = 0; $i < $count; $i++) {
if ($i != $count - 1) $query.= ':'.$columns[$i].' , ';
else $query .= ':'.$columns[$i]; // No coma for the last value
}
$query .= ')';
$stmt = $conn->prepare($query);
Hi I'm really new to php/mysql.
I'm working on a php/mysql school project with 39 fields all in all in a single table.
I want to shorten my codes especially on doing sql queries.
$sql = "INSERT into mytable ('field_1',...'field_39') Values('{$_POST['textfield_1']}',...'{$_POST['textfield_39']}')";
I don't know how to figure out this but , i want something like:
$sql = "Insert into mytable ("----all fields generated via loop/array----") Values("----all form elements genrated via loop/array---")";
Thank you in advance.
<?php
function mysql_insert($table, $inserts) {
$values = array_map('mysql_real_escape_string', array_values($inserts));
$keys = array_keys($inserts);
return mysql_query('INSERT INTO `'.$table.'` (`'.implode('`,`', $keys).'`) VALUES (\''.implode('\',\'', $values).'\')');
}
?>
For example:
<?php`enter code here`
mysql_insert('cars', array(
'make' => 'Aston Martin',
'model' => 'DB9',
'year' => '2009',
));
?>
try this it i thhink it il work
You could use implode:
$sql = "
INSERT into mytable
('" . implode("', '", array_keys($_POST) . "')
VALUES
('" . implode("', '", $_POST . "')";
(This assumes the indices of the POST array are also the names of the db table fields)
However, this is extremely insecure since you would directly insert post data into the database.
So the least you should do beforehand is escape the values and make sure they are ok/valid table fields:
// Apply mysql_real_escape_string to every POST value
array_walk($_POST, "mysql_real_escape_string");
and
// Filter out all POST values with invalid indices
$allowed_fields = array('field_1', 'field_2', /* ... */ );
$_POST = array_intersect_key($_POST, $allowed_fields);
<?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "'" . $_POST[textfield_$i] . "'";
} else {
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
?>
< ?php
$sql = "Insert into mytable (";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
$sql .= "field_$i";
} else {
$sql .= "field_$i,";
}
}
$sql .= "Values(";
for ($i = 1; $i < 40; $i++) {
if ($i == 39) {
if(is_int($POST[textfield$i])){
$sql .= $POST[textfield$i];
}
else{
$sql .= "'" . $POST[textfield$i] . "'";
}
} else {
if(is_int($_POST[textfield_$i])){
$sql .= $_POST[textfield_$i] .",";
}
else{
$sql .= "'" . $_POST[textfield_$i] . "',";
}
}
}
?>
it will work for numeric values. you can insert numeric values in single quotes but some times it will create some problems