用php创建一个Json输出页面

时间:2014-03-05 23:25:15

标签: php json

我正在尝试创建一个json输出但是在将一些旧代码转换为mysqli时我遇到了一些错误。

以下是完整代码:

<?php 

$con=mysqli_connect("localhost","root","pass","db"); 

if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = mysqli_query($con,"SELECT * FROM users");


$response = array();

$users = array();

$result=mysqli_query($con, $sql); //ERROR 1 points here

while($row=mysqli_fetch_array($result)) //ERROR 2 points here
{ 
$firstname=$row['first_name']; 
$lastname=$row['last_name']; 

$users[] = array('firstname'=> $firstname, 'lastname'=> $lastname);

} 

$response['users'] = $users;

$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);


?>

我收到2个错误:...请参阅上面代码中的评论

  1. 警告:mysqli_query()期望参数2为字符串,对象在...中给出

  2. 警告:mysqli_fetch_array()要求参数1为mysqli_result,在...中给出为null

2 个答案:

答案 0 :(得分:1)

第一个错误是因为您已在此处查询数据库

$sql = mysqli_query($con,"SELECT * FROM users");

删除此行

$result=mysqli_query($con, $sql); //remove this line

并使用$sql对象来获取数据以避免第二个错误

while($row=mysqli_fetch_array($sql)) 
                             //^Change here from $result to $sql

答案 1 :(得分:0)

您正在给mysqli_query一个对象而不是一个字符串:

$sql = mysqli_query($con,"SELECT * FROM users");

$result=mysqli_query($con, $sql); //ERROR 1 points here

来自php documentation

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries 
mysqli_query() will return a mysqli_result object. For other successful queries 
mysqli_query() will return TRUE.

第二个错误是第一个错误的结果,你应该将$ sql提供给mysqli_fetch_array函数。