How to add a data to each JSON object PHP - php

I'm getting posts details from 'postsTable' with php and encoding it in JSON Like this way
$result_json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($result_json);
each post has a unique ID
Then I have another table called 'postsLikes' I want to see how many Likes the post have using mysqli_num_rows()
But my question is how can I add the data it returns to each object in Encoded JSON ?
$query_checkup = "SELECT * FROM postsTable WHERE Post_AgeFrom < $age AND $age < Post_AgeTo AND Post_Reviewed = 1";
$result=mysqli_query($con, $query_checkup);
$result_json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo "{\"result\":";
echo json_encode($result_json);
echo "}";

You should append extra data to your array before encoding to json.
foreach ($result_json as $key => $result) {
$result_json[$key]['likes'] = getLikes();
}
echo json_encode($result_json);
And you need to implement getLikes function as you wish or can do the operation inside foreach loop.
There a note that you need to pay attention: you need to query for each product to get likes. It is better to join tables and format your array as your need in a loop.

Maybe you can create a new array and use the foreach construct to add the previous values and the new values.
$new_array = array();
foreach($result_json as $result){
$new_array[] = array(
'id' => $result['id'],
'likes' => getlikes($result['id'])
);
}
function getlikes($id){
// your code to get likes number with mysqli_num_rows()
}
echo json_encode($new_array);

You should join the 'postsLikes' table in your original query to pull in all the data you need with a single trip to the database.
Something like this:
(Guessing on how your tables are setup)
$query = "
SELECT
P.* ,
L.Likes
FROM postsTable P
LEFT JOIN postsLikes L ON L.Post_id = P.Post_Id
WHERE
P.Post_AgeFrom < :age AND
:age < P.Post_AgeTo AND
P.Post_Reviewed = 1 ";
$params = array( "age" => $age );
$pdo = new PDO('mysql:dbname=testdb;host=127.0.0.1', $user, password);
$stmt = $pdo->prepare( $query );
$stmt->execute( $params );
$results = $stmt->fetchAll( PDO::FETCH_ASSOC );
$response = array( "results" => $results );
echo json_encode( $response );
Other bits of advice:
1) Use bound parameters to prevent SQL injection.
2) Don't manually create any of the JSON in your response, create the response array first and let json_encode do the rest of the work

Related

fetching an array from MySQL

I am querying MySQL to perform an operation and return an array. To do this I am using the following code:
$return_array = array(
"title" => "nearby media",
"nearby_media_list" => array()
);
$my_query = "select * from `Media`";
$result = $conn->query($my_query);
while($row = $result->fetch_assoc()) {
$mediaLat = $row["lat"];
$mediaLon = $row["lon"];
$calculated_distance = distance( $userLat, $userLon, $mediaLat, $mediaLon, "M");
if( $calculated_distance <= $distance_limit ) {
// Build array
$return_array["nearby_media_list"][] = array(
'uid' => $row['uid']
);
}
}
echo json_encode($return_array);
$conn->close();
?>
and my output looks like this:
{"title":"nearby media","nearby_media_list":[{"uid":"-Kn1f0jo_36qnQBCqjCq"}]}
Since the array only contains one type of data I don't need to store a key and don't need JSON. What I want is a simple array of the values separated by a token so I can take it apart more easily. desired outcome is something like
[value1##$%value2##$%]
Can anyone instruct me how to do this? I haven't had any luck

PDO: PHP foreach array returning null

I did a very short and simple PHP .
The output is an array in json. However it doesn't work .
The array-items are always null.
I guess it must have something to do with mistakenly calling the db table columns
('id' => $row->MASTER_ID).
Whereas 'MASTER_ID' is the name of the column in my db.
I'd be very glad if someone could point me in the right direction.
My script looks as follows:
<?php
$db = new PDO('mysql:host=xxx;dbname=xx;charset=utf8mb4', 'xx', 'xxx');
$month = date('Y-m');
$monthwild = "$month%";
$sql = ("SELECT * FROM MASTER WHERE START_DATE LIKE '". $monthwild ."'");
$out = array();
foreach($db->query($sql) as $row) {
$out[] = array(
'id' => $row->MASTER_ID,
'title' => $row->MASTER_TITLE,
'start' => strtotime($row->MASTER_START),
'end' => strtotime($row->MASTER_END)
);
}
echo json_encode(array('success' => 1, 'result' => $out));
exit;
?>
I'm new to PDO (used to do things like this with mysql) and
I didn't get it yet and didn't find the right resources
PDO::query “executes an SQL statement, returning a result set as a PDOStatement object,” not a row.
You have to put the result in a variable and then retrieve rows from this variable:
$result = $db->query( $sql );
while( $row = $result->fetchObject() )
{
(...)
}
As alternative, you can set a default fetch mode and then retrieve single rows with:
$result = $db->query( $sql );
$result->setFetchMode( PDO::FETCH_OBJ );
while( $row = $result->fetch() )
{
(...)
}
Edit:
Actually, also direct foreach works, but without a specific fetch mode it returns enumerated and associative result:
foreach( $db->query( $sql ) as $row )
{
$id = $row['MASTER_ID'];
// $id = $row[0]; // ← Alternative
}
To use objects with direct foreach you have to use this syntax:
foreach( $db->query( $sql, PDO::FETCH_OBJ ) as $row )
{
$id = $row->MASTER_ID;
}
Read more about PDO::query
Read more about PDOStatement
I'd say that your definition of $monthwild is wrong.
The right notation for that what you want to write is:
$monthwild = $month."%";
In your script is the content of $monthwild the string "$month%"
Now is the content of $monthwild the string %
I hope you can understand that.
It is not easily described.

PHP turn data into json array

I'm trying to get the coordinates from my database and show them as markers on a map using the Jvectormap plugin. But how can I turn the data which I retrieve from my database into a working json array? I've done something similar before with the morrisJs plugin so I know how to encode them to json but I'm having some issues.
As of now my code looks like this:
$sql = "SELECT latitude, longtitude, user_name FROM page_load
INNER JOIN users ON page_load.username = users.user_ID
WHERE bot = 0 AND latitude <> 0 AND longtitude <> 0 LIMIT 10";
$sth = $conn->prepare($sql);
$sth->execute();
$arr = array();
while ($rows = $sth->fetchAll(PDO::FETCH_ASSOC)) {
$arr = $rows;
}
foreach($arr as $row){
$temp = $row['latitude'].", ".$row['longtitude'];
$temp2 = $row['user_name'];
$newarray = array("latLng" => $temp,
"name" => $temp2
);
}
?>
markers: <?php print_r(json_encode($newarray)); ?>
This returns
{"latLng":"52.5, 6","name":"crecket"},
But I need it to look like this according to the guide for this plugin:
{latLng: [52.5, 6], name: 'crecket'},
As you can see I already turned the 2 langtitude and longtitude variables into 1 key for the array but I can't seem to get rid of the quotations.
So my question really is, what steps do I need to take to turn the result I get now into the format I need?
Just make $temp an array:
$temp = array($row['latitude'], $row['longtitude']);

No query result

I have this sql query that returns no result. The table it queries has data but no results being pull. The query is put into an array.
$qry = array();
$qry[] = "SELECT events_id as 'Reference ID', event_level as 'Level', events_date as 'Date', events_time as 'Time', events_opponent as 'Opponent', events_place as 'Place', events_results as 'Results'";
$qry[] = "FROM wp_events WHERE events_id = ".$sched_id."";
$val = array();
$val = implode(" ", $qry);
$result = $wpdb->get_results($val, ARRAY_A);
i var_dump the $result but it only output Array ( ). I also tried to var_dump($val) if there is something wrong on the query but query is ok. I don't know what im missing here. please help.
There are two points in this code which can remain problematic:
Do you always have the $sched_id filled?
Does passing a complete query string to the $wpdb->get_results() return anything?
Try doing a fully complete query in phpMyAdmin to see the expected result and work the PHP code until you have the same results back.
try something like this if u want to print variable values..
<?php
$id = $_GET['value'];//value received from array[]
$N = count($id);
for($i=0; $i <N; $i++)
{
$result_h = mysql_query("SELECT * FROM `table` where id='$id[$i]'");
$pks_h = mysql_fetch_array($result_h);
echo $pks_h['mysql coloumn name'];
}
?>
or use while loop if u want to print only mysql table value.

How do you append to a PDO resultset array or Json_encoded string?

I want to add a bit more information to a json object before sending it back to my app.
$sql = "SELECT * FROM users WHERE repo=?";
$q=$dbh->prepare($sql);
$q->execute(array($repo));
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res['isnew']="1"; //this part isn't working
echo '{"items":'. json_encode($res) .'}';
The PDO query returns a result set like this when I echo($res)
Array{"items":[{"uid":"10","repo":"bnef"}]}
then it gets encoded back to jquery- echo '{"items":'. json_encode($res) .'}';
giving me
{"items":[{"uid":"10","repo":"bnef}]}
I'd like to add "isnew":"1" to that but when I try
$res['isnew']="1"; or array_merge I end up with
{"items":{"0":{"uid":"10","repo":"bnef"},"isnew":"1"}}
which doesn't work. I need
{"items":[{"uid":"10","repo":"bnef, "isnew":"1"}]}
Am I misguide in try to do this?
I misread your question and got confused on the code... you shoudl incat be dealign with an array initially try the following:
$sql = "SELECT * FROM users WHERE repo=?";
$q=$dbh->prepare($sql);
$q->execute(array($repo));
$items = $q->fetchAll(PDO::FETCH_OBJ);
// you actually wnt isnew as a property of each row
// so you need to loop over the results
foreach($items as $key => $item){
$item->isnew = 1;
}
echo json_encode(array(
'items' => $items
));
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res['isnew']="1"; //this part isn't working
Its not working because you used FETCH_OBJ instead of FETCH_ASSOC so youre wokring with an StdObject instance not an array. In that case you need to use -> to assign:
$res = $q->fetchAll(PDO::FETCH_OBJ);
$res->isnew = "1";
Alternatively you could fetch as an associative array:
$res = $q->fetchAll(PDO::FETCH_ASSOC);
$res['isnew']="1"; //this will work now
Additionalyl i wouldnt try to manipulate the JSON serialized string. I would doo all modifications natively:
$items = array(
'items' => $res
);
echo json_encode($items);

Categories