PHP submit to insert and update data - php

I need my form to post either INSERT or UPDATE data, depending on whether the column already exists. The INSERT query works fine, but the UPDATE doesn't. I guess this would be because the initial sql query ($query) is failing, more than likely because it is not finding the $Unique_Ref POST data. If this is the case, how do I extract this single value from the $invoice_data array?
This is the form page code:
if (isset($_GET['success']) && empty($_GET['success'])) {echo 'Record saved'; } else {if (empty($_POST) === false && empty($errors) === true) {$invoice_data = array(
'Unique_Ref' => mysqli_real_escape_string($conn, $_POST['Unique_Ref']),
'Supplier_Name' => mysqli_real_escape_string($conn, $_POST['Supplier_Name']),
'Supplier_Invoice_Ref' => mysqli_real_escape_string($conn, $_POST['Supplier_Invoice_Ref']),
'Office' => mysqli_real_escape_string($conn, $_POST['Office']),
'Loss_Surplus_Amount' => mysqli_real_escape_string($conn, $_POST['Loss_Surplus_Amount']),
'Loss_Surplus_Currency' => mysqli_real_escape_string($conn, $_POST['Loss_Surplus_Currency']),
'Outcome' => mysqli_real_escape_string($conn, $_POST['Outcome']));
save_invoice($invoice_data);header('Location: invoices.php?success'); exit();
} else if (empty($errors) === false) {echo output_errors($errors);} ?> *html form....*
This is the save_invoice() function:
function save_invoice($invoice_data) {
global $conn;
array_walk($invoice_data, 'array_sanitize');
$fields = '`' . implode('`, `', array_keys($invoice_data)) . '`';
$data = '\'' . implode('\', \'', $invoice_data) . '\'';
$query = mysqli_query($conn, "SELECT * FROM `invoicelog` WHERE `Unique_Ref` = '$Unique_Ref'");
$result = mysqli_num_rows($query);
if($result > 0) {
mysqli_query($conn, "UPDATE `invoicelog` SET $fields = $data WHERE `Unique_Ref` = '$Unique_Ref'");
} else {
mysqli_query($conn, "INSERT INTO `invoicelog` ($fields) VALUES ($data)");
}
Any suggestions would be very welcome. As I mentioned, the final INSERT query works fine, it's the UPDATE query which isn't functioning.

Your have to pair your
$fields = '`' . implode('`, `', array_keys($invoice_data)) . '`';
$data = '\'' . implode('\', \'', $invoice_data) . '\'';
Edit
i've edited you code like this:
$fields = array_keys($invoice_data)[$i];
$data = $invoice_data;
to achieve whats below, and it works for me.. hmm..
End Edit
something like :
'fields[0] = $data[0], ...' //and so on, place it in a loop. or whatever you prefer.. :)
because when updating it's (field1 = value1, field2 = value)
Edit2
Actual code of testing:
End Edit
maybe something like this will do?
$set_arr = array();
for ($i = 0; $i < count($data); $i++)
{
$set_arr[] = "`".array_keys($invoice_data)[$i]/*$fields*/."` = '".$data[$i]."' ";
}
$setString = implode(',', $set_arr);
/*
Result ]> `Unique_Ref` = '1' ,`Supplier_Name` = '2' ,`Supplier_Invoice_Ref` = '3' ,`Office` = '4' ,`Loss_Surplus_Amount` = '5' ,`Loss_Surplus_Currency` = '6' ,`Outcome` = '7'
]> from my test
*/
then your update statement will be something like this:
"UPDATE `invoicelog` SET ($setString) `Unique_Ref` = '$Unique_Ref'
Hope i've helped you.. i'm outta here, Happy Coding Cheers!

You can't set multiple values to multiple fields within single expression like SET $fields = $data. You should set each value for each field separately: SET field1='value1', field2='value2', ...

//mysqli_query($conn, "UPDATE invoicelog SET $fields = $data WHERE Unique_Ref = '$Unique_Ref'");
update below code with above line.
$str = '';
foreach($invoice_data as $field=>$val ){
$str = $str.",".$field."=".$val;
}
$str = substr($str,1);
mysqli_query($conn, "UPDATE `invoicelog` SET $str WHERE Unique_Ref = '$Unique_Ref'");

make sure insert quote (') for string value :
mysqli_query($conn, "UPDATE `invoicelog` SET $fields = '$data' WHERE `Unique_Ref` = '$Unique_Ref'");

Related

What did i missed in code? PHP calculating

I want to send data to database, but if result = 1 status=plusone, result = 2 status=plustwo, etc..
It should work like that..
But no, it work like this: result = 2 status=plusone .
What did i missed? Help me..
I've tried this:
$item = '0';
$result = $item + $points;
and:
$result = $points + 0;
Here is rest (part of) code:
if($result = 1){
$Sql_Query ="INSERT INTO points SET unique_id = '$id', description = '$Description', points = '$points', status= 'plusone'";
if(mysqli_query($con,$Sql_Query)) {
echo 'Succcess!';
}
}elseif($result = 2){
$Sql_Query ="INSERT INTO points SET unique_id = '$id', description = ' $Description', points = '$points', status= 'plustwo'";
if(mysqli_query($con,$Sql_Query)) {
echo 'Succcess!';
}
}
= and == are different; = is for assignment, and == is to compare statement

Inserting JSON data into MySQL

I have a solution with PHP as server-side, Vue JS for front-end and MySQL as DB.
The UI bundles data as JSON and posts it to PHP through axios, and PHP in turn will decode the JSON and inserts into MySQL.
Here is my PHP code (omitting the other lines like connecting etc.):
$data = file_get_contents("php://input");
$jsonData = json_decode($data, true);
//echo var_dump($jsonData);
// Below is the jsonData as dumped
//[{"candidate_id":"SM_009","FirstName":"test","LastName":"dummy","DOB":"1990-06-05"}]
$tableName = 'profile';
foreach((array)$jsonData as $id=>$row) {
$insertPairs = array();
foreach ((array)$row as $key=>$val) {
$insertPairs[addslashes($key)] = addslashes($val);
}
$insertKeys = '`' . implode('`,`', array_keys($insertPairs)) . '`';
$insertVals = '"' . implode('","', array_values($insertPairs)) . '"';
$sql = "INSERT INTO `{$tableName}` ({$insertKeys}) VALUES ({$insertVals});" ;
//echo var_dump($sql);
$stmt = $con->prepare($sql);
$stmt->execute();
}
However, here is the actual insert statement generated, which is obviously wrong.
INSERT INTO `profile` (`0`) VALUES ("[{\"candidate_id\":\"SM_009\",\"FirstName\":\"test\",\"LastName\":\"dummy\",\"DOB\":\"1990-06-05\"}]");
Where am I doing wrong? Any help would be greatly appreciated..
Thanks
Note: When I use the same dumped jsondata as hardcoded string, it works.
$data ='[{"candidate_id":"SM_009","FirstName":"test","LastName":"dummy","DOB":"1990-06-12"}]';
//$data = file_get_contents("php://input");
...
Generated statement:
"INSERT INTO `profile` (`candidate_id`,`FirstName`,`LastName`,`DOB`) VALUES ("SM_009","test","dummy","1990-06-12");"
The reason you are still receiving the json in your insert statement is because you decoded the first part of your json string and received the data array which still contains the json string inside of it. To resolve this just decode the $jsonData variable again like so:
<?php
$data = file_get_contents("php://input");
$jsonData = json_decode($data, true);
$jsonData = json_decode($jsonData['data'], true); //Decode the data as well
$tableName = 'profile';
foreach((array)$jsonData as $id => $row){
$insertPairs = array();
foreach ((array)$row as $key=>$val) {
$insertPairs[addslashes($key)] = addslashes($val);
}
$insertKeys = '`' . implode('`,`', array_keys($insertPairs)) . '`';
$insertVals = '"' . implode('","', array_values($insertPairs)) . '"';
$sql = "INSERT INTO `{$tableName}` ({$insertKeys}) VALUES ({$insertVals});" ;
$stmt = $con->prepare($sql);
$stmt->execute();
}
You can check out a working example here: https://ideone.com/i86iVP
You can do like this:
$jsonString = '{"data":[{"candidate_id":"SM_009","FirstName":"test","LastName":"dummy","DOB":"1990-06-12"}]}';
$jsonArray = json_decode($jsonString,true);
$data = $jsonArray['data'];
//$data = json_decode(file_get_contents("php://input"),true);
//$json = json_decode($data, true); $json = $data['data'];
//json_decode($_GET['data']);
$tableName = 'profile';
foreach((array)$data as $id=>$row) {
$insertPairs = array();
foreach ((array)$row as $key=>$val) {
$key = addslashes($key);
$val = addslashes($val);
$insertPairs[] = " `{$key}` = '{$val}' ";
}
$sqlInsert = implode(", ", $insertPairs);
$sql = "INSERT INTO `{$tableName}` SET {$sqlInsert} ";
echo var_dump($sql);
/*
string(126) "INSERT INTO `profile` SET `candidate_id` = 'SM_009' , `FirstName` = 'test' , `LastName` = 'dummy' , `DOB` = '1990-06-05' "
*/
// $stmt = $con->prepare($sql);
// $stmt->execute();
}

How do I ensure null is sent instead of 0 for empty form fields

I have a table with columns that allow null values and has a default null value. On update, if the field is empty (not data inserted) my script inserts 0 instead of null. I have gone through similar questions as mine and i have tried the advice given but am still not able to fix my issue. Here's my code
<?php
if (isset($_POST['submit'])) {
# process the form
$student_id = $_POST["student_id"];
$subject_id = $_POST['subject_id'];
if (is_null($_POST["test1"])){$test1 = null;} else {$test1 = $_POST["test1"];}
if (is_null($_POST["test2"])){$test2 = null;} else {$test2 = $_POST["test2"];}
if (is_null($_POST["test3"])){$test3 = null;} else {$test3 = $_POST["test3"];}
for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
$test_1 = mysqli_real_escape_string($connection, $test1[$i]);
$test_2 = mysqli_real_escape_string($connection, $test2[$i]);
$test_3 = mysqli_real_escape_string($connection, $test3[$i]);
$query = "UPDATE fullresult SET test1='{$test_1}', test2='{$test_2}', test3='{$test_3}' WHERE student_id={$studentid} AND subject_id={$subjectid}";
$result = mysqli_query($connection, $query);
}
}
?>
When i echo the query, this is what i see and am wondering why i still get 0 inserted
UPDATE fullresult SET test1=' 10', test2=' ', test3=' ' WHERE student_id=51 AND subject_id=2
is_null does not return true for an empty string. Try changing your if statements to something like this:
$test1 = trim($_POST["test1"])
if (!strlen($test1)) $test3 = null;
You could use
ctype_digit
to check if there are numeric characters in it.
The function
mysqli::real_escape_string -- mysqli_real_escape_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
(Source: http://php.net/manual/en/mysqli.real-escape-string.php)
Since you want to have null inside the database you should rewrite the code
if (is_null($_POST["test1"])){$test1 = null;} else {$test1 = mysqli_real_escape_string($connection, $_POST["test1"]);}
to have the values escaped only if needed (which is in case you have a value in $_POST)
What about
if (isset($_POST['submit'])) {
# process the form
$student_id = $_POST["student_id"];
$subject_id = $_POST['subject_id'];
# only retrieve FILLED IN answers
$tests = array();
if(isset($_POST["test1"]) && strlen($_POST["test1"])) $tests['test1'] = $_POST["test1"];
if(isset($_POST["test2"]) && strlen($_POST["test2"])) $tests['test2'] = $_POST["test2"];
if(isset($_POST["test3"]) && strlen($_POST["test3"])) $tests['test3'] = $_POST["test3"];
if(!empty($tests)){ # if there were no answers, there's no point in updating the database
for($i=0; $i < count($student_id); $i++) {
$studentid = mysqli_real_escape_string($connection, $student_id[$i]);
$subjectid = mysqli_real_escape_string($connection, $subject_id);
# now let's build the "SET" part of the query
$set = array();
foreach($tests as $key => $value) $set[]=mysqli_real_escape_string($key)."='".mysqli_real_escape_string($value)."'";
$set = implode(', ',$set);
# ...and finally update
$query = "UPDATE fullresult SET {$set} WHERE student_id={$studentid} AND subject_id={$subjectid}";
$result = mysqli_query($connection, $query);
}
}
}
The point of this approach is that if you don't include a key=>value pair in your UPDATE query, it will be filled in with its default value.
You must set 'null' word, not null value.
if (is_null($_POST["test1"])){$test1 = 'null';} else {$test1 = $_POST["test1"];}
if (is_null($_POST["test2"])){$test2 = 'null';} else {$test2 = $_POST["test2"];}
if (is_null($_POST["test3"])){$test3 = 'null';} else {$test3 = $_POST["test3"];}

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

echo json_encode() is returning NULL

I am trying to pass data to a php page via ajax, the data gets inserted to the database, then I need to pick up the last insert and pass the back to update a select menu with that last insert selected. The database gets updated correctly, but Im getting a NULL return for the echo json_echo($data);
Been stuck on this all day, would really appreciate the help!!!
if (empty($_POST) === false && empty($errors) === true) {
$company_id = $_POST['company_id'];
$patient_id = $_POST['addpatient_id'];
$first_name = $_POST['addpatient_firstname'];
$last_name = $_POST['addpatient_lastname'];
$dob = $_POST['addpatient_dob'];
$updated = $_POST['patient_added'];
$update = array();
array_walk($update_data, 'array_sanitize');
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("INSERT INTO `lab`.`patients` (`company_id`, `patient_firstname`, `patient_lastname`, `patient_dob`, `patient_added`) VALUES ('$company_id', '$first_name', '$last_name', '$dob', '$updated')");
$last_patient_id = mysql_insert_id();
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname`, `patient_dob` FROM `patients` WHERE `patient_id` = $last_patient_id");
$data[] = mysql_fetch_assoc($result);
}
echo json_encode( $data );
json_encode returns false if an error happened (php manual). I would start there.
$json_string = json_encode( $data );
if( $json_string ){
echo $json_string;
}else{
echo "Error";
echo "<pre>";
print_r($data);
echo "</pre>";
}
That should at least lead you a way to debug.
EDIT: Also try add this to the beginning of the function all
error_reporting(E_ALL);
ini_set('display_errors', '1');
This will help display errors that the mysql is throwing.
EDIT: I wanted to just fix spelling, but since I need 6 characters minimum I will mention http://jsonlint.com/ to validate what you're putting into json_encode

Categories