echo json_encode() is returning NULL - php

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

Related

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

Mysql auto insert an empty row

I am working with mysql in my project and when I try to call the webAPI to insert data to the database, it inserts an empty row before the inserted row.
Can anyone help please?
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
$nom = $_POST['nom'];
$query = "INSERT into class (nom_class) values('$nom')";
$result = $db->query($query);
if ($result === TRUE) {
$res = "Inserted" . $nom;
echo json_encode($res);
} else {
echo json_encode("Error" . $query . "<br>" . $db->error);
}
break;
I have tried EMPTY, and ISSET features but it didn't work.
This is the database:
I'll be so grateful if any one could help.

PHP submit to insert and update data

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

Cannot insert character into mysql column from array

I have following code in order to capture data from the previous page. Its working fine, the data is passing true, just the problem is the only variable that has characters ($itemName).
I simply cannot insert in mysql column. Its not type setting or character set. I suspecting its something to with a fact that the text is coming from array. Any ideas?
if(isset($_POST["cantidad"]) && count($_POST['cantidad'])>0) {
foreach($_POST["cantidad"] as $key => $value) {
$cantidad = $value;
$value = $_POST["cantidad"][$key];
$idItem = $_POST['hiddenField'][$key];
$itemName = $_POST['hiddenName'][$key];
$query = "INSERT INTO `inventarioStat` SET `fecha` = $timestamp, `idItem` = $idItem, `nombreItem` = $itemName, `cantidad` = $value";
///// this section is to check do data pass true and they do
echo "<br>";
echo "value:" . $value . "<br>";
echo "id:" . $idItem . "<br>";
echo "name:" . $itemName . "<br>";
mysql_query($query);
}
}
echo "<br>";
$query = "INSERT INTO `inventarioStat` SET `fecha` = $timestamp, `idItem` = $idItem, `nombreItem` = $itemName, `cantidad` = $value";
This line is incorrect and extremely unsafe. The issue is that you are not quoting your strings in the SQL query. You need quotes around the $itemName value.
You also need to be escaping the values here. This code is wide open to SQL injection. If you use it, you will probably get hacked.
Try this:
foreach($_POST["cantidad"] as $key => $value) {
$cantidad = $value;
$value = mysql_real_escape_string($_POST["cantidad"][$key]);
$idItem = mysql_real_escape_string($_POST['hiddenField'][$key]);
$itemName = mysql_real_escape_string($_POST['hiddenName'][$key]);
$query = "INSERT INTO `inventarioStat` SET `fecha` = '$timestamp', `idItem` = '$idItem', `nombreItem` = '$itemName', `cantidad` = '$value'";
mysql_query($query);
}
This code is better, but not perfect. It's safer, but not 100% safe.
You should upgrade to using PDO or MySQLi and prepared statements (PDO docs or MySQLi docs).

JQuery string not parsing correctly in PHP

In a previous post, I asked about how to deserialize a JQuery string, and was told to use parse_str(). However, I didn't post my code until later. So, here is my JQuery string:
age_gender=1&age_gender=2&age_gender=3&age_gender=4&age_gender=5&age_gender=6
And here is my PHP code:
if(isset($_POST['age_gender'])) {
$formSerialized = $_POST['age_gender'];
$formData = array();
parse_str($formSerialized, $formData);
addRow($formData, $link);
}
function addRow($dataArray, $link) {
$age_group = $dataArray[0];
$populations = array(intval($dataArray[1]) + intval($dataArray[2]), intval($dataArray[1]), intval($dataArray[2]));
$percents = array(doubleval($dataArray[3]) + doubleval($dataArray[4]), doubleval($dataArray[3]), doubleval($dataArray[4]));
$m_per_100_f = doubleval($dataArray[6]);
$query = "INSERT INTO national_age_gender_demographics (age_group, both_pop, male_pop, female_pop, both_percent, male_percent, female_percent, males_per_100_females)
VALUES ('$age_group','$populations[0]','$populations[1]','$populations[2]','$percents[0]','$percents[1]','$percents[2]','$m_per_100_f')";
$result = mysqli_query($link,$query);
if(!$result) die( "Query: " . $query . "\nError:" . mysql_error() );
}
For some reason, I am getting a blank string for $age_group, and 0's for all other values. Could anyone help me here?
Try to pass the data like this instead:
age_gender[]=1&age_gender[]=2&age_gender[]=3&age_gender[]=4&age_gender[]=5&age_gender[]=6
note the '[]' after the name, if they come from html input you would just have to name your html input age_gender[].
Then you function addRow should look like:
function addRow($dataArray, $link) {
$dataArray = $dataArray['age_gender'];//Added this line
$age_group = $dataArray[0];
$populations = array(intval($dataArray[1]) + intval($dataArray[2]), intval($dataArray[1]), intval($dataArray[2]));
$percents = array(doubleval($dataArray[3]) + doubleval($dataArray[4]), doubleval($dataArray[3]), doubleval($dataArray[4]));
$m_per_100_f = doubleval($dataArray[6]);
$query = "INSERT INTO national_age_gender_demographics (age_group, both_pop, male_pop, female_pop, both_percent, male_percent, female_percent, males_per_100_females)
VALUES ('$age_group','$populations[0]','$populations[1]','$populations[2]','$percents[0]','$percents[1]','$percents[2]','$m_per_100_f')";
$result = mysqli_query($link,$query);
if(!$result) die( "Query: " . $query . "\nError:" . mysql_error() );
}
You can try encoding with Json, this is a good solution
$.stringfy(your_var);
and to read with php use json_decode

Categories