Cannot get value from Key JSON MySQL PHP - javascript

I am retrieving data from a MySQL database using PHP and attempting to use JSON.stringify and JSON.parse to create an object. It works fine but I cannot get the assocaited keys/values. Just the entire object. I break this up in to parts. Here is the PHP code:
First PHP File:
<?php
session_start();
include("web_db_operations.php");
if(isset($_POST['recipeId']) && isset($_SESSION['email'])){
$recipeId = $_POST['recipeId'];
$email = $_SESSION['email'];
}
else{
echo "Did not work";
}
$results = getAllMyRecipesAsList_recipeTable2($email, $recipeId);
$_SESSION['recipeResults'] = $results;
header('location:web_selected_recipe.php');
exit();
?>
Second PHP File
function getAllMyRecipesAsList_recipeTable2(string $email, int $recipeId){
include 'config.php';
$sql = 'SELECT * FROM recipeTable WHERE email = :email AND recipeId = :recipeId';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':recipeId', $recipeId, PDO::PARAM_STR);
$stmt->execute();
$getResults = $stmt->fetchAll(PDO::FETCH_ASSOC);
$json = array();
if(count($getResults) > 0){
foreach($getResults as $row){
$json[] = array('firstName' => $row['firstName'],
'lastName' => $row['lastName'],
'email' => $row['email'],
'recipeName' => $row['recipeName'],
'description' => $row['description'],
'ingredients' => $row['ingredients'],
'prepTime' => $row['prepTime'],
'steps' => $row['steps'],
'nutrition' => $row['nutrition'],
'servings' => $row['servings'],
'rating' => $row['rating'],
'tags' => $row['tags'],
'imagePath' => $row['imagePath'],
'imageName' => $row['imageName'],
'recipeId' => $row['recipeId']
);
}
$results = json_encode($json);
return $results;
}else{
echo "no data found";
}
}
Then to retrieve in my JS file (this is just the relevant parts):
<script>
<?php $results = $_SESSION['recipeResults'];
var results = <?php echo $results; ?>;
var toString = JSON.stringify(results);
console.log(toString);
var parsed = JSON.parse(toString);
console.log(parsed);
</script>
Logging resultAsString yields this:
[{"firstName":"Marcus","lastName":"Holden","email":"marcus#gmail.com","recipeName":"Aloo Paratha","description":"","ingredients":"","prepTime":"25 Minutes","steps":"","nutrition":"","servings":"","rating":"","tags":"","imagePath":"../userRecipeImages","imageName":"9110164.jpg","recipeId":"1"}]
Logging parsed yields this:
[{…}]
0:description:
"No Description", email "marcus#gmail.com", firstName:"Marcus", imageName:"9110164.jpg", imagePath:"../userRecipeImages", ingredients:"Some Ingredients",lastName:"Holden", nutrition:"Not given", prepTime:"25 Minutes", rating:"5/10", recipeId:"1", recipeName:"Aloo Paratha", servings: "6", steps:"Your Steps Here", tags:"It's bread"
Now, I have tried all steps to get the value associated with a key... for instance my object here is called parsed... so I have tried parsed.firstName.. returns undefined... as well as Object.keys(parsed). I cannot seem to get the keys. I would like to work with it like an array... setting content like this:
element.innerHTML = parsed[2]... etc.
What am I missing here?

I think you're doing quite a bit more than you need to. The data is coming to you as a JSON-encoded object. Just work with it.
<script>
var results = <?php echo $_SESSION['recipeResults']; ?>;
var first_results = results[0]; // Each array member is one object from your result set
console.log( first_results.firstName );
console.log( results[0].firstName ); // OR specify which array index to interact directly
</script>

Related

How to parse a JSON data that has been received by a PHP scipt

I have sent data from my php script using `json_encode' function.
if I console.log(resp) below is the O/P I get.
data: "{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}" status: "success"
however, if I console.log(resp.data) I get the below data
{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC001","emp_name":"Akshay S. Shrivastav"}{"dept_name":"IT","city_name":"Mumbai","emp_id":"#AC003","emp_name":"Aakash Shrivastav"}
Now I'm trying to display this data in the data tables for which I am using the below code.
$('#grpList').DataTable().row.add([
resp.data.dept_name,
resp.data.city_name,
resp.data.emp_id,
resp.data.emp_name
]).draw(false);
I'm receiving the following error
DataTables warning: table id=grpList - Requested unknown parameter '0' for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4
when I am single handed displaying only console.log(resp.data.dept_name) it says undefined
I'll be having multiple JSON response if the data increases, for now, I only have two. I'm not able to figure out how to display multiple data using a loop and appending it to the data table.
I'm using below php code to generate JSON
$jsonArray = "";
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
$jsonArray .= json_encode(
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
Because resp.data is an array of objects. You need to get the index first - let's say index 0, or the first object in the array:
$("#grpList").DataTable().row.add([
resp.data[0].dept_name,
resp.data[0].city_name,
resp.data[0].emp_id,
resp.data[0].emp_name
]).draw(false);
And if you want the second object:
$("#grpList").DataTable().row.add([
resp.data[1].dept_name,
resp.data[1].city_name,
resp.data[1].emp_id,
resp.data[1].emp_name
]).draw(false);
Of course, row.add() accepts an array argument as well - so this would work too:
$("#grpList").DataTable().row.add(resp.data).draw(false);
The issue is on server side.
You define $jsonArray as a string ! That's wrong.
Try this instead:
$jsonArray = []; // An ARRAY here!
if($data->num_rows > 0)
{
while($row = $data->fetch_assoc())
{
array_push($jsonArray, json_encode( // Use array_push here
array(
"dept_name" => $row['department_name'],
"city_name" => $row['city_name'],
"emp_id" => $row['emp_id'],
"emp_name" => $row['name']
));
}
echo json_encode(array("data" => $jsonArray, "status" => 'success'));
}
EDIT
I don't if the above works... Since I did not test it.
But here's how I would have writen it (I guess you'll have more chances with it):
$jsonArray = [];
if($data->num_rows > 0) {
while($row = $data->fetch_assoc()) {
// A temp array to rename the one of the keys...
$tempArray = [];
$tempArray = ["dept_name"] = $row['department_name'];
$tempArray = ["city_name"] = $row['city_name'];
$tempArray = ["emp_id"] = $row['emp_id'];
$tempArray = ["emp_name"] = $row['name'];
// Push to the jsonArray now...
array_push($jsonArray,$tempArray);
}
// And finally the result array... To be json encoded
$result = [];
$result = ["status"] = "success";
$result = ["data"] = jsonArray;
echo json_encode($result);
}
Note that without renaming one key and if there's only 4 data per rows from the DB... You could have done array_push($jsonArray,$row); directly, without using the $tempArray.
So try this... AND then apply Jack's answer. ;)

PHP to decode JSON array and insert into MYSQL database

I am trying to create a PHP script that decodes a JSON array and insert it into a database. So far i've managed to get the script to insert the first row in the array and nothing else.
What would I need to add to this to get the script to insert all the rows in the array?
Here's the array, ignore "listings", I don't need that data yet (It's quite big):
json
Here's the script:
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$con = mysql_connect($servername, $username, $password);
//select db
$selected = mysql_select_db("ed",$con);
$json_obj = file_get_contents("stations.json");
//convert to stdclass object
$arr = json_decode($json_obj,true);
//store the element values into variables
$id = $arr[0]["id"];
$name = $arr[0]["name"];
$system_id = $arr[0]["system_id"];
$max_landing_pad_size = $arr[0]["max_landing_pad_size"];
$distance_to_star = $arr[0]["distance_to_star"];
$faction = $arr[0]["faction"];
$government = $arr[0]["government"];
$allegiance = $arr[0]["allegiance"];
$state = $arr[0]["state"];
$type = $arr[0]["type"];
$has_blackmarket = $arr[0]["has_blackmarket"];
$has_commodities = $arr[0]["has_commodities"];
$has_refuel = $arr[0]["has_refuel"];
$has_repair = $arr[0]["has_repair"];
$has_rearm = $arr[0]["has_rearm"];
$has_outfitting = $arr[0]["has_outfitting"];
$has_shipyard = $arr[0]["has_shipyard"];
//insert values into mysql database
$sql="INSERT INTO stations (station_id, name, system_id, max_landing_pad_size, distance_to_star, faction, government, allegiance, state, type, has_blackmarket, has_commodities, has_refuel, has_repair, has_rearm, has_outfitting, has_shipyard)
VALUES ('$id', '$name', '$system_id', '$max_landing_pad_size', '$distance_to_star', '$faction', '$government', '$allegiance', '$state', '$type', '$has_blackmarket', '$has_commodities', '$has_refuel', '$has_repair', '$has_rearm', '$has_outfitting', '$has_shipyard')";
if(!mysql_query($sql,$con)) //$con is mysql connection object
{
die('Error : ' . mysql_error());
}
?>
try this.
$arr = json_decode($json_obj,true);
$sql = 'INSERT INTO stations (`';
$sql.= implode('`,`', array_keys( $arr[0] ) );
$sql.= '`) values (\'';
$sql.= implode('\',\'', $arr[0] );
$sql.= '\')';
Use foreach
$arr = json_decode($json_obj,true);//decode object
foreach($arr as $ar){
$id = $ar["id"];
$name = $ar["name"];
$system_id = $ar["system_id"];
$max_landing_pad_size = $ar["max_landing_pad_size"];
$distance_to_star = $ar["distance_to_star"];
$faction = $ar["faction"];
$government = $ar["government"];
$allegiance = $ar["allegiance"];
$state = $ar["state"];
$type = $ar["type"];
$has_blackmarket = $ar["has_blackmarket"];
$has_commodities = $ar["has_commodities"];
$has_refuel = $ar["has_refuel"];
$has_repair = $ar["has_repair"];
$has_rearm = $ar["has_rearm"];
$has_outfitting = $ar["has_outfitting"];
$has_shipyard = $ar["has_shipyard"];
//insert values into mysql database
$sql="INSERT INTO stations (station_id, name, system_id, max_landing_pad_size, distance_to_star, faction, government, allegiance, state, type, has_blackmarket, has_commodities, has_refuel, has_repair, has_rearm, has_outfitting, has_shipyard)
VALUES ('$id', '$name', '$system_id', '$max_landing_pad_size', '$distance_to_star', '$faction', '$government', '$allegiance', '$state', '$type', '$has_blackmarket', '$has_commodities', '$has_refuel', '$has_repair', '$has_rearm', '$has_outfitting', '$has_shipyard')";
if(!mysql_query($sql,$con)) //$con is mysql connection object
{
die('Error : ' . mysql_error());
}
}
For big amounts of data like in this case, you would want to execute the query just once, or you'll burden your database unnecessarily. For this, you can build your query with all the data being inserted and then execute it, like so:
<?php
$arr = json_decode($json_obj,true);//decode object
$query = "INSERT into stations (station_id, name, system_id, max_landing_pad_size, distance_to_star, faction, government, allegiance, state, type, has_blackmarket, has_commodities, has_refuel, has_repair, has_rearm, has_outfitting, has_shipyard) values ";
foreach($arr as $ar) {
$query .= "($ar['id'],$ar['name'],$ar['system_id'],
$ar['max_landing_pad_size'],$ar['distance_to_star'],$ar['faction'],
$ar['government'],$ar['allegiance'],$ar['state'],
$ar['type'],$ar['has_blackmarket'],$ar['has_commodities'],
$ar['has_refuel'],$ar['has_repair'],$ar['has_rearm'],
$ar['has_outfitting'],$ar['has_shipyard']),";
}
$query = rtrim(",",$query);
if(!mysql_query($query,$con)) //$con is mysql connection object
{
die('Error : ' . mysql_error());
}
In case you want to know, your original code doesn't work because you're just grabbing the first row from the json ($arr[0]). You need to loop through the data to get all the rows.

Parsing JSON file to produce and return another JSON with required data

I need to parse a given JSON file for events that occur between the start and end time that are passed through an HTTP GET. The events that occur between this range should then be returned as a new JSON encoded response. So far I have come up with two possible solutions. Neither seem to be giving me the expected JSON encoded file.
EDIT: Aside from the script not producing the proper JSON file, I get the following error in the developers console on Chrome: Uncaught TypeError: Cannot read property 'length' of null
Solution 1:
$param1 = $_GET['startTime'];
$param2 = $_GET['endTime'];
$data = file_get_contents('./events.json');
$json = json_decode($data, true);
foreach ($json as $key => $value){
if ($value > $param1 && $value < $param2) {
echo "$key => $value"; }
else { return; }
}
Solution 2 (same parameters passed in, different for each loop):
foreach ($json as $key => $value){
if ($value >= $param1 && $value <= $param2) {
$tempFile = "tempEvents.json";
$jsonArray = json_decode(file_get_contents($tempFile), true);
array_push($jsonArray, array( 'title' => ????, 'start' => $param1, 'end' => $param2 ));
file_put_contents($file, json_encode($jsonArray));
}
else { return; }
echo json_encode('tempEvents.json');
}
Sample JSON file to be parsed:
[
{
"Name":"Event 1",
"Start Time":258147369,
"End Time":369147258
},
{
"Name":"Event 2",
"Start Time":789456123,
"End Time":159487263
},
]
You should use json_encode on an array to get well-formed JSON output. I can't speak for your if statement's validity as you haven't provided any sample data, but this is how you should do your conversion:
$param1 = $_GET['startTime'];
$param2 = $_GET['endTime'];
$data = file_get_contents('./events.json');
$json = json_decode($data, true);
$output = array();
foreach ($json as $key => $value){
if ($value > $param1 && $value < $param2)
$output[$key] = $value;
}
$json_out = json_encode($output);
echo $json_out; // this outputs to the browser
// to output to file, use $json_out as your string to write to file

How to properly format JSON

I asked a question earlier, which all revolved around a JSON formatting problem. I have a PHP page, which just grabs rows from a MYSQL database, and returns them. However, i'm unsure how to format them so all the columns I get are a set, and for each row, it creates a new set. I'm not sure what is common practice to do to encode things like this.
e.g. this is what I want (if it is even correct):
{ "message": [
{
"chat":"Hello, world!",
"time":"2014-05-09 17:32:00",
"username":"Josue"
},
{
"chat":"This is my second message.",
"time":"2014-05-09 17:32:05",
"username":"Josue"
}
]
}
That way, I can parse using $.parseAJAX, and get access to my data like: data.message[0].chat, and it would return "Hello world!".
Here is what I am currently doing:
$SQL = sprintf('SELECT time_sent, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = 'chat';
$messages[] = $row['chat'];
$messages[] = 'time';
$messages[] = $row['time_sent'];
$messages[] = 'username';
$messages[] = $row['username'];
}
$loopCount = count($chats);
if(count($messages) > 0){
/*
$sexyJSON = '{message: [';
for($i = 0; $i < $loopCount; $i++){
$sexyJSON .= '{"chat":"'.$chats[$i].'","time":"'.$times[$i].'","username":"'.$usernames[$i].'"},';
}
$sexyJSON = substr($sexyJSON,0,strlen($sexyJSON)-1);
$sexyJSON .= ']}';
$newMessages = $sexyJSON;
echo $sexyJSON;
*/
echo json_encode($messages);
}
When I simply encode my array, it returns something like this:
["chat","Hello, world!","time","2014-05-09 17:32:00","username","Josue","chat","hmmm","time","2014-05-09 17:48:34","username","asdf"]
What would I have to do to group chat with the message, date with the date, and username with the username in a key-value pair?
The format of the mysql_fetch_assoc should be
array('chat'=>'Some chat', 'time_sent'=>'123456', 'username'=>'abcdefg')
json_encode would directly translate this to
{"chat":"Some chat", "time_sent":"123456", "username":"abcdefg"}
So in your loop, if you simply do $mesages[] = $row; and leave your json_encode call as-is, it should work as shown above. However, you can alter your SQL statement to give the columns an alias so that time_sent simply shows as the property time
This is what i would do:
$SQL = sprintf('SELECT time_sent, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = array();
while ( $row = mysql_fetch_assoc($result) ) {
$arr = array();
$arr['chat'] = $row['chat'];
$arr['time'] = $row['time_sent'];
$arr['username'] = $row['username'];
$messages[] = $arr;
}
$loopCount = count($chats);
if(count($messages) > 0){
echo json_encode($messages);
}
This will output if not encoded:
Array
(
[0] => Array
(
[chat] => chat_0
[time] => time_sent_0
[username] => username_0
)
[1] => Array
(
[chat] => chat_1
[time] => time_sent_1
[username] => username_1
)
[2] => Array
(
[chat] => chat_2
[time] => time_sent_2
[username] => username_2
)
[3] => Array
(
[chat] => chat_3
[time] => time_sent_3
[username] => username_3
)
)
And this if encoded:
[{"chat":"chat_0","time":"time_sent_0","username":"username_0"},
{"chat":"chat_1","time":"time_sent_1","username":"username_1"},
{"chat":"chat_2","time":"time_sent_2","username":"username_2"},
{"chat":"chat_3","time":"time_sent_3","username":"username_3"}]
To parse the JSON
lets say you have your JSON results in a data var
var obj = $.parseJSON(data);
$.each(obj, function(i, value){
console.log(value.chat);
});
You need to work with multi-dimensional arrays in order to get this to work. The code below has been edited to assign values to named indexes and append these to the 2nd level to the $messages array.
$messages = Array();
while ( $row = mysql_fetch_assoc($result) ) {
$messages[] = Array(
'chat' => $row['chat'],
'time' => $row['time_sent'],
'username' => $row['username']
);
}
The while cycle should be like this:
while ( $row = mysql_fetch_assoc($result) ) {
$arr = array();
$arr['chat'] = $row['chat'];
$arr['time'] = $row['time_sent'];
$arr['username'] = $row['username'];
$messages[] = $arr;
}
Save a little time by getting the field names correct within the SQL.
$SQL = sprintf('SELECT time_sent as `time`, chat, username FROM Messages where time_sent >= date(\'%s\')', $last_chat_time);
$result = mysql_query($SQL);
$messages = array();
while ($row = mysql_fetch_assoc($result)) {
$messages[] = $row;
}
echo json_encode($messages);
IMO returning an empty array when there are no messages is better than returning nothing, as now you have a way to differentiate if your php worked vs if you had no messages, from within your JavaScript code.

nested javascript array to php array

I have a javascript array :
disharray = ([aa,11,],[bb,22])
I send this to php as a json object using - var jsoncvrt = JSON.stringify(disharray);
How do I extract the value of the nested arrays so that I can access values like:
$a = aa and $b = 11?
I use the below code but get the output as
aa11
bb22
Please note, my server uses php 5.2
$data = json_decode(stripcslashes($_POST['strings']));
foreach ($data as $d => $v) {
foreach ($v as $v1 => $value) {
echo $value;
}
}
Your code is fine. Just add this at the top of the code
$values = array();
Now change the inner foreach loop to
if( sizeof($v) == 2 ){
$values[$v[0]] = intval($v[1]);
}
Now to access, say the value corresponding to 'aa' just use $values['aa']
You can insert it into a table using the following code
$con = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DBNAME);
$query = "INSERT INTO tablename (key, value) VALUES(?, ?);";
$stmt = $con->prepare($query);
if( $stmt ){
foreach ($values as $key => $value){
$stmt->bind_param("sd", $key, $value);
$stmt->execute();
}
$stmt->close();
}
$con->close();
In the $query variable, the '?' stands for wild card character that can take any value and it is set by calling bind_param() function. In the bind_param function, the 's' stands for string and the 'd' stands for integer data type. This is the right way to execute database queries as they void the possibility of SQL Injections.

Categories

Resources