收到PHP错误警告:fputcsv()期望参数2为数组 [英] Getting PHP error Warning: fputcsv() expects parameter 2 to be array
问题描述
我有mysql
个具有不同表的数据库.表之间的数据已链接,我使用userid检索并显示它们.我使用了PHP MYSQLi中显示数据库中所有表的引用.我使用fputcsv($fp, $val)
将结果输出到.csv
文件中,但出现此错误:
I have mysql
db with different tables. The data between the tables are linked and I retrieve and display them by using the userid. I used the reference from PHP MYSQLi Displaying all tables in a databases. I used fputcsv($fp, $val)
for outputting the result in .csv
file, but I get this error:
警告:fputcsv()期望参数2为array **.这是我的代码:
Warning: fputcsv() expects parameter 2 to be array** . This is my code:
<?php
$con=mysqli_connect("localhost","root","","mytable");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT user_id FROM tbl_users";
$users_profile_user_id = mysqli_query($con, $sql);
$row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC);
$fp = fopen("user_profile_id.csv", "w");
foreach($row as $val) {
fputcsv($fp, $val);
}
fclose($fp);
?>
我还尝试用var_export($ val)替换 fputcsv($ fp,$ val),它仅显示数据库中的1个条目.现在我知道为什么它显示错误,因为它显示了一个字符串,但是它的解决方法是什么?如何从数据库中获取所有条目,并在.csv文件中显示所有这些元素?
I also tried replacing fputcsv($fp, $val) with var_export($val) and it is showing just 1 entry from database. Now I know why is it displaying error because it is showing a string, but what is the fix to it? How can I take all the entries from database, and display all those elements in .csv file?
推荐答案
您必须给它提供一个数组,所以可以尝试这样
You have to give it an array so try it like this
$con=mysqli_connect("localhost","root","","mytable");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT user_id FROM tbl_users";
$users_profile_user_id = mysqli_query($con, $sql);
$fp = fopen("user_profile_id.csv", "w");
while($row = mysqli_fetch_array($users_profile_user_id, MYSQLI_ASSOC)){
fputcsv($fp, $row);
}
fclose($fp);
这篇关于收到PHP错误警告:fputcsv()期望参数2为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!