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
Related
So I am trying to make an undetermined amount of bindParam calls within a foreach, but for some reason it fails. I know the $sql variable is working fine, but I am pretty sure it is failing at the bindParam. Is there any reason for this?
$sql = "INSERT INTO " . $row1["rand"] . " (" . $areas . ") VALUES (" . $vals . ")";
echo $sql;
$entry2 = $conn->prepare("'".$sql."'");
//echo "swag";
foreach($splitHeader as $element){
if(strlen($element)>0) {
$thisVal = "':" . $element . "'";
$entry2->bindParam($thisVal,$_POST[$element]);
}
}
$entry2->execute();
The number of parameters that you define in the query must match the number of parameters that you bind.
You would need to loop twice trough your data : once to dynamically construct a sql statement (that you can then prepare), and then a second time to bind the parameters, before finally calling execute.
Here is an adaptation of your code that demonstrates the principle :
$cols = "";
$vals = "";
foreach( $splitHeader as $element ) {
if( strlen($element) > 0 ) {
if ( strlen($cols) > 0 ) {
$cols .= ", ";
$vals .= ", ";
}
$cols .= $element;
$vals .= "?";
}
}
$sql = "INSERT INTO " . $row1["rand"] . " (". $cols . ") VALUES(". $vals . ")";
echo $sql;
$sth = $conn->prepare($sql);
$i = 1;
foreach($splitHeader as $element){
if( strlen($element) > 0 ) {
$sth->bindParam( $i, $_POST[$element] );
$i++;
}
}
$sth->execute();
the IPN works for putting the order details in, etc. But I'm trying to get the item_numbers back to MySQL table.. and I can't see where I'm going wrong. And I can't work out how to log my _POSTs. I'm guessing it's just not finding any item_numbers...but I can't get the _POST variables to see what exactly's coming in.
$oID = $_POST['txn_id']; // joins o and oItems
$n = 1;
while (TRUE)
{
if (isset(${"_POST['item_number" . $n . "']"}))
{$item_numbers[] = ${"_POST['item_number" . $n . "']"};}
else {break;}
$n++;
}
$n = 1;
foreach ($item_numbers as $key => $item_number)
{
$pID = $item_number;
$pAmount_o = ${"_POST['mc_gross_" . $n . "']"};
$pQuantity = ${"_POST['quantity" . $n+1 . "']"};
$q = "INSERT INTO `oItems` (ID, pID, pAmount_o, oID, pQuantity) VALUES ('', '$pID', '$pAmount_o', '$oID', '$pQuantity')";
mysqli_query($c, $q);
$n++;
}
And I can't tell what's going on with this log either.. :(
$t = time();
$post = serialize(print_r($_POST));
$q = "INSERT INTO `ipnLogs` (`logID`, `logTime`, `logType`, `logContent`) VALUES ('', '$t', '_POST', '$post')";
mysqli_query($c, $q);
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.
I need to save the values from my dynamic textbox in different tables at the same time. Can someone help me do this? I have 4 tables that needs to be filled. This is my tables and its fields:
table1
- desk_id
- desk_user
- desk_report
- desk_action
table2
- print_id
- print_brand
- print_model
- print_report
- print_action
table3
- tel_id
- tel_local
- tel_user
- tel_report
- tel_action
table4
- remarks_id
- remarks
My PHP code:
<?php
$con = mysql_connect ("localhost","root","nasi") or die
('cannot connect to database error: '.mysql_error());
if (isset($_POST['desk_user']) &&
isset($_POST['desk_report']) &&
isset($_POST['desk_action']) &&
isset($_POST['print_brand']) &&
isset($_POST['print_model']) &&
isset($_POST['print_report']) &&
isset($_POST['print_action']) &&
isset($_POST['tel_local']) &&
isset($_POST['tel_user']) &&
isset($_POST['tel_report']) &&
isset($_POST['tel_action']) &&
isset($_POST['remarks']))
{
$desk_user = $_POST['desk_user'];
$desk_report = $_POST['desk_report'];
$desk_action = $_POST['desk_action'];
$print_brand = $_POST['print_brand'];
$print_model = $_POST['print_model'];
$print_report = $_POST['print_report'];
$print_action = $_POST['print_action'];
$tel_local = $_POST['tel_local'];
$tel_user = $_POST['tel_user'];
$tel_report = $_POST['tel_report'];
$tel_action = $_POST['tel_action'];
$remarks = $_POST['remarks'];
if (!empty($desk_user)&& !empty($desk_report)&& !empty($desk_action) && !empty($print_brand) && !empty($print_model) && !empty($print_report) && !empty($print_action) && !empty($tel_local) && !empty($tel_user) && !empty($tel_report) && !empty($tel_action) && !empty($remarks)) {
mysql_select_db("csr", $con);
$queries = array();
for($i=0; $i<count($desk_user || $print_brand || $tel_local || $remarks); $i++)
{
$queries [] = "('" .$desk_user [$i ] . "', '" .$desk_report [$i ] . "', '" .$desk_action [$i ] . "')" ;
$queries1 [] = "( '" .$print_brand [$i ] . "', '" .$print_model [$i ] . "', '" .$print_report [$i ] . "', '" .$print_action [$i ] . "')" ;
$queries2 [] = "('" .$tel_local [$i ] . "', '" .$tel_user [$i ] . "', '" .$tel_report [$i ] . "', '" .$tel_action [$i ] . "')" ;
$queries3 [] = "('" .$remarks [$i ] . "')" ;
}
if(count($queries) == 0)
{
# Nothing passed
# exit
}
$query = "insert into desktoplaptop (desk_user, desk_report, desk_action tel_local) values " . implode(", ", $queries) ;
$query1 = "insert into printer (print_brand, print_model, print_report, print_action) values " . implode(", ", $queries1) ;
$query2 = "insert into tel (tel_user, tel_report, tel_action) values " . implode(", ", $queries2) ;
$query3 = "insert into remarks (remarks) values " . implode(", ", $queries3) ;
if ($sql_run = mysql_query($query) || $sql_run = mysql_query($query1) || $sql_run = mysql_query($query2) || $sql_run = mysql_query($query3)) {
echo 'ok.';
}
else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}
}
?>
If there are four tables, there needs to be a unique INSERT statement for each one. With the code you provided, you only name one table: desktoplaptop
If there actually are four unique tables as suggested by your list above, you will need to write a unique INSERT statement which refers to each table's schema.
For example:
$queries = array();
if(!empty($desk_user)) {
$queries[] = "INSERT into desktop (desk_user, desk_report, desk_action) VALUES ('" . $desk_user . "', '" .$desk_report . "', '" . $desk_action . "')'";
}
repeat for other 3 tables
foreach($queries as $query) {
if ($sql_run = mysql_query($query)) {
echo 'ok.';
} else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}
Note that if you are taking input from a web form, you will also want to mysql_escape_string() each $_POST variable to prevent injection. In addition, it seems you are using the count() function incorrectly-- you are passing it a Boolean expression when it expects an array. Overall I would suggest taking another look over exactly how your code operates.
Do four INSERT as a loop?
$query[0] = "INSERT INTO TABLE1 (...) VALUES (...)";
$query[1] = "INSERT INTO TABLE2 (...) VALUES (...)";
//etc...
foreach ($query as $x)
{
if ($sql_run = mysql_query($x)) {
echo 'ok.';
} else {
echo '*Sorry, we couldn\'t register you at this time. Try again later.';
}
}
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