Multiple rows of data from table into JSON array - php

I have been on this for nearly a full 24 hours now.
I am not a coder and I am not pretending to be, I just have a problem I cannot solve that I'd like your help with :)
I have a database column full of latitude and longitude locations. I want to create a file called points.json which matches the following format:
{
"points": [
[LAT, LONG],
[LAT, LONG],
[LAT, LONG],
[LAT, LONG],
[LAT, LONG]
]
}
Where LAT and LONG are the records from the database (52.93839800000001,-1.1425212999999999)
My current code gets all the locations from the database and outputs on screen one lat/long per row:
$sql = "SELECT latlong from requests";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['latlong'] . "<br>";
}
} else {
echo "0 results";
}
$con->close();
Table structure:
|id|user| latlong |
----------------------------------
|1|user|52.93839801,-1.1425212999|
I just cannot work out to get it into the above format. I have tried a number of different json_encode methods but end up with separate JSON array for each row?
Ultimately I want to generate a file in the above format on the fly containing the location refs saved in the database column/row.
Thanks in advance.

Try exploding your latlong and push the values to an array.
$sql = "SELECT latlong from requests";
$result = $con->query($sql);
$points = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$points[] = explode(',', $row['latlong']);
}
}
$con->close();
echo json_encode(array('points' => $points));

If you are using a newer version of MySQL, try the following:
SELECT JSON_OBJECT(
'points', JSON_ARRAYAGG(
JSON_ARRAY(LAT, LONG)
)
FROM yourTable;
If that doesn't help, share your table structure and your database version.
If you want to try on your own, check out PHP's json_encode()

You can use below code :
$sql = "SELECT latlong from requests";
$result = $con->query($sql);
$points = array();
$i=0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$latlong = explode(",", $row['latlong']);
$points['points'][$i] = $latlong;
$i++;
}
}
print_r((json_encode($points)));

Related

How can I separate. to my database variable?

I have few data in mysql(link,description,date,del(delete status))
now Im taking this data from mysql with my code. But I wanna show my data's like this photo
as you can see all data's looks clear and separate.
Im using this sql code for take these data's
$sql = "SELECT `vLink` ,`vDescription`, `vDate` FROM `video_table`
But when I use my code output looks like
https://www.youtube.com/watch?v=D8f9IiUXA4EMYSQL | How to auto date time with MYSQL?2021-01-17 02:32:55
now I can use 3 sql code(for link,description,date) to take my all data's and I can put list each by each but Im wondering have we easy way?
thats my code
$sql = "SELECT `vLink` ,`vDescription`, `vDate` FROM `video_table` WHERE `vDel` = 0 ";
$result = mysqli_query($conn,$sql);
$Vdatas = array();
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result)) {
$Vdatas[] = $row;
}
}
//print_r($Vdatas);
foreach ($Vdatas[0] as $data) {
echo $data;
}

How to display the multiple records in a line from single column and all the rows using php

I have column name called as email. In that, I have more than 100 rows. Some rows have more than 10 records with a comma(,) some have only 1 records. I have to display all the records in one line.
This is my table
I am getting output like
The output I need in one line so that I can export it.
$sql ="SELECT email FROM email12";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$a=$row['email'];
$b = explode(',',$a);
echo '<pre>'; print_r($b);echo '<pre>';
}
}
I would iterate through exploded array:
$sql ="SELECT email FROM email12";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$a=$row['email'];
$b = explode(',',$a);
foreach($b as $email) {
echo '<pre>'; print_r($email);echo '<pre>';
}
}
}
From the database's perspective, it's not recommended and certainly not a good practice to have data as comma separated list. You should consider normalizing your database. Having said that, you should follow the below procedure to achieve the desired result as of now(or for the time being).
Create an empty array(for example, $resultArr) before the beginning of while loop. In each iteration of while loop, explode email column value and append them to $resultArr array. Finally, after coming out of the loop, simply perform implode operation on the resultant array to display all the records in one line.
$sql ="SELECT email FROM email12";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$resultArr = array();
while($row = $result->fetch_assoc()) {
$resultArr[] = explode(',',$row['email']);
}
echo implode(',', $resultArr);
}

Running two select queries in php and encoding it in json format?

I have two tables billing_all and payment_details. I am trying to write php code such that I can run the 2 queries in the same php code and encode their data in json format.I am currently using the following code to achieve that without json encode :-
<?php
include "config.php";
$dbname ="webappdb";
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$dbname);
if(!$con)
{
echo "Connection Error".mysqli_connect_error();
}
else{
//echo "";
}
$sql = "SELECT SUM(total_wt) FROM `billing_all` WHERE date ='15-Apr-2016';";
$sql .= "SELECT pymt_amount, mode_of_pymt FROM `payment_details` WHERE DATE ='15-Apr-2016';";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf("%s%s\n",$row[0],$row[1]);
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
How can I encode the received data in json format? I tried something like:-
// Store first result set
if ($result=mysqli_store_result($con))
{
$r = array();
while($row = mysqli_fetch_array($result))
{
array_push($r,
array('total_wt'=>$row[0],
'pymt_amount'=>$row[0],$row[1],
'mode_of_pymt'=>$row[0],$row[1]));
}
echo json_encode(array("result"=>$r));
Which does not give me the expected result.How can I encode the data
in the right way? The following is the structure for the 2 tables
I am new to programming any help is appreciated.Thank you?
<?php
//Joining both tables on the basis of doc_no column
$sql = "SELECT billing_all.SUM(total_wt) AS total
,payment_details.pymt_amount
,payment_details.mode_of_pymt
FROM billing_all
,payment_details
WHERE billing_all.doc_no = payment_details.doc_no
AND billing_all.DATE = '15-Apr-2016'";
// Executing query
$res = mysqli_query($con,$sql);
//initializing array to store result
$rows = array();
//Iterating result and storing each row in $r then array $rows to covert result set into array because json accept array as parameter.
while($r = mysqli_fetch_assoc($res))
{
$rows[] = $r;
}
//print whole array in json format
echo json_encode($rows); ?>

Selecting multiple rows in a table

I need to select multiple comments (if there are any) based on the photo_id. As I understand it you can use the WHERE clause but I'm not exactly sure how to select multiple ones and store them in some kind of array?
e.g.
$result = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photo1id'");
$row = $result->fetch_assoc(); // but there's more than 1 row
If for example $photo1id == 21, how do I get all the comments (2 in this case)? Some kind of while loop?
At the end of the PHP file I have this:
echo json_encode(array('photo1id'=>$photo1id));
I need to store each row in that array somehow because I need to retrieve the data in another PHP file using $.getJSON. Or perhaps there is a better solution to this.
Loop through it and generate an array -
while($row = $result->fetch_assoc()) {
$comments[] = $row;
}
After that you can send the array as json.
echo json_encode($comments);
Is there is more rows, you need to use a loop.
while ($row = $result->fetch_assoc()) {
// your code here
}
Try the code below:
//Run query
$result = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photo1id'");
//While there is a result, fetch it
while($row = $result->fetch_assoc()) {
//Do what you need to do with the comment
}
If you don't want to print the code straight away you can just create an array:
$x=0;
while($row = $result->fetch_assoc()) {
$comment[$x]=$row['comment'];
$x++;
}

Storing database records into array

I would want to create an array that will hold records retrieved from a database using a query of SELECT statement.
The records to be retrieved have multiple fields such as lastname, firstname, mi and 20 more fields. What would be the best approach on coding this function?
alright i have followed what prisoner have given below.. the next question is how do i search through this kind of array using queries? for example i want to search for a username..
<?php
// run query
$query = mysql_query("SELECT * FROM table");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['username']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['username']; // print the first rows username
You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:
if (isset($_GET['search'])) {
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT * FROM users WHERE username = '$search'";
$res = mysql_query($sql) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($res);
if ($row){
print_r($row); //do whatever you want with found info
}
}
$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
$c++;
}
for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}

Categories