[英]How can I get all values of a mysql table in JSON from a php script?
This is php script that fetches a table values from mysql (one row). 这是从mysql(一行)获取表值的php脚本。 & echoes it as JSON 并将其作为JSON回应
<?php
$username = "user";
$password = "********";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to
connect to MySQL");
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
$query = "SELECT * FROM user_spec";
$result=mysql_query($query);
$outArray = array();
if ($result) {
while ($row = mysql_fetch_assoc($result)) $outArray[] = $row;
}
echo json_encode($outArray);
?>
this is HTML file to receive & print json data. 这是用于接收和打印json数据的HTML文件。
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> //$('document').ready(function() { src =“http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”> // $('document')。ready(function(){
function Preload() {
$.getJSON("http://localhost/conn_mysql.php", function(jsonData){
$.each(jsonData, function(i,j)
{ alert(j.options);});
});}
// });
</script></head>
<body onLoad="Preload()">
</body>
</html> >
Your PHP needs to actually put all the rows together: 您的PHP需要实际将所有行放在一起:
$query = "SELECT * FROM user_spec";
$result=mysql_query($query);
$outArray = array();
if ($result) {
while ($row = mysql_fetch_assoc($result)) $outArray[] = $row;
}
echo json_encode($outArray);
Your Javascript needs to look at each of the rows.. 你的Javascript需要查看每一行..
$.getJSON("/whatever.php", function(jsonData) {
for (var x = 0; x < jsonData.length; x++) {
alert(jsonData[x].options);
}
});
mysql_fetch_assoc
will only return a single row from the database. mysql_fetch_assoc
只返回数据库中的一行。 You will need a loop to retrieve all rows: 您将需要一个循环来检索所有行:
$data = array();
while ($row = mysql_fetch_assoc($result)) {
// add some or all of $row to the $data array
}
echo json_encode($data);
<?php
$username = "user";
$password = "********";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL");
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
$query = "SELECT * FROM user_spec";
$result=mysql_query($query);
$_ResultSet = array();
while ($row = mysql_fetch_assoc($result)) {
$_ResultSet[] = $row;
}
echo json_encode($_ResultSet);
?>
and your jQuery would looks like : 你的jQuery看起来像:
$.getJSON("/yourscript.php", function(data) {
$.each(data, function(i, j) {
// use: j.columnName
});
});
Good luck 祝好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.