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();
}
Related
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, ',');
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'");
I wrote this PHP code to extract values from a JSON file and insert them into a MySQL database.
<?php
//connect to mysql db
$con = mysqli_connect("localhost","root","","db_tweets") or die('Could not connect: ' . mysql_error());
//read the json file contents
$jsondata = file_get_contents('prova.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
foreach ($data as $u => $z){
foreach ($z as $n => $line){
//get the tweet details
$text = $line['text'];
$id_tweet = $line['id_str'];
$date = $line['created_at'];
$id_user = $line['user']['id_str'];
$screen_name = $line['user']['screen_name'];
$name = $line['user']['name'];
$sqlu = "INSERT INTO user(id_user, screen_name, name)
VALUES ('".$id_user."', '".$screen_name."', '".$name."')";
}
}
if(!mysqli_query($con, $sqlu))
{
die('Error : ' . mysql_error());
}
?>
In so doing it insert the values always in the first line of my table, overwriting the previous value. So it remains only the last.
How can I:
1) insert all values in multiple lines?
2) to parse multiple JSON files?
Try this.
You are just executing the last query cause you mysqli_query() is outside loop.
Method 1:
<?php
//connect to mysql db
$con = mysqli_connect("localhost","root","","db_tweets") or die('Could not connect: ' . mysql_error());
//read the json file contents
$jsondata = file_get_contents('prova.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
foreach ($data as $u => $z){
foreach ($z as $n => $line){
//get the tweet details
$text = $line['text'];
$id_tweet = $line['id_str'];
$date = $line['created_at'];
$id_user = $line['user']['id_str'];
$screen_name = $line['user']['screen_name'];
$name = $line['user']['name'];
$sqlu = "INSERT INTO user(id_user, screen_name, name)
VALUES ('".$id_user."', '".$screen_name."', '".$name."')";
if(!mysqli_query($con, $sqlu))
{
die('Error : ' . mysql_error());
}
}
}
?>
Method 2:
<?php
//connect to mysql db
$con = mysqli_connect("localhost","root","","db_tweets") or die('Could not connect: ' . mysql_error());
//read the json file contents
$jsondata = file_get_contents('prova.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
$values = "";
foreach ($data as $u => $z){
foreach ($z as $n => $line){
//get the tweet details
$text = $line['text'];
$id_tweet = $line['id_str'];
$date = $line['created_at'];
$id_user = $line['user']['id_str'];
$screen_name = $line['user']['screen_name'];
$name = $line['user']['name'];
$values .= "('".$id_user."', '".$screen_name."', '".$name."'),";
}
}
if(!empty($values)) {
$values = substr($values, 0, -1);
$sqlu = "INSERT INTO user(id_user, screen_name, name) VALUES {$values}";
if(!mysqli_query($con, $sqlu))
{
die('Error : ' . mysql_error());
}
}
?>
Answer for multiple files:
<?php
//connect to mysql db
$con = mysqli_connect("localhost","root","","db_tweets") or die('Could not connect: ' . mysql_error());
$files = array("prova.json", "file2.json");
foreach ($files as $file) {
//read the json file contents
$jsondata = file_get_contents($file);
//convert json object to php associative array
$data = json_decode($jsondata, true);
$values = "";
foreach ($data as $u => $z) {
foreach ($z as $n => $line) {
//get the tweet details
$text = $line['text'];
$id_tweet = $line['id_str'];
$date = $line['created_at'];
$id_user = $line['user']['id_str'];
$screen_name = $line['user']['screen_name'];
$name = $line['user']['name'];
$values .= "('" . $id_user . "', '" . $screen_name . "', '" . $name . "'),";
}
}
if (!empty($values)) {
$values = substr($values, 0, -1);
$sqlu = "INSERT INTO user(id_user, screen_name, name) VALUES {$values}";
if (!mysqli_query($con, $sqlu)) {
die('Error : ' . mysql_error());
}
}
}
?>
With every loop you're overwriting the last $sqlu value before ever passing that variable to the mysqli_query function after the loops. So once the loops are completed you're left with the last assigned value to $sqlu, and that's the only one that gets executed.
Instead, execute your query inside the loop and...
Use PHP mysqli_ functions mysqli_prepare, mysqli_stmt_bind_param, and mysqli_stmt_execute to simplify and secure your query:
//connect to mysql db
$con = mysqli_connect("localhost","root","","db_tweets") or die('Could not connect: ' . mysql_error());
// prepare your insert query
$stmt = mysqli_prepare($con, 'INSERT INTO user(id_user, screen_name, name) VALUES (?, ?, ?)');
// bind the upcoming variable names to the query statement
mysqli_stmt_bind_param($stmt, 'iss', $id_user, $screen_name, $name);
// loop over JSON files
$jsonfiles = array('prova.json', 'provb.json', 'provc.json');
foreach ( $jsonfiles as $jsonfile ) {
//read the json file contents
$jsondata = file_get_contents($jsonfile);
//convert json object to php associative array
$data = json_decode($jsondata, true);
foreach ($data as $u => $z){
foreach ($z as $n => $line){
//get the tweet details
$id_user = $line['user']['id_str'];
$screen_name = $line['user']['screen_name'];
$name = $line['user']['name'];
// execute this insertion
mysqli_stmt_execute($stmt);
}
}
}
So, this not only uses fewer database resources by preparing your query once, and has cleaner code, but also properly escapes your insertion values to protect against sql injection.
Added an array $jsonfiles containing any number of JSON filenames, and used a foreach construct to loop over the JSON files.
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
I have some data in JSON format in a text file as below. I need to insert this data into mysql using php but can't do it.
{"address":"+92 334 6629424","service_center":"Test Sending Sms","id":3,"locked":0,"person":0,"protocol":0,"read":0,"reply_path_present":2,"seen":0,"error_code":0,"status":1,"date":1873326412,"thread_id":1,"type":-1}
My PHP file has the code like this.
<?php $source_file = "SMS2012-05-21.txt"; $handle = fopen("SMS2012-05-21.txt", "r");
$col_names = implode(",", fgetcsv($handle)); // Getting comma separated list of col name
$link = mysql_connect('localhost', 'root', '');
mysql_select_db("messages");
while (($data = fgetcsv($handle)) !== FALSE) {
$values = "";
foreach($data as $key => $value) {
if ($key != 0) $values .= ", ";
$values .= "'".mysql_escape_string($value)."'";
}
mysql_query('INSERT INTO messages ('.$col_names.') VALUES ('.$values.')');
}
?>
I can't find any result nor any error. Could any one please help me in this regard that where i am wrong?
You should use json_decode function to manipulate json data.
<?php
$source_file = "SMS2012-05-21.txt";
$string = file_get_contents($source_file);
$json = json_decode($string,true);
//DB Conn Handling Stuff
$cols = array(); $values = array();
foreach($json as $key=>$value)
{
array_push($cols,'`' . $key . '`');
if(is_string($value))
{
array_push($values,'\''.$value.'\'');
}
else
{
array_push ($values, $value);
}
}
$col_name = implode(',',$cols);
$col_value = implode(',',$values);
$query = 'INSERT INTO messages('.$col_name.') VALUES ('.$col_value.')';
mysql_query($query,$connection) or die(echo mysql_error());
?>
Maybe I've missed something, you should use it in this way:
<?php $source_file = "SMS2012-05-21.txt";
$handle = fopen("SMS2012-05-21.txt", "r");
$data = fread($handle, filesize($source_file));
$jsonArray = json_decode($data, true);
$keys = implode(',', array_keys($jsonArray));
$values = "'" . implode("','", $jsonArray) . "'";
$link = mysql_connect('localhost', 'root', '');
mysql_select_db("messages");
mysql_query('INSERT INTO messages ('.$keys.') VALUES ('.$values.')');