-4

Possible Duplicate:
MySQL returns only one row

In Terminal

mysql> select image,title,price from test;

db result:

image title price
 1       2     3
 4       5     6

But, In PHP

.
.
$query=mysql_query("select image,title, price from test",$connect);

$row=mysql_fetch_object($query);

print json_encode($row);

result:

image= 1, title = 2  , price=3

why don't print image=4 title=5 price=6? how?

Community
  • 1
  • 1
석진영
  • 243
  • 4
  • 13

5 Answers5

3

Because you are only printing the first $row

You need a loop:

while ($row = mysql_fetch_object($result)) {
   ...
}
Icarus
  • 63,293
  • 14
  • 100
  • 115
3

If you look at the PHP documentation for mysql_fetch_object(), its purpose is to "Fetch a result row as an object." You have to keep calling until there are no more rows:

$result = mysql_query("select image,title, price from test", $connect);
while ($row=mysql_fetch_object($result)) {
    print json_encode($row);
}
mysql_free_result($result);

Also notice I renamed the return value of mysql_query() to $result, as that's a bit more correct.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • this time Only print image=4, title=5, price=6 don't print image=1 title=2 price=3 why?? – 석진영 Jan 10 '12 at 02:58
  • I'm not sure - is the row still in the database? Try running it again? This is a straightforward code sequence that is in use in many, many PHP scripts. – Jonathon Reinhart Jan 10 '12 at 03:03
1

Try putting the query in a while loop:

while($row = mysql_fetch_object($query ))
{
print json_encode($row);
}
ennuikiller
  • 46,381
  • 14
  • 112
  • 137
1

mysql_fetch_object fetches only a single row. You need to loop through them until there are no more rows, like this:

while (($row = mysql_fetch_object($query)) !== false) {
    // do stuff
}
fivedigit
  • 18,464
  • 6
  • 54
  • 58
1

mysql_fetch_object method returns only first row of result set. You should iterate through result set to get all rows.

cafesolo
  • 11
  • 1