php 简单的 Ajax Jquery 脚本 - 如何获取表中每一行的信息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8019489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple Ajax Jquery script- How can I get information for each of the rows in the table?
提问by TryHarder
I'm following a simple ajax>php>mysql example posted here http://openenergymonitor.org/emon/node/107
我正在关注这里发布的一个简单的 ajax>php>mysql 示例http://openenergymonitor.org/emon/node/107
I can only display information from the first row. My table is set up like so
我只能显示第一行的信息。我的桌子是这样摆的
--------------
| id | name|
--------------
| 1 | Pat |
| 2 | Joe |
| 3 | Rob |
--------------
The php code
php代码
$result = mysql_query("SELECT * FROM $tableName"); //query
$array = mysql_fetch_row($result); //fetch result
echo json_encode($array);
The script
剧本
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(data)
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});
ROW 1
第 1 行
If I put the var id = data[0];
I get the value 1.
If I put the var name = data[1];
I get Pat.
如果我把var id = data[0];
我得到值1。如果我把var name = data[1];
我得到帕特。
ROWS 2 n 3 are undefined
ROWS 2 n 3 未定义
Example var id=data[2];
returns undefined
etc
示例var id=data[2];
返回未定义等
My Questions
我的问题
Why do I only get the values from the first row?
How can I get information for rows other than the first one?
为什么我只从第一行获取值?
如何获取除第一行以外的行的信息?
From other questions on Stackoverflow I see that I will probably have to use a while loop, but I'm not really sure why or how.
从 Stackoverflow 上的其他问题我看到我可能不得不使用 while 循环,但我不确定为什么或如何。
回答by ComFreek
The old MySQL extension mysql
is outdated, better use mysqli
or PDO
!
旧的 MySQL 扩展mysql
已经过时,更好用mysqli
还是PDO
!
mysql_fetch_row()
returns only 1 row!
You have to put it into a loop, for example:
mysql_fetch_row()
仅返回 1 行!您必须将其放入循环中,例如:
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
You also have to change the JavaScript:
您还必须更改 JavaScript:
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
$('#output').append("<b>id: </b>"+id+"<b> name: </b>"+vname)
.append("<hr />");
}
}
});
By the way I would recommend you to use mysql_fetch_assoc()
because it makes your code more flexible and cleaner.
顺便说一下,我建议您使用mysql_fetch_assoc()
它,因为它使您的代码更加灵活和简洁。
回答by Elfaks
$result = mysql_query("SELECT * FROM $tableName");
$array = array(mysql_fetch_row($result));
// To store every row in the $array
while($row = mysql_fetch_row($result)) {
$array[] = $row;
}
echo json_encode($array);