I am using the code below to get information from a database and make it into JSON (it may be wrong).
Unfortunately it won't load in my web browser, it just says it's loading but it doesn't finish. Please can you tell me what I am doing wrong.
$query = mysql_query("SELECT * FROM Posts ORDER BY date DESC") or die(mysql_error());
$array = array();
while ($row = mysql_fetch_assoc($query)) {
$array[] = $row;
$postID = $row['id'];
while ($ra = mysql_fetch_assoc(mysql_query("SELECT * FROM Comments WHERE postID = '$postID'"))) {
$array['comments'] = $ra;
}
while ($rd = mysql_fetch_assoc(mysql_query("SELECT * FROM Likes WHERE postID = '$postID'"))) {
$array['likes'] = $rd;
}
}
echo json_encode($array);
You are executing mysql_query in the infinite loop:
on each iteration you query the database, and fetch the first row. Change it to
$res = mysql_query("SELECT * FROM Comments WHERE postID = '$postID'");
if (!$res)
{
// handle error
}
while ($ra = mysql_fetch_assoc($res))
{
....
}
And the same for your second query.
Related
I am using these queries in my php page and I think there is a better way to do the same thing.
$cms1 = getRow("select * from cms where cmsID=1");
$cms2 = getRow("select * from cms where cmsID=2");
$cms3 = getRow("select * from cms where cmsID=3");
$cms4 = getRow("select * from cms where cmsID=4");
$cms5 = getRow("select * from cms where cmsID=5");
I am printing the data from these queries like
<?=$cms['content']?>
<?=$cms2['content']?>
<?=$cms3['content']?> ....
Is there a better way to do this or to get all this data in one single query? I think I might get the result by using AS key in the query but I have no idea how.
function getRow($query)
{
$rs = mysql_query($query) or die(mysql_error());
$result = array();
if(mysql_num_rows($rs))
{
$row = mysql_fetch_assoc($rs);
return $row;
}
}
This can also be best achieved using
BETWEEN
in mysql
SELECT * FROM cms WHERE cmsID BETWEEN 1 AND 5;
For more information on Between clause, you can visit this Link
$arrData = array();
$result = mysql_query($query) or die(mysql_error());
while($row = $result->fetch_array()) {
array_push($arrData,$row);
}
print_r($arrData);
First of All change your function
function getRow($query)
{
$rs = mysql_query($query) or die(mysql_error());
$result = array();
if(mysql_num_rows($rs))
{
while($row = mysql_fetch_assoc($rs))
{
$record[$row['cmsID']] = $row;
}
return $record;
}
}
Then change your query
$output = getRow(select * from cms where cmsID in (1,2,3,4,5));
Then echo your output.
print_r($output);
use mysql IN
select * from cms where cmsID in (1,2,3,4,5)
You can use IN clause to replace many OR conditions
$sql = "select * from cms where cmsID in (1,2,3,4,5)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['cmsID'].' '.$row['content'];//output like :- 1 content
}
for($i=1;$i<=5; $i++) {
$cms1 = getRow("select * from cms where cmsID='".$i."'");
}
I need to encode a table content to JSON in order to insert it into a file.
The output has to be as following :
{
"name1":[{"id":"11","name":"name1","k1":"foo","k2":"bar"}],
"name2":[{"id":"12","name":"name2","k1":"foo","k2":"bar"}],
}
Indeed, each JSON "line" corresponds to the content of the mysql row and the name of each JSON array is the name of the 'name' column.
The only thing I could manage for the moment is this :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
$index = 0;
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$index] = $row;
$index++;
}
echo json_encode($return_arr);
And here is the output I get :
[
{"id":"11","name":"name1","k1":"foo","k2":"bar"},
{"id":"12","name":"name2","k1":"foo","k2":"bar"},
]
Thanks a lot !!!
UPDATED
Working code :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$return_arr[ $row['nom_appart'] ][] = $row;
}
echo json_encode($return_arr);
}
You were close. I noticed you want final output to be an object not an array, because the outer brackets are {} not []. So you need a different object type, and you need to use each row's name as the key for storing that row.
$return_obj = new stdClass();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
$return_obj->$name = [$row]; // for PHP < 5.4 use array($row)
}
echo json_encode($return_obj);
This loop is enough, to create the desired JSON:
$return_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$row['name']][] = $row; #or $return_arr[$row['name']] = [$row];
}
echo json_encode($return_arr);
I was working on it a lot of time and Create mash/mysql-json-serializer package.
https://github.com/AndreyMashukov/mysql-json-serializer
You can select Json_array of json_objects and etc. It support ManyToMany, oneToMany, manyToOne relations
SELECT JSON_ARRAYAGG(JSON_OBJECT('id',est_res.est_id,'name',est_res.est_name,'advert_groups',(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',adg.adg_id,'name',adg.adg_name)) FROM advert_group adg INNER JOIN estate est_2 ON est_2.est_id = adg.adg_estate WHERE est_2.est_id = est_res.est_id))) FROM (SELECT * FROM estate est LIMIT 1 OFFSET 2) est_res
<?php
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$return_arr[] = $row;
}
echo json_encode($return_arr);
?>
Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.
I have one problem, when i´m going to run the app i receive one System.err: no value for anotacoes!
I think my problem is on php code. If someone help me i'll appreciate a lot your help.
(Sorry for my bad english ;) )
<?php
// array for JSON response
$response = array();
$response1 = array();
mysql_connect("localhost","root",""); // host, username, password...
mysql_select_db("mobimapa"); // db name...
// check for post data
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT id_anotacao FROM processo_anotacoes WHERE id_processo = $pid");
// check for empty result
if (mysql_num_rows($result) > 0) {
//$response["processo_anotacoes"] = array();
$processo_anotacoes = array();
while ($row = mysql_fetch_array($result)){
array_push($processo_anotacoes, $row["id_anotacao"]);
// $processo_anotacoes["id_anotacao"] = $row["id_anotacao"];
// $processo_anotacoes["id_processo"] = $row["id_processo"];
// success
//$response["success"] = 1;
// user node
// $response["processo_anotacoes"] = array();
}
// echo json_encode($processo_anotacoes);
}
$ids = join(', ',$processo_anotacoes);
$result1 = mysql_query("SELECT * FROM anotacoes WHERE id_anotacao IN ($ids)");
if (mysql_num_rows($result1) > 0) {
$response1["anotacoes"] = array();
// check for empty result
while ($row1 = mysql_fetch_array($result1)) {
//$result1 = mysql_fetch_array($result1);
$anotacoes = array();
$anotacoes["id_anotacao"] = $row1["id_anotacao"];
$anotacoes["nome"] = $row1["nome"];
$anotacoes["descricao"] = $row1["descricao"];
// success
$response1["success"] = 1;
// user node
$response1["anotacoes"] = array();
array_push($response1["anotacoes"], $anotacoes);
}
// echoing JSON response
echo json_encode($response1);
}
?>
08-12 17:09:03.308: D/All Products:(806):
{"success":1,"processo":[{"data":"2013-07-17","id_processo":"1","nome":"Processo
1","imagem":"Later"},{"data":"2013-08-04","id_processo":"2","nome":"Processo
2","imagem":"Later"}]} 08-12 17:09:03.518: I/Choreographer(806):
Skipped 110 frames! The application may be doing too much work on its
main thread. 08-12 17:09:29.238: D/Processo clicado(806): 2 08-12
17:09:29.838: D/Single Product Details(806):
{"product":[{"data":"2013-08-04","id_processo":"2","nome":"Processo
2","imagem":"Later"}],"success":1} 08-12 17:09:30.028: D/Anotacoes
Details(806):
{"success":1,"anotacoes":[{"descricao":"teste","id_anotacao":"3","nome":"Anotacao
3"}]}
The problem is with the PHP variable being passed to the 2nd SQL query. This not the complete code; but if you understand it, it will solve your problem:
$anotacaos = array();
while ($row = mysql_fetch_array($result))
array_push($anotacaos, $row["id_anotacao"]);
$ids = join(',',$anotacaos);
$result1 = mysql_query("SELECT * FROM anotacoes WHERE id_anotacao in ($ids)");
while ($row = mysql_fetch_array($result1))
//do something...
I am executing a query like this (PHP + MySQL):
$query = "SELECT * FROM tablename WHERE 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
// PHP Statement
}
I want to use the same result again on the same page then i need to execute query again like this:
$query = "SELECT * FROM tablename WHERE 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
// PHP Code
}
then it works. But if I use only
while($row = mysql_fetch_array($result))
{
// PHP Code
}
Then it doesn't work. Is there any other way to use the result many times on the same page without executing query every time?
I know i can use the same result to make an array. but is there any other way?
I believe mysql_data_seek will do this for you.
<?php
function mysql_pointer_position($result_set) {
$num_rows = mysql_num_rows($result_set);
$i = 0;
while($result = mysql_fetch_array($result_set)) {
$i++;
}
$pointer_position = $num_rows - $i;
//Return pointer to original position
if($pointer_position <= $num_rows - 1) {
mysql_data_seek($result_set, $pointer_position);
}
return $pointer_position;
}
?>