JQGRID, How to post Selected rows data only once to Database? - php

Hi I have a jqgrid setup with a custom action button that sends selected rows to a database. I have everything working except that it posts the data 7 times per each row select where I only want it posted once per selected row. Please any and all help appreciated. JQGrid, How to post JSON string to PHP to Process and send to Database?
$decarr= array(
['id'] =>
518
['name'] =>
'Brochure for amada'
['id_continent'] =>
' Ramon'
['lastvisit'] =>
'5/15/2013'
['cdate'] =>
'5/29/2013'
['ddate'] =>
'5/31/2013'
['email'] =>
'Files'
)
PHP:
//First decode the array
$arr = $_POST["json"];
$decarr = json_decode($arr, true);
$count = count($decarr);
$values = array(); // This will hold our array values so we do one single insert
for ($x=0; $x < $count; $x++){
$newrec = $decarr;
$id = $newrec['id']; $id = mysql_real_escape_string($id);
$name = $newrec['name']; $name = mysql_real_escape_string($name);
$id_continent = $newrec['id_continent']; $id_continent = mysql_real_escape_string($id_continent);
$email = $newrec['email']; $email = mysql_real_escape_string($email);
$lastvisit = $newrec['lastvisit']; $lastvisit = mysql_real_escape_string($lastvisit);
$cdate = $newrec['cdate']; $cdate = mysql_real_escape_string($cdate);
$ddate = $newrec['ddate']; $ddate = mysql_real_escape_string($ddate);
// Create insert array
$values[] = "('".$id."', '".$name."', '".$id_continent."', '".$lastvisit."','".$cdate."','".$ddate."','".$email."' )";
}
// Insert the records
$sql = "INSERT INTO finish (id, name, id_continent, lastvisit,cdate,ddate, email)
VALUES ".implode(',', $values);
$result = mysql_query($sql, $con) or die(mysql_error());
?>

Fixed! I figured out the the variables were reiterated over and over with the other lines. Much love y'all.
//First decode the array
$arr = $_POST["json"];
$decarr = json_decode($arr, true);
$count = count($decarr);
for ($x=0; $x < $count; $x++){
$newrec = $decarr;
$id = $newrec['id'];
$name = $newrec['name'];
$id_continent = $newrec['id_continent'];
$email = $newrec['email'];
$lastvisit = $newrec['lastvisit'];
$cdate = $newrec['cdate'];
$ddate = $newrec['ddate'];
}
// Create insert array
$values[] = "('".$id."', '".$name."', '".$id_continent."', '".$lastvisit."','".$cdate."','".$ddate."','".$email."' )";
// Insert the records
$sql = "INSERT INTO finish (id, name, id_continent, lastvisit,cdate,ddate, email)
VALUES ".implode(',', $values);
$result = mysql_query($sql, $con) or die(mysql_error());
?>

Related

How to fetch record to sum upto a value and then add into two new tables?

I am trying to sum (add the values) from the database. My application checks the values from each row, adds up the value from each row up to 2000. And once it reaches up to 2000, it saves in the database (insert query) and continues the same till last record fetched. The total value summed (or totaled) up by each rows should not exceed over 2000.
There are two insert queries, One for inserting the total( from each row between 1800 and 2000) with the ID (like Primary key) generated and the second table add each row inserted with ID (the ID generated becomes now foreign key)
Please refer to the screenshot.
Please find the code below:
$i = 1;
do {
$id = $row_FetchRecordRS['ID'];
$dateissued = $row_FetchRecordRS['DateIssued'];
$rundateCarrierRun = $row_FetchRecordRS['RundateCarrierRunID'];
$timegenerated = $row_FetchRecordRS['TimeGenerated'];
$carrierID = $row_FetchRecordRS['CarrierRunID'] ;
$areaID = $row_FetchRecordRS['CarrierAreaID'];
$address = $row_FetchRecordRS['DeliveryAddress'];
$potzone = $row_FetchRecordRS['Postzone'];
$carr_ID = $row_FetchRecordRS['CarrierID'];
$instruction = $row_FetchRecordRS['DeliveryAddress'];
$areaRep = $row_FetchRecordRS['AreaRepDetails'];
// $vendor = $row_FetchRecordRS['VendorDetails'];
$quantity = $row_FetchRecordRS['Quantity'];
$direct = $row_FetchRecordRS['Direct'];
$jobID = $row_FetchRecordRS['JobID'];
$jobName = $row_FetchRecordRS['JobName'];
$bundlesize = $row_FetchRecordRS['Bundlesize'];
$bundle = $row_FetchRecordRS['Bundles'];
$items = $row_FetchRecordRS['Items'];
$weight = $row_FetchRecordRS['WeightKgs'];
$totalWeightCol = $row_FetchRecordRS['TotalWeightKgs'];
$date = date("D M d, Y G:i");
$total_weight = $row_FetchRecordRS['FinalWeight'] + $total_weight ;
echo "Row: " .$row_FetchRecordRS['FinalWeight']. "<br>";
echo "Total is______ $i : $total_weight <br><br>";
$sqlquerytest = "INSERT INTO `GenerateRun`
(`DateIssued`, `RundateCarrierRunID`, `TimeGenerated`,
`CarrierRunID`, `CarrierAreaID`, `DeliveryAddress`, `Postzone`,
`CarrierID`, `DeliveryInstruction`, `AreaRepDetails`,
`Quantity`, `Direct`, `JobID`, `JobName`, `Bundlesize`,
`Bundles`, `Items`, `WeightKgs`, `TotalWeightKgs`,
`LodingZoneID`)
VALUES
('$dateissued', '$rundateCarrierRun', '$timegenerated',
'$carrierID', '$areaID', '$address', '$potzone', '$carr_ID',
'$instruction', '$areaRep', '$quantity', '$direct', '$jobID',
'$jobName', '$bundlesize', '$bundle', '$items', '$weight',
'$totalWeightCol','$i')";
mysql_select_db($database_callmtlc_SalmatDB, $callmtlc_SalmatDB);
$ResultUpd1 = mysql_query($sqlquerytest, $callmtlc_SalmatDB) or die(mysql_error());
if ($total_weight >= 1800) {
$sqltransitlist = " INSERT INTO `TransitList`(`genID`, `total`) Values ('$i','$total_weight')";
mysql_select_db($database_callmtlc_SalmatDB, $callmtlc_SalmatDB);
$ResultUpd3 = mysql_query($sqltransitlist, $callmtlc_SalmatDB) or die(mysql_error());
$i = $i+1;
$total_weight = 0;
}
} while($row_FetchRecordRS = mysql_fetch_assoc($FetchRecordRS));
Some of your line of codes are irrelevant to your problem. I will simplify it for you.
$i = 1;
$total = 0;
$arr = array(); // for storing a list of data provides that the total doesn't exceed 2000
while ($row = mysql_fetch_assoc($record)) {
$id = $row['id'];
$name = $row['name'];
$num = $row['num'];
$arr[] = array('id' => $id, 'name' => $name, 'num' => $num);
if ($num + $total > 2000) {
$sql = "INSERT INTO Table1(genID, total) Values ('$i','$total')";
mysql_query($sql) or die(mysql_error());
foreach ($arr as $data) {
$sql = "INSERT INTO Table2(ID, name, genID, total) Values ('$data[id]','$data[name]','$i','$data[num]')";
mysql_query($sql) or die(mysql_error());
}
$arr = array(); // empty the array as the data has been stored to database
$i++;
$total = 0;
} else { // if the total doesn't exceed 2000, add it to total
$total += $num;
}
}
$sql = "INSERT INTO Table1(genID, total) Values ('$i','$total')";
mysql_query($sql) or die(mysql_error());
foreach ($arr as $data) {
$sql = "INSERT INTO Table2(ID, name, genID, total) Values ('$data[id]','$data[name]','$i','$data[num]')";
mysql_query($sql) or die(mysql_error());
}
Note: this code is just a sample, not your actual code. You can implement my code and match it to your code.

How to insert data from a PHP Array to MySQL

I am trying to insert data from an Array to MySQL Database. The Database contains two columns (string). Here is the code I wrote. What is wrong?
<?php
$time = date("H:i:s");
$a = array("foo", "bar", "hallo", "world");
//convert values of the array to string
$a = array_map('strval', $a);
//get array size
$arraySize = count($a);
//connection to database
$link = mysql_connect('', '', '') or die('connection lost');
mysql_select_db() or die('DB not found');
//try to insert data from the array to the database
for ($i = 0; $i < $arraySize; $i++) {
mysql_query("INSERT INTO `` (`time`, `text`) VALUES ('$time','$a[i]'))");
}
mysql_close($link);
?>
I cleared some personal data in the code intentionally.
Here is your answer..! Hope it works for you
$contentArray = [];
$rows = array();
$time = date("H:i:s");
$rows[] = array( "foo", "bar", "hallo", "world");
$fields = json_encode($rows);
array_push($contentArray,$fields,$time);
$values[] = '(' . placeholders('?', 2) . ')';
$field_names = "text,time";
$sql = "INSERT INTO table_name (" . $field_names . ") VALUES " . implode(',', $values);
Try this
remove the $a = array_map('strval',$a)
for(){
inside the for loop
$value = (string)$a[i];
$sql = "INSERT INTO $tablename (time,text) VALUES ('$time', '{$value}') ";
mysql_query($sql);
$value = "";
}
The problem is with this part of code:
VALUES ('$time','$a[i]')
I missed $ before i.
Also this part of code may be droped without any problems:
$a = array_map('strval', $a);

PHP: Inserting Multiple array into mysql table

I am testing multiple array insertion into my table, I have try all what I could but I am not getting.Here is my code:
<?php
ini_set('display_errors',1);
//ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$mysqli = new mysqli(HOST,USER,PASS,DB);
$message = array();
$id =1;
$SocialHandle = "Facebook,Twitter,LinkIn";
$SociaUrl ="Url1,Url2,Url3";
$strSocialHandle = explode(',', $SocialHandle);
$strSociaUrl = explode(',', $SociaUrl);
print_r($strSocialHandle);
print_r($strSociaUrl);
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES";
foreach($strSocialHandle as $SocialNameValue){
$sql .= "({$id}, '{$SocialNameValue}','{$strSociaUrl}'),";
}
$sql = rtrim($sql, ',');
$result = $mysqli->query($sql);
if (!$result){
$message = array('Message' => 'insert fail or record exist');
echo json_encode($message);
}else{
$message = array('Message' => 'new record inserted');
echo json_encode($message);
}
?>
Here is my goal achievement:
ID social handle
handle url 1 Facebook
url1 1
Twitter url2 1
LinkIn
url3
Please help.
You can use for loop for it as
$id =1;
$SocialHandle = "Facebook,Twitter,LinkIn";
$SocialHandle = explode(",", $SocialHandle);
$SociaUrl = "Url1,Url2,Url3";
$SociaUrl = explode(",", $SociaUrl);
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES";
for ($i = 0; $i < count($SocialHandle); $i++) {
$sql .= "({$id}, '$SocialHandle[$i]','$SociaUrl[$i]'),";
}
$sql = rtrim($sql, ',');
echo $sql;
$result = $mysqli->query($sql);
OUTPUT
INSERT INTO social_table(id, social_handle, handle_url)
VALUES(1, 'Facebook','Url1'),(1, 'Twitter','Url2'),(1,
'LinkIn','Url3')
DEMO
UPDATED
Better use prepare and bind statement to prevent form sql injection as
for ($i = 0; $i < count($SocialHandle); $i++) {
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES (?,?,?)";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('iss', $id, $SocialHandle[$i], $SociaUrl[$i]);
$stmt->execute();
}
You're only looping over $strSocialHandle - the $strSociaUrl array isn't affected by the loop, so will still be an array rather than an individual value. You can store the two lists in a single key-value array, and use one loop to iterate over both:
<?php
$id = 1;
$social = [
'Facebook' => 'Url1',
'Twitter' => 'Url2',
'LinkIn' => 'Url3',
];
$sql = "INSERT INTO `social_table`(`id`, `social_handle`, `handle_url`) VALUES";
foreach($social as $handle => $url) {
$sql .= "({$id}, '{$handle}','{$url}'),";
}
echo rtrim($sql, ',');

For loop only loop one time

i have this code, suppose loop 5 time but it only loop one time only. How to make sure it will loop 5 time?.
for ($i = 0; $i < 5;)
{
$sql6 = "SELECT * FROM at_agent_management WHERE piam_reg = '$checkedValuesarr[$i]'";
$result6 = mysql_query($sql6);
while($row6 = mysql_fetch_array($result6)){
$reg = $row6['piam_reg'];
$date = $row6['piam_date'];
$agency = $row6['agency_name'];
$branch = $row6['branch'];
$category = $row6['agent_category'];
//$template_id = $reg_count;
$sql7 = "INSERT INTO at_agent_view_receipant(piam_reg, piam_date, agency_name, branch, agent_category, template_id) VALUES ('$reg', '$date', '$agency', '$branch', '$category', '$reg_count')";
$result7 = mysql_query($sql7);
}
$i++;
}
From logic you have written,
There is checkbox values array and you want to use that value in Query.
You can try with Foreach Loop as below,
<?
$checkedValuesarr=array("1","2","3","4","5");
foreach ($checkedValuesarr as $checkValue)
{
$sql6 = "SELECT * FROM at_agent_management WHERE piam_reg = '".$checkValue."'";
$result6 = mysql_query($sql6);
while($row6 = mysql_fetch_array($result6)){
$reg = $row6['piam_reg'];
$date = $row6['piam_date'];
$agency = $row6['agency_name'];
$branch = $row6['branch'];
$category = $row6['agent_category'];
//$template_id = $reg_count;
$sql7 = "INSERT INTO at_agent_view_receipant(piam_reg, piam_date, agency_name, branch, agent_category, template_id) VALUES ('$reg', '$date', '$agency', '$branch', '$category', '$reg_count')";
$result7 = mysql_query($sql7);
}
}?>

How to get multiple parameters with same name from a URL in PHP and insert all records into table

I'm using MySQL query to insert multiple records into table.
In my url i get all records that i have entered but in database it only updates my last record. I am using here onclick function to add new table rows. Any help.
Here is my code
if (isset($_GET['submit']))
{
require_once("shine_class.php");
$s = new shine;
$s->connection();
$date1 = date_default_timezone_set('Asia/Kolkata');
$date1= time() ;
$newdate1 = date("d-m-Y", $date1);
for ($i=0; $i < count($_GET['finished_product_name']); $i++ )
{
$product =$_GET['finished_product_name'];
$material = $_GET['material_name'];
$quantity = $_GET['product_quantity'];
// mysql_query("INSERT INTO material_used (product_name, material_name, product_quantity, date) VALUES ('$a', '$b', '$c','$newdate1')") or die(mysql_error());
$insert ="insert into material_used set `product_name` = '".$product."', `material_name` = '".$material."', `product_quantity` = '".$quantity."',`date` = '".$newdate1."' ";
$select = mysql_query($insert) or die(mysql_error());
}
}
You try to assign a value with same name.so your last value replace with the existing value.
for example :your URL look like,
http://www.example.com/index.php?finished_product_name=abc&material_name=xxx&finished_product_name=pqr&material_name=yyy
so your $_GET['finished_product_name'] has value is pqr not abc.
If you can change the field name with include [], then PHP will create an array containing all of the matching values:
http://www.example.com/index.php?id[]=123&version[]=3&id[]=234&version[]=4
your URL example like,
http://www.example.com/index.php?finished_product_name[]=abc&material_name[]=xxx&finished_product_name[]=pqr&material_name[]=yyy
your for loop is :
for ($i=0; $i < count($_POST['finished_product_name']); $i++ )
{
$product =$_POST['finished_product_name'][$i];
$material = $_POST['material_name'][$i];
$quantity = $_POST'product_quantity'][$i];
}
$insert ="insert into material_used(product_name,material_name,product_quantity,date) VALUES( '$product', '$material','.$quantiy','$newdate1')
use following function to insert data in DB
$data['col1']='value1';
$data['col2']='value2';
.
.
$data['coln']='valuen';
insert('table_name',$data);
function Insert( $table, $condition )
{
$sql = "INSERT INTO `$table` SET ";
$content = null;
foreach ( $condition as $k => $v )
{
$v_str = null;
if ( is_numeric($v) )
$v_str = "'{$v}'";
else if ( is_null($v) )
$v_str = 'NULL';
else
$v_str = "'" . mysql_real_escape_string($v) . "'";
$content .= "`$k`=$v_str,";
}
$content = trim($content, ',');
$sql .= $content;
return $result = mysql_query($sql);
}

Categories