我想創建一個json輸出,但是在將一些舊代碼轉換爲mysqli時出現了一些錯誤。使用php創建Json輸出頁面
下面是完整的代碼:
<?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個錯誤:...查看代碼中的註釋上述
警告:mysqli_query()預計參數2爲字符串,對象在...
警告:mysqli_fetch_array()期望參數1是mysqli_result,null給出在...
Op實際上使用'mysqli'而不是'mysql' – Fabio
對,我拼錯'mysqli_fetch_array'函數。 –