I have passed JSON encoded parameters by POST which we have captured and decoded in another PHP file. I have used the following code to do that.
$entityBody = file_get_contents('php://input');
$entityBody = json_decode($entityBody, true);
I have passed the JSON encoded parameters as follows:
{
"id": "5",
"name": "abcd",
"imei": "1234"
}
Actually the number of parameters I am passing by POST may be 15 to 20 which I am going to insert in a table i.e. each of them is a field in the table in mysql database. I am new to JSON and PHP. What method I know is that get value of each parameter after checking whether it is set like following:
if(isset($entityBody['id']))
...
elseif(isset(...))
...
It is clear there will be many if and else when there are many parameters. So is there any way so that I can store the parameters in table in more efficient way. If anyone helps me in doing that I will be really grateful.
use json_decode function to parse the json to an array or object.
$a = json_decode($entityBody);
$a->id;
refer http://php.net/manual/en/function.json-decode.php
If you're using prepared statements you could do something like this. Please note that you should consider how you implement something like this, and change it to suit your needs.
$json = '{"id": "5","name": "abcd","imei": "1234"}';
$array = json_decode($json, true);
if (!count($array) > 0) {
throw new Exception('No params set.');
}
$allowedKeys = array('id','name','imei'); // could be hard coded, or something like: SELECT * FROM yourdb.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = yourtable
$queryParams = array();
foreach ($array as $key => $value) {
if (in_array($key, $allowedKeys)) {
$queryParams['keys'][] = $key;
$queryParams['values'][] = $value;
}
}
print_r($queryParams);
$query = 'INSERT INTO yourtable (' . implode(', ', $queryParams['keys']) . ') VALUES (?' . str_repeat(',?', count($queryParams['values'])-1) . ')';
print_r($query); // INSERT INTO yourtable (id, name, imei) VALUES (?,?,?)
Then you can just execute it with the $queryParams['values'] as the values :)
There's however no need to insert "id" if you're using auto increment, it will possibly just end up in some strange errors.
Related
I am not able decode and insert the array data in PHP. I tried to functions like decode and foreach, but nothing work.
The $_POST['area'] data:
[area] => [{"text":"DATA1"},{"text":"DATA2"},*,{"text":"DATA3"}]
I am new to PHP, how can I insert these rows of data into my database with pdo's prepared statements?
$area = $_POST['area'];
foreach ($area as $data) {
echo json_decode($data);
}
echo json_decode($area);
However it does not echo.
Ultimately, I want to use the data in this:
$stmt = $con->prepare(INSERT INTO `table` (`areas`) VALUES(:data));
$stmt->execute(array($data));
First things first, you have an invalid json string because of the *,.
$_POST['area'] = '[{"text":"DATA1"},{"text":"DATA2"},*,{"text":"DATA3"}]';
// uh oh, not valid json -----^^
So I'll assume that this is a posting error and run with the following input data:
$_POST['area'] = '[{"text":"DATA1"},{"text":"DATA2"},{"text":"DATA3"}]';
This means that before you can iterate $_POST['area'], you must json_decode() it. (Demo)
An unchanging prepared statement should be declared before entering the loop -- it is designed to be used over and over.
The binding of values to placeholders and the execution of the query is to be done inside the loop.
$stmt = $con->prepare(INSERT INTO `table` (`areas`) VALUES(?));
foreach (json_decode($_POST['area']) as $obj) {
$stmt->execute([$obj->text]);
}
Your json format is incorrect. To do json_decode(); you need correct json format
$post['area'] = [{"text":"DATA1"},{"text":"DATA2"},*,{"text":"DATA3"}];
changed it to
$post['area'] = [{"text":"DATA1"},{"text":"DATA2"},{"text":"DATA3"}];
then do
$ex = json_decode($data, true);
Use This:
$area = json_decode($_POST['area'],true);
You can't echo an array in PHP. You have to use the var_dump() function to do that.
Have a good day ;).
I need help understanding this clever PHP Multiple Mysql Insert code.
Allow me to stress that, I've found the parsing of JSON data online and the rest is mine.
It works flawlessly but there are things I don't fully understand about it...
How is it building the insert string? If you could comment the code that's wonderful...
Is it repeatedly inserting or is it one giant insert PDO execute?
I've notice that it uses bindValue instead of bindParameter. Is this because of the nature of this dynamic PHP script?
Optional: If you know of a simple and clear way to do this, by all means, let me know if you get a chance.
JSON POST DATA
[
{
"PK_LINE_ITEM_ID":555,
"DESCRIPTION":"LINE ITEM 5",
"QUANTITY":0,
"UNIT":"SF",
"COST":0,
"TOTAL":"0.00"
},
{
"PK_LINE_ITEM_ID":777,
"DESCRIPTION":"LINE ITEM 7",
"QUANTITY":0,
"UNIT":"SF",
"COST":0,
"TOTAL":"0.00"
},
{
"PK_LINE_ITEM_ID":999,
"DESCRIPTION":"LINE ITEM 9",
"QUANTITY":0,
"UNIT":"SF",
"COST":0,
"TOTAL":"0.00"
}
]
PHP script (data_post_json_insert_all.php)
<?php
/* Status Codes
return 0 = Nothing to Update (n/a)
return 1 = Successful Insert Query
return 2 = Database Connection refused
return 3 = MySQL Query Error OR Wrong URL Parameters */
/* Disable Warnings so that we can return ONLY what we want through echo. */
mysqli_report(MYSQLI_REPORT_STRICT);
// First get raw POST input
$raw_post = file_get_contents('php://input');
// Run through url_decode..
$url_decoded = urldecode($raw_post);
// Run through json_decode...
// false to allow for reference to oject. eg. $column->name instead of $column["name"] in the foreach.
$json_decoded = json_decode($url_decoded, true);
$table_name = 'tbl_xyz';
// INCLUDE DB CONNECTION STRING
include 'php_pdo_mysql_connect.php';
pdoMultiInsert($table_name, $json_decoded, $link);
function pdoMultiInsert($mysql_table, $json_decoded, $pdo_object) {
//Will contain SQL snippets.
$rows_sql = [];
//Will contain the values that we need to bind.
$to_bind = [];
//Get a list of column names to use in the SQL statement.
$column_names = array_keys($json_decoded[0]);
//Loop through our $json_decoded array.
// begin outter for each
foreach($json_decoded as $array_index => $row) {
$params = [];
// begin inner for each --------------------------------
foreach($row as $column_name => $column_value) {
$param = ":" . $column_name . $array_index;
$params[] = $param;
$to_bind[$param] = $column_value;
} // end inner for each --------------------------------
$rows_sql[] = "(" . implode(", ", $params) . ")";
} // end outter for each
//Construct our SQL statement
$sql = "INSERT INTO `$mysql_table` (" . implode(", ", $column_names) . ") VALUES " . implode(", ", $rows_sql);
//Prepare our PDO statement.
$pdo_statement = $pdo_object->prepare($sql);
//Bind our values.
foreach($to_bind as $param => $val) {
$pdo_statement->bindValue($param, $val);
}
//Execute our statement (i.e. insert the json_decoded data).
return $pdo_statement->execute();
}
$link = null;
$stmt = null;
// return 1 = Successful Insert Query
echo '1';
Thanks
1) The script uses a bidimensional array to make it easier to prepare the insert query.
It will create an array for each row (using the column name as the index and the field value as the value), and then a second array containing those rows. So the array represents all the data that will be inserted, exactly as it should be included.
Then, they implode each line using a coma as glue - so you'll have each value separated with a coma and put parenthesis on it. Then just implode the second array using a coma as glue again, wich will mount the whole insert values query.
2) Execute is runing outside any repeat loop, so it's only one giant insert.
3) bindParam will bound the query to a variable, and if this variable changes in the future, it will change in the query too. bindValue append the final value at the runtime. Take a look at this thread.
4) This script is meant to be generic and work with different table setups - and it's a good way of doing it.
I'm trying to handle a POST request from a web service. It's sending an HTTP POST request like this:
{
"latitude":"12.232",
"longitude":"123.323"
}
It's posting to a PHP file on my server. I know that it is hitting the file for sure. However, I'm not getting the data.
In my PHP, I have this (leaving out a bunch of stuff:
$json = file_get_contents('php://input');
$obj = json_decode($json);
$mine ="sixteen"; //using this for a test
$sql = "INSERT INTO rr_emergency (random) VALUES('$obj');";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
This makes no change to my database.
If I do this instead:
$sql = "INSERT INTO rr_emergency (random) VALUES('$mine');";
Then "sixteen" is added in the right spot in a new row in my table each time the webservice calls my PHP. This is how I know I'm receiving data.
NOTE: I was trying to simply add $obj into my table just to see the data format that's returned before I tried to properly parse it and put everything where it belongs.
What am I doing wrong here? I think the problem is here ($json = file_get_contents('php://input');), but not sure what else to try.
Thanks.
So there's a few problems
$obj = json_decode($json);
This will return an object. You want an array
$obj = json_decode($json, true);
Then your PDO is incorrect
$sql = "INSERT INTO rr_emergency (random) VALUES(:val);";
$prep = $dbh->prepare($sql);
foreach($obj as $row) $prep->execute([':val' => $row]);
This will insert your data correctly (using a prepared statement) and loop over the JSON return data
You're trying to insert an object, when you really need a string. use:
$obj = json_decode($json, true)
$obj_str = implode(", ", $obj);
$sql = "INSERT INTO rr_emergency (random) VALUES('$obj_str');";
After I posted the above, you added:
I was trying to simply add $obj into my table just to see the data
format
Objects do not inherently convert to strings, so putting $obj within your query doesn't work. The way I store objects in my DB when I've needed to, is to store the JSON notation directly.
$json = file_get_contents("php://input");
$sql = "INSERT INTO rr_emergency (random) VALUES('$json')";
You lose the ability to perform filtering and selecting operations within the object, but it's an effective way to pack away data that you won't need the DB to parse through.
If you need well formatted, easy to read structure:
$obj = json_decode($json);
$obj_str = print_r($obj,true); //store formatted string
$sql = "INSERT INTO rr_emergency (random) VALUES('$obj_str');";
If as you said, all you need to do is "just see the data format", I suggest echoing to the screen or writing to a log file; do one of the following. To print to screen:
print_r($obj);
To write to file:
$filepath = "/path/to/file.txt"
file_put_contents($filepath,print_r($obj,true));
Important note
Entering text directly into your DB queries without escaping it makes you vulnerable to SQL injection attacks. Use prepared statements instead.
I have the following json file which I'm sending through my mobile application to PHP and on the PHP side I want to Decode it and insert it into a mysql database.
[{"Address":"Somewhere ",
"Area":"Somwhe",
"CreatedBy":null,
"CreatedDate":"\/Date(1419786831365+0530)\/",
"Distance":0,
"EditedDate":"\/Date(-62135596800000+0000)\/",
"Latitude":12.903999947011471,
"Longitude":77.607999974861741,
"Phone1":"80372899",
"Phone2":"993729927",
"Response":null,
"StoreDescriptions":[],
"StoreName":"First"},
{"Address":"Addwmsj",
"Area":"Sbnns",
"CreatedBy":null,
"CreatedDate":"\/Date(1419786863657+0530)\/",
"Distance":0,
"EditedDate":"\/Date(-62135596800000+0000)\/",
"Latitude":12.960867136716843,
"Longitude":77.647689711302519,
"Phone1":"799268299",
"Phone2":"68393973738",
"Response":"Waiting",
"StoreDescriptions":[{"LongNBQuantity":862,
"MeetDate":"\/Date(1419786915048+0530)\/",
"MeetSummary":"Meeting",
"Response":"Negative",
"StoreName":"Ssxond",
"id":1
},
{"LongNBQuantity":8862,
"MeetDate":"\/Date(1419786927673+0530)\/",
"MeetSummary":"Pjsjsbsj",
"Response":"Waiting",
"StoreName":"Ssxond",
"id":2}],
"StoreName":"Ssxond"},
{"Address":"Sumwhere",
"Area":"Righthere",
"CreatedBy":null,
"CreatedDate":"\/Date(1419953186686+0530)\/",
"Distance":0,
"EditedDate":"\/Date(-62135596800000+0000)\/",
"Latitude":12.903999947011471,
"Longitude":77.607999974861741,
"Phone1":"872737288",
"Phone2":"663838828",
"Response":null,
"StoreDescriptions":[],
"StoreName":"NewEntry"}]
As we can see in this I have Array of objects [{},{},{}...{}] and the complexity increases when one of these objects have array of objects like {"abc":"bcd","storedesc":[{},{},{},....{}]} , so this is a little complex when compared to the simple jsons.
My code is not working. Can anybody guide me in the right direction. Thanks
$json = file_get_contents('php://input');
$result = json_decode($json,true);
/*
Database connection setup done here.
*/
foreach ($result as $key => $value) {
if($value){
$sql = "INSERT INTO StoreInfo(name,created_date,edited_date,address,area,ph_num1,ph_num2,response,latitude,longitude) VALUES ($value->StoreName,$value->CreatedDate,'hellyeah',$value->Address,$value->Area,$value->Phone1,$value->Phone2,$value->Response,$value->Longitude,$value->Latitude)";
if($conn->query($sql) === TRUE){
echo "New record inserted";
}
}
}
There are couple of reasons, this not works.
Because you are using the true flag, when you are decoding the JSON, you will get back only arrays, and as I see, you want to use objects in your querys.
In your query do not wrap your wariables with quotes.
So it will be something like this, but please, see my NOTE section!
$sql = "INSERT INTO StoreInfo (name,created_date,edited_date,address,area,
ph_num1,ph_num2,response,latitude,longitude)
VALUES ('".$value["StoreName"]."','".$value["CreatedDate"]."','hellyeah',
'".$value["Address"]."','".$value["Area"]."','".$value["Phone1"]."',
'".$value["Phone2"]."'
,'".$value["Response"]."','".$value["Longitude"]."','".$value["Latitude"]."')";
NOTE
Please escape your variables comes from outside, or use prepared statements to avoid sql injection!
By $result = json_decode($json,true); it is converted to array. true parameter in json_decode() convert JSON to array(). So you should access value by $value['CreatedDate'] instead of $value->CreatedDate and so on.
foreach ($result as $key => $value) {
if($value){
$sql = "INSERT INTO StoreInfo(name,created_date,edited_date,address,area,ph_num1,ph_num2,response,latitude,longitude) VALUES ('".$value['StoreName']."','".$value['CreatedDate']."','hellyeah','".$value['Address']."','".$value['Area']."','".$value['Phone1']."','".$value['Phone2']."','".$value['Response']."','".$value['Longitude']."','".$value['Latitude']."')";
if($conn->query($sql) === TRUE){
echo "New record inserted";
}
}
}
Reference:
json_decode()
I have a little problem to code in PHP how to obtain this result with data provided from MySQL
{"profiles":[
{"ID": "39780b57-9181-4a41-a31e-5d4b3fa59a50", "Name": "Mihai - BP Dev Team","CountryCode": "ro","PictureID": "a30d750a-38e6-407f-a722-943fe3711807","IsStandard": true,"IsOnline": true,"IsPremium": true,"IsVerified": true,"Age": 27,"CityStateCode": "Bucharest"},
{"ID": "e1dd5bab-1eeb-4729-a4f6-0baeb851f750", "Name": "Nicolai", "CountryCode": "dk", "PictureID": "af1345b5-8380-4300-abf0-1d5f15c90040", "IsStandard": true, "Age": 32, "CityStateCode": "Valby"},
{"ID": "2c8535ec-25a4-4a3e-a333-c3797aff491f", "Name": "Testing", "CountryCode": "ca", "PictureID": "ba44bf9b-1592-40a8-b60c-068603bfb9c1", "IsStandard": true, "Age": 30, "CityStateCode": "Centre-Sud North"}}
]}
This is my PHP code :
$accessDb = new Connexion("gaiurba_MyBD");
$connexion2 = $accessDb->openConnexion();
if ($query2 = $connexion2->prepare("SELECT u.UserName as UserName, u.PictureID as PictureID, u.CountryCode as CountryCode,
u.DateOfBirth as DateOfBirth, u.CityCode as CityCode, u.VerifiedTimestamp as VerifiedTimestamp,
u.OnlineStatus as OnlineStatus, u.IsPaying as IsPaying, u.StatusAvailableForDates as StatusAvailableForDates,
cc.$languageCode as CityStateCode, os.$languageCode as LabelOnlineStatus
FROM Users u
INNER JOIN CityCode cc ON u.CityCode = cc.id
INNER JOIN OnlineStatus os ON u.OnlineStatus = os.id
WHERE u.ID = ?")) {
$query2->bind_param('s', $id);
$query2->execute();
$query2->bind_result($UserName, $PictureID, $CountryCode, $DateOfBirth, $CityStateCode, $VerifiedTimestamp, $OnlineStatus, $IsPaying, $StatusAvailableForDates, $CityStateCode, $LabelOnlineStatus);
$query2->store_result();
$affected2 = $connexion2->affected_rows;
// TRACE
echo "[affected2 row 2 = $affected2]";
if ($affected2 == 1) {
while ($query2->fetch()) {
echo "[ID = $id - UserName = $UserName - PictureID = $PictureID - CountryCode = $CountryCode - DateOfBirth = $DateOfBirth - CityStateCode = $CityStateCode - VerifiedTimestamp = $VerifiedTimestamp - OnlineStatus = $OnlineStatus - IsPaying = $IsPaying - StatusAvailableForDates = $StatusAvailableForDates - CityStateCode = $CityStateCode - LabelOnlineStatus = $LabelOnlineStatus]";
}
} else {
$result = '{"exception":false,"success":false,"status":0,"message":"ERROR SQL Query : SELECT-ULL-ID Number of row !","confirmMessage":null,"html":null,"data":null}';
}
} else {
$result = '{"exception":false,"success":false,"status":0,"message":"ERROR SQL Query : SELECT-ULL-ID Number of row !","confirmMessage":null,"html":null,"data":null}';
}
I know the right code is on my while($query2->fetch()) condition because my echo see me good information read from my BD. The first thing i need to create an array in PHP and append each row fetched from BD and at the end use
echo json_encode($result);
Do not pay attention to my data return by me SELECT and the data in the JSON string. I know I'll have to format some data in my while loop to get the right result.
I just need to know how to create an array in which I add a new array for each rows returned by MySQL.
Thank you for your helping !
Creating an array is as simple as:
$profiles = array();
or just
// Add an item. Array is created if $x didn't contain an array already.
$profiles[] = 'foo';
So to create something with the structure you like, you'll need an object with a property that contains an array of objects representing the rows.
You can create a simple object in a similar fashion as arrays: just start assigning properties. So to create the array of profiles, just do this for each row:
$profile = null;
$profile->UserName = $UserName;
$profile->PictureID = $PictureID;
// Etc
Maybe your database class supports a method to return an entire row as an object instead of calling fetch() combined with outbound parameters. That way you don't need to create the object yourself, saving a couple of lines.
// Add profile object to array.
$profiles[] := $profile;
Maybe your database class supports a way to return the entire dataset as an array of objects. If so, you don't need to loop and build the array yourself. Saving yet another couple of lines of code.
However you have built the array, afterwards, wrap it in another object, in its profiles property to be precise.
$result = null;
$result->profiles = $profiles;
And output:
echo json_encode($result);
It's not strictly necessary to make a variable null before starting to assign properties, but it prevents accidental reuse of an old variable. Especially in the loop this is required, otherwise you'll just reassign the properties of the same object and add the same object a number of times to the array, leading to undesired results (every row being the same).
Instead of just assigning properties, you can actually create an object before doing so:
$profile = new StdClass();
This is a little more verbose and therefor maybe a little more readable, just as using array() to initialize an empty array. It's a matter of personal taste.