问题描述
我有一个包含5列和多行的数据库.我想获取前3行并将它们作为数组回显.到目前为止,我只能获得第一行(我是PHP和mysql的新手).到目前为止,这是我的PHP:
I've got a database with 5 columns and multiple rows. I want to fetch the first 3 rows and echo them as an array. So far I can only get the first row (I'm new to PHP and mysql). Here's my PHP so far:
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_row($result);
//==== ECHO AS JSON
echo json_encode($array);
我们将不胜感激.
推荐答案
您需要遍历结果. mysql_fetch_row
一次让他们一个.
You need to loop through the results. mysql_fetch_row
gets them one at a time.
http://php.net/manual/en/function.mysql-fetch-row .php
代码最终将像:
$jsonData = array();
while ($array = mysql_fetch_row($result)) {
$jsonData[] = $array;
}
echo json_encode($jsonData);
//json_encode()
请注意mysql扩展在PHP 5.5中已弃用,如注释中所述,您应使用mysqli或PDO.您只需在上面的代码中替换mysqli_fetch_row
即可. http://www.php.net/manual/en/mysqli-result.fetch- row.php
PLEASE NOTEThe mysql extension is deprecated in PHP 5.5, as stated in the comments you should use mysqli or PDO. You would just substitute mysqli_fetch_row
in the code above.http://www.php.net/manual/en/mysqli-result.fetch-row.php
这篇关于MySQL获取所有行并作为JSON回显的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!