Reputation: 473
I am a novice in Json and I am not able to fill json list with data gathered from mysql query. Only one value is filled in the list and it keeps repeating rather than showing all the values. The code is:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('abcd');
$jsonData = 0;
$result = mysql_query("SELECT picname,title,date,time,location,timestamp FROM uploaded_photo_data ORDER BY timestamp DESC ");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($result) > 0) {
$num = mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
$a = $row['location']."/".$row['picname'];
echo $row['timestamp'];
echo $a;
echo $row['picname'];
echo $row['title'];
echo $row['location'];
echo "<br></br>";
$dir = $row['location']."/";
$jsonData = '{';
$x = 0;
$dirHandle = opendir($dir);
while($x!=$num){
$x++;
$jsonData .= '"img'.$x.'":{ "num":"'.$x.'","title":"'.$row['title'].'","src":"'.$a.'", "timestamp":"'.$row['timestamp'].'"},<br></br> ';
}
}
}
closedir($dirHandle);
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData; echo $x;
Upvotes: 0
Views: 2121
Reputation: 1259
You can encode an array to JSON with the json_encode
method.
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
The above example will output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
php.net/manual/en/function.json-encode.php
EDIT:
Maybe this works for you:
$jsonData = array();
while ($row = mysql_fetch_assoc($result)) {
$a = $row['location']."/".$row['picname'];
echo $row['timestamp'];
echo $a;
echo $row['picname'];
echo $row['title'];
echo $row['location'];
echo "<br></br>";
$dir = $row['location']."/";
$x = 0;
while($x!=$num){
$x++;
$img = 'img'.$x;
$jsonData[$img] = array(
"num" => $x,
"title" => $row['title'],
"src" => $a,
"timestamp" => $row['timestamp']
);
}
}
print json_encode($jsonData);
Upvotes: 4