PHP turn data into json array - php

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']);

Related

Error while display json from sql database - PHP

I made a script to display data from online SQL database into JSON format.
The problem is, I don't have the format i was looking for, I get 2 [ more while i wanted only one:
A part of my script:
$sql = "select pseudo, dixsec from user;";
$result = mysqli_query($conn,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
$arrray = array("server_response" => array($rows));
print json_encode($arrray);
What i get (You can see here that i have 2 "["):
Json i get
How can i solve it and get only one "[" ?
$rows is already an array.
Try with: $arrray = array("server_response" => $rows);

How to add a data to each JSON object 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

How to roam in SQL query more than one time in PHP

A friend of mine has asked me a question which i do not know how.
The problem is he wants to use a result set of a query more than one time. Whenever he wants.
There is example tables and example output attached.
I will query two times only:
Select * from ornek1_ust
Select * from ornek1_alt
Is it possible to roam in a result set we already have with PHP to have some output like example output. I want to query database with full data for once. Then i want to use it wherever i want whenever i want.
Example Tables:
Example Output:
You'd want to "cache" the results within PHP. To fetch the data, you'd do a simple join query:
SELECT ornek_ust1.isim AS ust, ornek1_alt.ism AS alt
FROM ornek_ust1
JOIN ornek1_alt ON ornek_ust1.id = ornek1_alt.ust_ID
ORDER BY ornek_ust1.isim, ornek1_alt.ism
and within PHP, do something like:
$data = array();
$sql = "SELECT ...";
$res = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($res)) {
$data[$row['ust'][] = $row['alt'];
}
which will build an array that looks like your desired data:
$data = array(
'ust data1' => array(
0 => 'alt data 1'
1 => 'alt data 2'
),
'ust_data2' => ... etc...
)
It sounds like you want to be using mysql_result() to be able to pull out data from a resultset at will.
If you want to loop through the whole dataset and still have it available to loop through again, you can use mysql_data_seek() to set the internal pointer back to the beginning.
Just store the query results in an array....
$sql = "Select * from ornek1_ust";
$results = array();
$query = mysql_query($sql);
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$results[] = $row;
}
// Use $results further on in your code

Adding items to a multi-dimensional array during query while loop

I have a query returning data that looks like this:
Status Total
Success 234
Failed 20
Missing 12
I want to add this to an array which can then be used to populate a google pie chart.
the array would look like this:
array backup = array("Success" => 234),
("Failed" => 20),
("Missing" => 12);
How would I add these item dynamically at each row in a query?
$result = mysql_query(...);
$backup = array();
while ($r = mysql_fetch_assoc($result)) {
$backup[$r['Status']] = $r['Total'];
}
Here's how you can make the Google Charts API call:
$values = implode(',', array_values($backup));
$labels = implode('|', array_keys($backup));
$img = "http://chart.apis.google.com/chart?cht=p3&chd=t:{$values}&chl={$labels}&chs=250x100";
echo "<img src='{$img}' alt='Chart'>";
Assuming this is your query:
SELECT status, total FROM table
Then you can do:
$data = array();
while(($row = mysql_fetch_assoc($result))) {
$data[$row['status']] = $row['total'];
}
If this is not what you mean, please clarify your question and/or provide the code you already have.
I think we need a bunch more information, but in the mean time look at array_merge()
http://www.php.net/manual/en/function.array-merge.php

PHP Sorting associative-array by other array

I need to sort an associative-array in the exact order of the content of another array.
The Arrays are retrieve by 2 separate sql-requests (stated below). The requests could not be combined to only one request, so I have to sort the second array into the order of the first one.
These are the arrays:
#Array which contains the id's in needed order
$sorting_array = array(1,2,3,8,5,6,7,9,11,10...);
#Array which contains the values for the id's, but in order of "id" ASC
$array_to_sort = array(
array("id" => "1", "name" => "text1", "help" => "helptxt2");
array("id" => "2", "name" => "text2", "help" => "helptxt2");
);
The SQL-Queries:
SQL-Ouery for $sorting_array: (the db-field 'conf' is setup as "text", maybe this is my problem so that I have to first explode and implode the entries before I could use it for the next query.)
$result = sql_query("select conf from config where user='me'", $dbi);
$conf = sql_fetch_array($result, $dbi);
$temp = explode(',', $conf[0]);
$new = array($temp[0], $temp[1], $temp[2], $temp[3],$temp[4],
$temp[5], $temp[6], $temp[7], $temp[8], $temp[9],
$temp[10], ...);#Array has max 30 entries, so I count them down here
$sorting_array = implode(',', $new);
SQL-Ouery for $array_to_sort:
$result = sql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'");
while ($array_to_sort[] = mysql_fetch_array ($result, MYSQL_ASSOC)) {}
array_pop($array_to_sort);#deleting the last null entry
I could access $array_to_sort as follows to see the content one by one:
(if the lines below don't match the array above, than I mixed it up. However, the lines below is what brings the content)
echo $array_to_sort[0]["id"];
echo $array_to_sort[0]["name"];
echo $array_to_sort[0]["helptxt"];
But it is sorted by "id" ASC, but I need exactly the sorting as in $sorting_array.
I tried some things with:
while(list(,$array_to_sort) = each($sorting_array)){
$i++;
echo $array_to_sort . "<br>";
}
which only brings the Id's in the correct order, but not the content. Now I'm a bit confused, as I tried so many things, but all ended up in giving me the same results.
Maybe the sql-query could be done in one step, but I didn't brought it to work.
All results to my searches just showed how to sort ASC or DESC, but not what I want.
Furthermore I must confess that I'm relative new to PHP and MySQL.
Hopefully some one of you all could bring me back on track.
Many thanks in advance.
To fetch your results:
$result = mysql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'");
$array_to_sort = array();
while ( ($row = mysql_fetch_assoc($result)) !== false ) {
// associate the row array with its id
$array_to_sort[ $row[ "id" ] ] = $row;
}
To display them in order of $sorting_array:
foreach ( $sorting_array as $id ) {
// replace the print_r with your display code here
print_r( $array_to_sort[ $id ] );
}
And a bonus tip for the code fetching $sorting_array:
$result = mysql_query("select conf from config where user='me'", $dbi);
$conf = mysql_fetch_array($result, $dbi);
$temp = explode(',', $conf[0]);
// limit to 30 ids
$new = array();
// no need to do this manually, use a loop
for ( $i = 0; $i < 30; ++$i )
$new[] = $temp[ 0 ];
$sorting_array = implode(',', $new);
Its a little hard to tell because there is a lot going on here, in the future you'll probably get better/more responses if you ask several simple questions and figure out yourself how to make the answers fit together.
Your best bet long term is going to be to restructure your SQL tablessuch that you can combine these query together. You can do what you're asking in PHP, but it's going to be slower than doing it in MySQL and much more complicated.
To do what you're asking (pretty slow in PHP):
$sorted = array();
foreach ( $sorting_array as $id )
{
foreach ( $array_to_sort as $values )
{
if ( $values['id'] == $id )
{
$sorted[] = $values;
break;
}
}
}
what I tend to do in such a situation is first to rearrange the array with the data. so the keys represent ids
In your case:
$array_to_sort_ids = array();
foreach ($array_to_sor as $item)
{
$array_to_sort_ids[$item['id']] = $item;
}
Then sorting is as simple as:
$array_sorted = array();
foreach ($sorting_array as $id)
{
$array_sorted[] = $array_to_sort_ids[$id];
}
This solution is quite efficient, since you only have 2 foreach loops.
EDIT!!!
As I couldn't edit my question anymore, I just like to state my solution this way:
The tip to rethink my database was what brought me to some testings and then I found the solution, with the following query:
$result = sql_query("SELECT id, name, helptxt
FROM table
WHERE id IN ($sorting_array)
AND language='english'
ORDER BY FIELD(id,$sorting_array)");
while ($array_to_sort[] = mysql_fetch_array ($result, MYSQL_ASSOC)) {}
array_pop($array_to_sort);#deleting the last null entry
Just the line:
ORDER BY FIELD(id,$sorting_array)
will do the trick. It orders the results the way you want, even if this means 1,4,2,3,9,7,...
Sometimes it's so easy, when you know where to look.
Thanks again!!!

Categories