我还是PHP的新手,我正在尝试使用PHP从MySQL检索数据。我有一个存储在csv文件中的id列表(csv的第一列)。所以我试图根据该ID检索数据。
//MySQL Connection
$con=mysqli_connect($hostname,$username,$password,$dbName);
//CSV File
$file_handle = fopen($fileName, "r");
$sql = "SELECT count(*) AS total FROM user WHERE user_id = ";
$i = 0;
while ($i < 50) {
//Retrieving user_id from csv file
$file_line = fgetcsv($file_handle, 1024);
$query = $sql . $file_line[0];
//Retrieving data from mySQL
$result = mysqli_query($con,$query);
//Tested with single row but still giving me an error
//$row = $result->fetch_assoc();
$row = mysqli_fetch_array($result);
echo $row;
$i++;
}
//close file
fclose($file_handle);
//close the connection
mysqli_close($con);
?>
我收到的错误消息:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\.. on line 59
所以,我不确定我做错了什么。任何帮助都会很棒。
更新:
感谢大家的帮助,我能够找出问题所在。这是我所做的更新代码。
$i = 0;
while ($i < 50) {
//Retrieving user_id from csv file
$file_line = fgetcsv($file_handle, 1024);
$user_id = $file_line[0];
$sql = "SELECT count(*) AS total FROM user WHERE user_id = $user_id ";
//Retrieving data from mySQL
$result = mysqli_query($con,$sql);
//Tested with single row but still giving me an error
$row = mysqli_fetch_array($result);
echo $row[0]; //Since this is an array I forgot to retrieve the first index of the array.
$i++;
}
答案 0 :(得分:0)
几乎是对的,你只需要改变:
$row = mysqli_fetch_array($result);
要:
$row = $result->fetch_array(MYSQLI_NUM);
或者只是这样做:
$row = mysqli_fetch_array($result, MYSQLI_NUM);
您必须指定结果类型。
答案 1 :(得分:0)
我想你忘了在这里添加一些变量
$sql = "SELECT count(*) AS total FROM user WHERE user_id = ";
通常就像这样
$sql = "SELECT count(*) AS total FROM user WHERE user_id = " $userId = $file_line[0] "";
有关详细信息,请参阅this。这完全是关于 WHERE 条款,我认为这对你很有帮助。