我是php的新手。我正在努力从数据库中获取结果,并将这些以Json格式发送的详细信息发送到ajax调用。而我无法使用json_encode进行转换。 我希望以
的格式获得结果[{"id":1,"name":"Rafael","password":"rafael"},{"id":1,"name":"nadal","password":"nadal"}]
我的PHP代码是
// credentials of MySql database.
$username = "root";
$password = "admin";
$hostname = "localhost";
$jsonArray = array();
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("Angular",$dbhandle)
or die("Could not select Angular");
//execute the SQL query and return records
$result = mysql_query("SELECT name,password FROM User");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
$id = $row{'id'};
$name = $row{'name'};
$password = $row{'password'};
$jsonData = json_encode($name,$password);
}
echo "Json:".$jsonData;
答案 0 :(得分:0)
json_encode中的参数必须是数组。
你应该使用
$jsonData = json_encode( $array ); //$array is your array element
答案 1 :(得分:0)
将mysql_query
后的代码更改为:
while($row = mysql_fetch_assoc($result))
{
$jsonArray[] = $row;
}
echo json_encode($jsonArray);
请注意,您不要在查询中选择ID。它应该是
$result = mysql_query("SELECT id, name, password FROM User");
答案 2 :(得分:0)
使用像这样的东西
$ queryString =" SELECT * FROM user&#34 ;;
$ query = mysql_query($ queryString)或die(mysql_error());
$db = array();
while($dbs = mysql_fetch_assoc($query)) {
$db[] = $dbs;
}
echo
$output = json_encode(array(
"success" => mysql_errno() == 0,
"information" => $db
));
myoutput看起来像这样;
它将显示数据库表中的所有字段
{"成功":真,"信息":[{" ID":" 1""用户名&# 34;:" sampleName""名字":" SampleLastName"}] }
希望它有效:D