如何在MySQL + PHP中获取所有结果行?
你知道,如果我使用mysql_fetch_assoc()
,它只会返回一个结果行作为关联数组。我正在使用AJAX来获取MySQL表中的数据。
$result=mysql_query("select * from questions where announcementid='$taskid'")or die(mysql_error());
如何将$ result的值作为数组返回到触发Ajax请求的页面?
答案 0 :(得分:0)
// fetch the results from mysql
$row = mysql_fetch_assoc( $result );
// output them, encoded as a javascript object
echo json_encode( $row );
http://php.net/manual/en/function.json-encode.php
然后,您可以在客户端的javascript代码中以数组的形式访问数据。
答案 1 :(得分:0)
我认为您可以在PHP代码中添加while
函数,并执行与rikh suggested相同的功能:
$results = array();
while ( $row = mysql_fetch_assoc( $result )) {
$results[] = $row;
}
// output them, encoded as a javascript object
echo json_encode( $results );