使用php数据库连接我想以json格式显示数据从数据库(MySql)中获取数据,但我无法以json格式显示。 http://takeyourtime.16mb.com/fatchData.php
$con = mysqli_connect($host, $username, $pwd, $db) or die('Unable to connect');
if (mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$name = $_POST['Query'];
$sql = "SELECT * FROM playerstb";
$query = mysqli_query($con,$sql);
if ($query)
{
$rows = array();
while ($r = mysql_fetch_assoc($query)) {
$rows['root_name'] = $r;
}
}
echo json_encode($rows);
mysqli_close($con);
答案 0 :(得分:0)
只需使用json_encode
即可。顺便说一下,你的脚本在结尾 if 块中有语法错误:
if($query){
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows['root_name'][] = $r; // probably must be an array
}
echo json_encode($rows);
}else{
/*
This will show up when you have a query error
nothing to do with the results found.
I would consider changing the message below
*/
echo('Not Found');
}
答案 1 :(得分:0)
你必须将它存储在数组中,例如注意这个([])*
printf
答案 2 :(得分:0)
你必须首先将你的结果存储在数组中然后创建一个数组名称你想要的键($ array [“name”])
$con=mysqli_connect($host,$username,$pwd,$db) or die('Unable to connect');
if(mysqli_connect_error($con))
{
echo "Failed to Connect to Database ".mysqli_connect_error();
}
$name=$_POST['Query'];
$sql="SELECT * FROM playerstb";
$query=mysqli_query($con,$sql);
if($query)
{
$rows = array();
while($r = mysql_fetch_assoc($query)) {
$rows[] = $r;
}
$data["data"]=$rows;
echo json_encode($data);
}
}else
{
echo('Not Found ');
}
mysqli_close($con);
?>