Insert Multiple not empty - php

I need to insert multple records i have this right now.
Its adds also the empty field because i dont know how to exclude them from inserting:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
/* as_factuurregel */
$product1 = $_POST['product1'];
$product2 = $_POST['product2'];
$product3 = $_POST['product3'];
$product4 = $_POST['product4'];
$product5 = $_POST['product5'];
$product6 = $_POST['product6'];
$aantal1 = $_POST['aantal1'];
$aantal2 = $_POST['aantal2'];
$aantal3 = $_POST['aantal3'];
$aantal4 = $_POST['aantal4'];
$aantal5 = $_POST['aantal5'];
$aantal6 = $_POST['aantal6'];
$sql = "INSERT INTO as_factuurregel (productid, factuurid, aantal)
VALUES ('$product1', 'test', '$aantal1'),('$product2', 'test', '$aantal2'),('$product4', 'test', '$aantal3'),('$product5', 'test', '$aantal5'),('$product5', 'test', '$aantal5')";
Thanks for helping.
Greetings

Try this:
$product1 = $_POST['product1'];
$product2 = $_POST['product2'];
$product3 = $_POST['product3'];
$product4 = $_POST['product4'];
$product5 = $_POST['product5'];
$product6 = $_POST['product6'];
$array_one = array($product1,$product2,$product3,$product4,$product5,$product6);
$aantal1 = $_POST['aantal1'];
$aantal2 = $_POST['aantal2'];
$aantal3 = $_POST['aantal3'];
$aantal4 = $_POST['aantal4'];
$aantal5 = $_POST['aantal5'];
$aantal6 = $_POST['aantal6'];
$array_two = array($aantal1,$aantal2,$aantal3,$aantal4,$aantal5,$aantal6);
$newArray = array();
foreach ($array_one as $key => $value) {
if($value != '' && $array_two[$key] != '')
{
$newArray[] = "('$value','test','$array_two[$key]')";
}
}
$values = implode(",",$newArray);
$sql = "INSERT INTO as_factuurregel (productid, factuurid, aantal)
VALUES ".$values;
You can optimize this solution if you optimize your input fields and move them in an array.

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')");
}
}

UPDATE record serialized - php mysql

I have this problem, I have to update a record of a table that has the values of a serialized column. the call to the function works and passes the data correctly. I can enter the record, but I can not update. This is my code:
public function update($user_id, $array_check)
{
$arrayB = array();
$array_check = unserialize($array_check);
foreach ($array_check $key => $value) {
if($value["id"] == $array_check){
$idRow = $value["id"];
if($value["value"] == "0"){
$valueRow = "1";
}else{
$valueRow = "0";
}
}else{
$idRow = $value["id"];
$valueRow = $value["value"];
}
$row = array("id" => $idRow, "value" => $valueRow);
$arrayB[] = $row;
}
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id');
$row = $stmt->execute(array(':user_id' => $user_id, ':docs_selected' => serialize($arrayB) ) );
return $arrayB;
}
edit.
Replace this:
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id);
with:
$deseralized = serialize($arrayB);
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = '$deseralized ' WHERE user_id = '$user_id');

Index causes and Error in Updating Row

Why does Index causes an error in MySQL Update row? Removing it makes the Query work.
The error is
MySQLi failed to query: UPDATE quests SET id = '1', FactionID = '2', ReqReputation = '2', ReqClassID = '3', ReqClassPoints = '2', Name = '2', Description = '2', EndText = '2', Experience = '2', GExperience = '2', Copper = '2', Silver = '2', Gold = '2', Coins = '2', Reputation = '2', ClassPoints = '2', RewardType = 'S', Level = '2', Upgrade = '1', Once = '1', Slot = '2', Value = '2', Field = '2', Index = '2', Badges = '3', Guild = '1', GiveMembership = '0', War = '1' WHERE id = 1 - December 20, 2016, 1:58 am
$id = $_POST["Id"];
$FactionID = $_POST["Faction"];
$ReqReputation = $_POST["RequiredReputation"];
$ReqClassID = $_POST["Class"];
$ReqClassPoints = $_POST["ReqClassRank"];
$Name = $_POST["Name"];
$Description = $_POST["Description"];
$EndText = $_POST["EndText"];
$Experience = $_POST["Experience"];
$GExperience = $_POST["GuildExperience"];
$Copper = $_POST["Copper"];
$Silver = $_POST["Silver"];
$Gold = $_POST["Gold"];
$Coins = $_POST["Diamond"];
$Reputation = $_POST["Reputation"];
$ClassPoints = $_POST["ClassPoints"];
$RewardType = $_POST["RewardType"];
$Level = $_POST["Level"];
$Upgrade = $_POST["Upgrade"];
$Once = $_POST["Once"];
$Slot = $_POST["Slot"];
$Value = $_POST["Value"];
$Field = $_POST["Field"];
$QIndex = $_POST["Index"];
$Badges = $_POST["Badges"];
$Guild = $_POST["Guild"];
$GiveMembership = $_POST["GiveMembership"];
$War = $_POST["War"];
$MYSQL_QUERY = $content->DBase('Query', array( 0 => "UPDATE quests SET id = '$id', FactionID = '$FactionID', ReqReputation = '$ReqReputation', ReqClassID = '$ReqClassID', ReqClassPoints = '$ReqClassPoints', Name = '$Name', Description = '$Description', EndText = '$EndText', Experience = '$Experience', GExperience = '$GExperience', Copper = '$Copper', Silver = '$Silver', Gold = '$Gold', Coins = '$Coins', Reputation = '$Reputation', ClassPoints = '$ClassPoints', RewardType = '$RewardType', Level = '$Level', Upgrade = '$Upgrade', Once = '$Once', Slot = '$Slot', Value = '$Value', Field = '$Field', Index = '$Index', Badges = '$Badges', Guild = '$Guild', GiveMembership = '$GiveMembership', War = '$War' WHERE id = $id"));
Function DBase
/** MYSQL IMPROVED EXTENSION (PARENT CLASS) **/
public function DBase($type, $params = array()) {
if (!$this->SITE->CMS->Connection)
SystemExit('No available MySQLi connection', __LINE__, __FILE__);
switch (strtoupper($type)) {
case 'QUERY':
if ($Query = parent::query($params[0])) {
$this->SITE->CMS->TotalQuery++;
return $Query;
} else
SystemExit('MySQLi failed to query: ' . $params[0], __LINE__, __FILE__);
break;
case 'PREPARE':
if ($Query = parent::prepare($params[0])) {
$this->SITE->CMS->TotalQuery++;
return $Query;
} else
SystemExit('MySQLi failed to prepare: ' . $params[0], __LINE__, __FILE__);
break;
case 'ESCAPESTRING':
if ($Escape = parent::real_escape_string($params[0]))
return $Escape;
else
SystemExit('MySQLi failed to escape: ' . $params[0], __LINE__, __FILE__);
break;
}
}
Here is the Table Quest
You're using the wrong variable for index. You define it above as $QIndex but then refer to it as $Index on the last line. Try the following:
$id = $_POST["Id"];
$FactionID = $_POST["Faction"];
$ReqReputation = $_POST["RequiredReputation"];
$ReqClassID = $_POST["Class"];
$ReqClassPoints = $_POST["ReqClassRank"];
$Name = $_POST["Name"];
$Description = $_POST["Description"];
$EndText = $_POST["EndText"];
$Experience = $_POST["Experience"];
$GExperience = $_POST["GuildExperience"];
$Copper = $_POST["Copper"];
$Silver = $_POST["Silver"];
$Gold = $_POST["Gold"];
$Coins = $_POST["Diamond"];
$Reputation = $_POST["Reputation"];
$ClassPoints = $_POST["ClassPoints"];
$RewardType = $_POST["RewardType"];
$Level = $_POST["Level"];
$Upgrade = $_POST["Upgrade"];
$Once = $_POST["Once"];
$Slot = $_POST["Slot"];
$Value = $_POST["Value"];
$Field = $_POST["Field"];
$QIndex = $_POST["Index"];
$Badges = $_POST["Badges"];
$Guild = $_POST["Guild"];
$GiveMembership = $_POST["GiveMembership"];
$War = $_POST["War"];
$MYSQL_QUERY = $content->DBase('Query', array( 0 => "UPDATE quests SET id = '$id', FactionID = '$FactionID', ReqReputation = '$ReqReputation', ReqClassID = '$ReqClassID', ReqClassPoints = '$ReqClassPoints', Name = '$Name', Description = '$Description', EndText = '$EndText', Experience = '$Experience', GExperience = '$GExperience', Copper = '$Copper', Silver = '$Silver', Gold = '$Gold', Coins = '$Coins', Reputation = '$Reputation', ClassPoints = '$ClassPoints', RewardType = '$RewardType', Level = '$Level', Upgrade = '$Upgrade', Once = '$Once', Slot = '$Slot', Value = '$Value', Field = '$Field', Index = '$QIndex', Badges = '$Badges', Guild = '$Guild', GiveMembership = '$GiveMembership', War = '$War' WHERE id = $id"));
Also see #Rahul 's comment too. Your: "WHERE id='$id'" seems to be passing the wrong value. An ID is most likely not that version of a date/time. if you want to use the current date + time you could us something like NOW() It gives you the current date and time down to the second.

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.

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