This code works perfectly for parsing the json object, but I need to store all json data to mysql. How can I retrieve the value to store in mysql?
function getDataAsArray($filename){
$dataArray=array();
$contents = file_get_contents($filename);
$first_split=explode("}}{",$contents);
$json_array=explode("\n",$first_split[0]);
foreach($json_array as $value){
$data = json_decode($value, true);
$dataArray[]=$data;
}
return $dataArray;
}
$logDataArray=getDataAsArray("akshara.txt");
echo "<pre>";print_r($logDataArray); echo "</pre>"
MySQL supports a JSON datatype in 2015, much like Postgres has had for a good few years now. You can simply insert the JSON into your database.
$json = file_get_contents($file); // {"my_value": "my data"}
DB::query("INSERT INTO my_table (json) VALUES ('{$json}')");
You can then use the various JSON functions to query your inserted data.
SELECT JSN_EXTRACT(json, '$.my_value') AS my_value FROM my_table // my_value = my data
Related
I have data from MySQL database and data from base64 file out of database
I want to combine them so i can have one JSON data with both
$PaFile="JVBERi0xLjcKMS.....";
$NaFile="JVBERi0xLjvvm.....";
$sqlRun = mysqli_query($conn, "SELECT laimCode, laimYear, laimMonth FROM laim_folio");
$row = mysqli_fetch_assoc($sqlRun);
$json_array[] = $row;
$jasondata = json_encode($json_array[]);
What i expect as output is
[{
"laimCode":"1234",
"laimYear":"2021",
"laimMonth":"11",
"PaFile":"JVBERi0xLjcKMS.....",
"NaFile":"JVBERi0xLjvvm....."
}]
If i put these two variable in SQL as static column with value i can get the result i want
But is there way to combine them outside SQL ?
Like extends array with two extra field and then convert to JSON
You can either add them to the array after fetching the data from the database and before adding into the overall array....
$row = mysqli_fetch_assoc($sqlRun);
$row['PaFile'] = "JVBERi0xLjcKMS.....";
$row['NaFile'] = "JVBERi0xLjvvm.....";
$json_array[] = $row;
$jasondata = json_encode($json_array);
Or add the values to the SQL so they become part of the result set. So the value is just a literal and the alias becomes the column name...
SELECT laimCode, laimYear, laimMonth,
"JVBERi0xLjcKMS....." as PaFile,
"JVBERi0xLjvvm....." as NaFile
FROM laim_folio
I have recently used this concat operator to join columns in JSON.
select concat('{"laimCode":',laimCode,',"laimYear":',laimYear,',"laimMonth":',laimMonth,',"PaFile":"JVBERi0xLjcKMS.....", "NaFile":"JVBERi0xLjvvm....."}') as json FROM laim_folio
I'm using an API that provides the data in JSON format. I'm trying to store the JSON response in the MySQL database (just as it is)
and then refetch it from the database in JSON format. You may be wondering why I'm doing this, well, I'm using a paid API that has limited no. of requests. To prevent multiple API calls, I wanted to serve API responses through my server (So basically application users would be polling my server to fetch the JSON response Instead of directly calling an API)
So I created a table named "matchinfo" and there is a column named "jsondata" which has a type of LONGTEXT
$json_response = file_get_contents("api_url"); // storing json format response
$update_data = "UPDATE matchinfo SET jsondata = '$json_response'"; // Succesfully stored it
$update_query = mysqli_query($conn,$update_data);
// how can I again fetch it in the JSON format
I think your question is "How can I pull data with mysqli".
//connection
$mysqli = new mysqli("localhost", "user", "pass", "database");
//obtaining the jsondata.
$result = $mysqli->query("SELECT jsondata FROM matchinfo");
$row = $result->fetch_array(MYSQLI_ASSOC);
//The data is like file_get_contents("api_url");
$json_response = $row['jsondata']; //json string
//If you want to use data as array.
$json = json_decode($json_response, true); //array
I guess what you are looking for is the function "json_decode".
You can use it like that:
$databaseValue = '{"field": "value"}'; // Example, this represents your string you have stored in your database
$fetchedJson = json_decode($databaseValue, true); // JSON Value
You need the true inside json_decode, because you want the result of the function to be a JSON array. If you'd put a false there, the result of the function will be an object.
You can read more about it in the php documentation.
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 ;).
Good Day Please can you assist I'm trying to update a mysql table with a JSON POST. The JSON output into a textfile fine but when I try and save it to the MySQL table then supplies an error:
Undefined index: ptp.create
The JSON Outputs the data as:
{"ptp.create":["629","630"]}
$jsonString = file_get_contents("php://input");
$myFile = "NewFile.txt";
file_put_contents($myFile,$jsonString);
$data = json_decode($jsonString, true);
foreach ($data as $row){
$PTP = $row['ptp.create'];
$query_rsTable1 = "INSERT INTO test SET id = '$PTP'";
$rsTable1 = mysql_query($query_rsTable1, $int) or die(mysql_error());
}
I'm not very 100% confident in JSON yet, if you could please assist.
Your for loop has already taken care of the ptp.create for you.
foreach ($data as $ptp){
echo $ptp; // Will be 629, then 630
}
When you actually insert into your database, use prepared/parameterized queries with PDO or similar.
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.