How To Loop SQL Insert for many data On PHP - php

I have many data on array, in this case I must insert on SQL one by one... can you help me to solve this? I want it to sort insert data... I use manual insert... can you give me solution to foreach or looping SQL?
$user_id = getUserId();
$current_dttm = getSQLDate();
$org_id = $_SESSION["ehr_org_id"];
$id = $this->getInosId();
list($patient_id,$inf_id,$num,$tindakan_id,$denum)=$args;
$inf_id = explode('%7C',$inf_id);
$inf_id_1 = $inf_id[0];
$inf_id_2 = $inf_id[1];
$inf_id_3 = $inf_id[2];
$inf_id_4 = $inf_id[3];
$inf_id_5 = $inf_id[4];
$inf_id_6 = $inf_id[5];
$inf_id_7 = $inf_id[5];
$num = explode('%7C',$num);
$num_1 = $num[0];
$num_2 = $num[1];
$num_3 = $num[2];
$num_4 = $num[3];
$num_5 = $num[4];
$num_6 = $num[5];
$num_7 = $num[6];
$tindakan_id = explode('%7C',$tindakan_id);
$tindakan_id_1 = $tindakan_id[0];
$tindakan_id_2 = $tindakan_id[1];
$tindakan_id_3 = $tindakan_id[2];
$tindakan_id_4 = $tindakan_id[3];
$tindakan_id_5 = $tindakan_id[4];
$tindakan_id_6 = $tindakan_id[5];
$tindakan_id_7 = $tindakan_id[6];
$denum = explode('%7C',$denum);
$denum_1 = $denum[0];
$denum_2 = $denum[1];
$denum_3 = $denum[2];
$denum_4 = $denum[3];
$denum_5 = $denum[4];
$denum_6 = $denum[5];
$denum_7 = $denum[6];
$sql_inf_1 = "insert into xocp_ehr_pencatatanInos (id,patient_id,org_id,inf_id,num,tindakan,denum,pengali,tgl_kejadian,created_dttm,created_user,status_cd)"
." values('$id','$patient_id','$org_id','$inf_id_1','$num_1','$tindakan_id_1','$denum_1','','$current_dttm','$current_dttm','$user_id','normal')";
$sql_1 = $db->query($sql_inf_1);
$sql_inf_2 = "insert into xocp_ehr_pencatatanInos (id,patient_id,org_id,inf_id,num,tindakan,denum,pengali,tgl_kejadian,created_dttm,created_user,status_cd)"
." values('$id','$patient_id','$org_id','$inf_id_2','$num_2','$tindakan_id_2','$denum_2','','$current_dttm','$current_dttm','$user_id','normal')";
$db->query($sql_inf_2);
$sql_inf_3 = "insert into xocp_ehr_pencatatanInos (id,patient_id,org_id,inf_id,num,tindakan,denum,pengali,tgl_kejadian,created_dttm,created_user,status_cd)"
." values('$id','$patient_id','$org_id','$inf_id_3','$num_3','$tindakan_id_3','$denum_3','','$current_dttm','$current_dttm','$user_id','normal')";
$db->query($sql_inf_3);
$sql_inf_4 = "insert into xocp_ehr_pencatatanInos (id,patient_id,org_id,inf_id,num,tindakan,denum,pengali,tgl_kejadian,created_dttm,created_user,status_cd)"
." values('$id','$patient_id','$org_id','$inf_id_4','$num_4','$tindakan_id_4','$denum_4','','$current_dttm','$current_dttm','$user_id','normal')";
$db->query($sql_inf_4);
$sql_inf_5 = "insert into xocp_ehr_pencatatanInos (id,patient_id,org_id,inf_id,num,tindakan,denum,pengali,tgl_kejadian,created_dttm,created_user,status_cd)"
." values('$id','$patient_id','$org_id','$inf_id_5','$num_5','$tindakan_id_5','$denum_5','','$current_dttm','$current_dttm','$user_id','normal')";
$db->query($sql_inf_5);
$sql_inf_6 = "insert into xocp_ehr_pencatatanInos (id,patient_id,org_id,inf_id,num,tindakan,denum,pengali,tgl_kejadian,created_dttm,created_user,status_cd)"
." values('$id','$patient_id','$org_id','$inf_id_6','$num_6','$tindakan_id_6','$denum_6','','$current_dttm','$current_dttm','$user_id','normal')";
$db->query($sql_inf_6);
$sql_inf_7 = "insert into xocp_ehr_pencatatanInos (id,patient_id,org_id,inf_id,num,tindakan,denum,pengali,tgl_kejadian,created_dttm,created_user,status_cd)"
." values('$id','$patient_id','$org_id','$inf_id_7','$num_7','$tindakan_id_7','$denum_7','','$current_dttm','$current_dttm','$user_id','normal')";
$db->query($sql_inf_7);
I want to insert all variable 1 - 7 on sort

You can put multiple sets of values in a single INSERT query. So concatenate all the values that you're inserting.
$values = array();
for ($i = 0; $i < count($inf_id); $i++) {
$values[] = "('$id', '$patient_id', '$org_id', '{$inf_id[$i]}','{$num[$i]}','{$tindakan_id[$i]}','{$denum[$i]}','','$current_dttm','$current_dttm','$user_id','normal')"
}
$values_string = implode(',', $values);
$sql = "insert into xocp_ehr_pencatatanInos (id,patient_id,org_id,inf_id,num,tindakan,denum,pengali,tgl_kejadian,created_dttm,created_user,status_cd) VALUES $values_string";
$db->query($sql);

Related

Insert values from excel in mysql WordPress Php

i have this php code that is suppose to insert data from excel file to mysql database, from wordpress. This is the code:
<?php
global $wpdb;
$table_name = $wpdb->prefix . 'excelvalues';
echo $table_name;
if(isset($_POST["submit_file"]))
{
$file = "example.csv"//$_FILES["file"]["tmp_name"];
$file_open = fopen($file,"r");
while(($csv = fgetcsv($file_open, 1000, ",")) !== false)
{
$Anrede = $csv[0];
$Titel = $csv[1];
$Nachname = $csv[2];
$Vorname = $csv[3];
$Strasse = $csv[4];
$LKZ = $csv[5];
$PLZ = $csv[6];
$Ort = $csv[7];
$Mobil = $csv[8];
$Email = $csv[9];
$Geburtsdatum = $csv[10];
$Eintrittsdatum = $csv[11];
$Prüfungsjahr = $csv[12];
$Vermittlung = $csv[13];
$Bezirk = $csv[14];
$Kartennummer = $csv[15];
$LinkQR = $csv[16];
$wpdb->query("INSERT INTO $table_name(ID, Anrede, Titel,Nachname,Vorname,Strasse,LKZ,PLZ,Ort,Mobil,Email,Geburtsdatum,Eintrittsdatum,Prüfungsjahr,Vermittlung,Bezirk,Kartennummer,LinkQR) VALUES(NULL, '$Anrede', '$Titel', '$Nachname', '$Vorname', '$Strasse', '$LKZ', '$PLZ', '$Ort', '$Mobil', '$Email', '$Geburtsdatum', '$Eintrittsdatum', '$Prüfungsjahr', '$Vermittlung', '$Bezirk', '$Kartennummer', '$LinkQR')");
}
}
?>
The code works it inserts values on the database but the values are only the number of rows from excel but the values are missing, i dont understand what am i doing wrong.
Currently you retrieved the row id to each variable. This should work -
global $wpdb;
$table_name = $wpdb->prefix . 'excelvalues';
if(isset($_POST["submit_file"])){
$csvFile = file( 'example.csv' );
$all_data = [];
// fetch all data to array
foreach( $csvFile as $line ){
$all_data[] = str_getcsv( $line );
}
// fetch data from each row
foreach( $all_data as $row_key => $rows ){
// fetch data from each column
$Anrede = $rows[0];
$Titel = $rows[1];
$Nachname = $rows[2];
$Vorname = $rows[3];
$Strasse = $rows[4];
$LKZ = $rows[5];
$PLZ = $rows[6];
$Ort = $rows[7];
$Mobil = $rows[8];
$Email = $rows[9];
$Geburtsdatum = $rows[10];
$Eintrittsdatum = $rows[11];
$Prüfungsjahr = $rows[12];
$Vermittlung = $rows[13];
$Bezirk = $rows[14];
$Kartennummer = $rows[15];
$LinkQR = $rows[16];
// Insert into table
$wpdb->query("INSERT INTO $table_name(ID, Anrede, Titel,Nachname,Vorname,Strasse,LKZ,PLZ,Ort,Mobil,Email,Geburtsdatum,Eintrittsdatum,Prüfungsjahr,Vermittlung,Bezirk,Kartennummer,LinkQR) VALUES(NULL, '$Anrede', '$Titel', '$Nachname', '$Vorname', '$Strasse', '$LKZ', '$PLZ', '$Ort', '$Mobil', '$Email', '$Geburtsdatum', '$Eintrittsdatum', '$Prüfungsjahr', '$Vermittlung', '$Bezirk', '$Kartennummer', '$LinkQR')");
}
}

Data not inserting to database table

When I choose the expandable radio button and press the save button it should save its data to inventory_status table but the data wont insert into the inventory_status table. I've seen similar questions but still couldn't figure out the cause of the problem.
<?php
if($_POST['save']){
if ($_POST['supply_type'] == "expandable"){
$insertI = (mysqli_query($connect, "INSERT INTO inventory_status(stock_prop_no, unit, description, quantity, price) VALUES ('".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')"));
}
$pr_no = $_POST['pr_no'];
$s = mysqli_query($connect,"SELECT purchase_no FROM `sms_request` WHERE purchase_no = '".$pr_no."'");
if(mysqli_num_rows($s) > 0)
{
echo"
<script type='text/javascript'>
alert('Purchase No. Existed!');
window.location.href = 'sms_supply management.php';
</script>
";
}
else{
$fcluster = $_POST['fund_cluster'];
$osection = $_POST['office_section'];
$pr_no = $_POST['pr_no'];
$rcode = $_POST['responsibility_code'];
$desig = $_POST['desig'];
$requester = $_POST['requester'];
$loc = $_POST['loc'];
$purpose = $_POST['prpose'];
$ename = $_POST['entity_name'];
$date = $_POST['date'];
$dateA = date("Y-m-d",strtotime($date));
$radioo = $_POST['supply_type'];
$ins = mysqli_query($connect, "INSERT INTO sms_purchaserecord(purchase_no, supply_type) VALUES ('".$pr_no."', '".$radioo."')");
$insS = mysqli_query($connect, "INSERT INTO sms_ris(purchase_no, ris_num) VALUES ('".$pr_no."', '".$pr_no."')");
$insert = mysqli_query($connect, "INSERT INTO sms_request(purchase_no,sms_request.date, entity_name, fund_cluster, office_section, responsibility_code, purpose, stat) VALUES ('".$pr_no."','".$dateA."','".$ename."', '".$fcluster."', '".$osection."', '".$rcode."','".$purpose."', '1')");
$inS = mysqli_query($connect, "INSERT INTO sms_iar(iar_num, purchase_no) VALUES ('".$pr_no."', '".$pr_no."')");
$select = mysqli_query($connect, "SELECT request_IDnum FROM sms_request WHERE purchase_no = '".$pr_no."'");
while ($row = mysqli_fetch_array($select)){
$rnum = $row['request_IDnum'];
}
$select2 = mysqli_query($connect, "SELECT * FROM sms_branchloc WHERE loc_ID_no = '".$loc."'");
while ($row1 = mysqli_fetch_array($select2)){
$loc_num = $row1['loc_ID_no'];
}
if ($rnum != NULL AND $loc_num != NULL){
$insert2 = mysqli_query($connect, "INSERT INTO sms_requester(request_IDnum, name, loc_ID_no, position) VALUES ('".$rnum."', '".$requester."', '".$loc_num."', '".$desig."')");
}
foreach ($_POST['sp_num'] as $row=>$sp_numm) {
$sp_num = $sp_numm;
$unit = $_POST['unt'][$row];
$desc = $_POST['sdesc'][$row];
$qty = $_POST['sqty'][$row];
$cost = $_POST['cost'][$row];
$query = mysqli_query($connect,"INSERT INTO sms_supply (supply_qty,purchase_no,unit_cost,supply_unit,supply_desc,stockproperty_num) VALUES ('".$qty."','".$pr_no."', '".$cost."', '".$unit."','".$desc."', '".$sp_num."')");
}
echo"
<script type='text/javascript'>
alert('Purchase Request Save.');
window.location.href = 'sms_supply management.php';
</script>
";
}
}
This is the table structure of our inventory_status table:
I found one issue on your following query. sms_request.date should be sms_request_date
$insert = mysqli_query($connect, "INSERT INTO sms_request(purchase_no,sms_request.date, entity_name, fund_cluster, office_section, responsibility_code, purpose, stat) VALUES ('".$pr_no."','".$dateA."','".$ename."', '".$fcluster."', '".$osection."', '".$rcode."','".$purpose."', '1')");
Other thing
All these '".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')" variables are not defined. so you have to take this condition in loop.
For i.e.
foreach ($_POST['sp_num'] as $row=>$sp_numm) {
$sp_num = $sp_numm;
$unit = $_POST['unt'][$row];
$desc = $_POST['sdesc'][$row];
$qty = $_POST['sqty'][$row];
$cost = $_POST['cost'][$row];
if ($_POST['supply_type'] == "expandable"){
$insertI = (mysqli_query($connect, "INSERT INTO inventory_status(stock_prop_no, unit, description, quantity, price) VALUES ('".$sp_num."','".$unit."','".$desc."','".$qty."','".$cost."')"));
}
$query = mysqli_query($connect,"INSERT INTO sms_supply (supply_qty,purchase_no,unit_cost,supply_unit,supply_desc,stockproperty_num) VALUES ('".$qty."','".$pr_no."', '".$cost."', '".$unit."','".$desc."', '".$sp_num."')");
}

Unknown column 'E5V7D24M10Y2015' in 'where clause'

I have the code below to update (more 'add to') a row in a database. I have read a few very similar posts, but still can't see where I'm going wrong...
I am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''EventID' = '2' WHERE GameID = 'E2V1D24M10Y2015' AND PlayerID = '55'' at line 1
In this case, 'E5V7D24M10Y2015' is the value of $GameID. I am looking for a column called GameID where the value is E5V7D24M10Y2015, not a column of that name. Please tell me why my $sql is looking for a column named after the value it is looking for.
Each time the function runs the count($Runners) will be different and the values in each variable will be different. That is why I have the SQL in a loop.
if ($formtype == "gameresults"){
$Runners = $_POST['runners'];
$event = $_POST['event'];
$eid = $_POST['eid'];
$vid = $_POST['vid'];
$GameID = $_POST['GameID'];
$date = $_POST['date'];
$season = $_POST['season'];
$region = $_POST['region'];
$notes = $_POST['notes'];
$kev = "kev#email.com";
$email = $_POST['manager'];
$notes = wordwrap($notes,70);
$subject = ("Results for " . $event);
$tix = "";
$cashs = "";
for ($x = 1; $x < ($Runners + 1); $x++){
$ID = $_POST['ID' . $x];
$Name = $_POST['Name' .$x];
$Place = $_POST['Place'.$x];
$Points = $_POST['Points'.$x];
$Cash = $_POST['Cash'.$x];
$Ticket = $_POST['Ticket'.$x];
$vn = $_POST['vn'];
$buyin = $_POST['buyin'];
$data = array($eid,$vid,$region,$buyin,$GameID,$date,$season,$ID,$Name,$Place,$Points,$Ticket,$Cash,$Runners);
$fields = array('EventID','VenueID','Region','Buyin','GameID','Date','Season','PlayerID','Name','Position','Points','Ticket?','Cash','Runners');
for ($x = 0; $x < (count($data) - 1); $x++){
$sql = "UPDATE results SET '$fields[$x]' = '$data[$x]' WHERE GameID = '$GameID' AND PlayerID = '$ID'";
$res = mysqli_query($dbcon, $sql) or die("Update failed. <br>" . mysqli_error($dbcon));
}
You could modify your code to be more clear. I did example but I did not map all the fields so you need to adjust it.
$eid = 4;
$vid = 5;
$region = 'aa';
$buyin = 'asd';
$gameID = 5;
$date = 5;
$playerID = 10;
$fields = array(
'EventID' => $eid,
'VenueID' => $vid,
'Region' => $region,
'Buyin' => $buyin,
'GameID' => $gameID,
'PlayerID'=> $playerID,
'Date' => $date,
);
$numItems = count($fields);
$query = "UPDATE `results` SET ";
$i = 0;
foreach($fields as $name => $value) {
++$i;
if($name == 'GameID' || $name == 'PlayerID') {
continue;
}
$query .= sprintf(" `%s` = '%s'%s ", $name, $value, ($i === $numItems ? "": ","));
}
$query .= sprintf(" WHERE `GameID` = '%d' AND `PlayerID` = '%d'", $fields['GameID'], $fields['PlayerID']);
echo $query;
Fields can be maped via $key => $value and then used in foreach loop. Also using sprintf() makes is more clear to read. However, the best option would be using prepared statements.
Also you don't need to make multiple UPDATE queries, just SET more parameters in one query.
$data = array($eid,$vid,$region,$buyin,$GameID,$date,$season,$ID,$Name,$Place,$Points,$Ticket,$Cash,$Runners);
$fields = array('EventID','VenueID','Region','Buyin','GameID','Date','Season','PlayerID','Name','Position','Points','Ticket?','Cash','Runners');
for ($x = 0; $x < (count($data) - 1); $x++){
$sql = "UPDATE results SET " . $fields[$x] . " = '$data[$x]' WHERE results.GameID = $GameID AND results.PlayerID = $ID";
$res = mysqli_query($dbcon, $sql) or die("Update failed. <br>" . mysqli_error($dbcon));
}
Try this by specifying alias.

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);
}
}?>

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

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());
?>

Categories