【问题标题】:PHP | fputcsv : generated file only populated with field header, but no recordsPHP | fputcsv :生成的文件只填充了字段标题,但没有记录
【发布时间】:2015-11-02 04:38:18
【问题描述】:

我不明白为什么这段代码只生成一个带有字段标题的文件,但没有记录。

文件内容:

"Article ID",Shoppergroupname,"Promotion Price",VAT-Code,"Article Currency","Promotion Start Date","Promotion End Date"

如你所见,没有记录被“导出”,数据库表也不是空的!

顺便说一句,我也想去掉字段标题引号。

如果有人能帮助我解决这个问题,我们将不胜感激。提前致谢。

马克

@KateMihalikova 提供的解决方案

// Create connection
$conn = new mysqli($databasehost, $databaseusername, $databasepassword, $databasename);

// Check connection
if (mysqli_connect_errno()) {
exit('Connect failed: '. mysqli_connect_error());
}
echo "Connected successfully | ";

// Create filename
date_default_timezone_set('Europe/Zurich');
$today = date("YmdHis"); 
$csvname = "WS_PRICE_IMPORT-".$today.".csv";
$csvfullname = '/var/.../'.$csvname; 


// create a file pointer connected to the output stream
$output = fopen($csvfullname, 'a+');

// output the column headings
fputcsv($output, array('Article ID', 'Shoppergroupname', 'Promotion Price', 'VAT-Code', 'Article Currency', 'Promotion Start Date', 'Promotion End Date'));

 // fetch the data
$sql = "SELECT `Article ID`, `Shoppergroupname`, `Promotion Price`, `VAT-Code`, `Article Currency`, `Promotion Start Date`, `Promotion End Date` FROM jos_temppriceimport";
$result = $conn->query($sql);

if (!$result) {
echo "Unable to execute query in the database : " . mysql_error();
exit;
}

if ($result->num_rows == 0) {
echo "No record found, no record to export in CSV.";
exit;
}

// loop over the rows, outputting them
while ($row = $result->fetch_row()) fputcsv($output, $row);

PS:带空格的字段名由数据提供者提供。

【问题讨论】:

  • if ($conn->query($row) .... 代码块应该做什么? a) 它看起来像 pdo 或 mysqli,而其他代码使用已弃用的 mysql_* 扩展。 b) 在 while 循环之后,$row 必须为 false/null。
  • @VolkerK 谢谢,现在好些了吗?
  • 你还在混用mysql和mysqli,试试$result->fetch_assoc()而不是mysql_fetch_assoc($sql)
  • @KateMihalikova 感谢您的更正,但查询仍然无效
  • 您的代码可能在mysql_num_rows 上失败,请将其更改为$result->num_rows。您还可以在这里和那里添加一些echos 来帮助调试。

标签: php fputcsv


【解决方案1】:

您的代码中的主要问题是混合了过程式mysql、过程式mysqli 和面向对象的mysqli。它们相似,但不能混用。

我们发现主要问题在while循环中。

while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

经过一点迭代后,面向对象的表示法出现了问题,其中使用了对象方法而不是具有属性的函数,但该属性仍然存在。 http://phpfiddle.org/main/code/jcbx-7c0n

while ($row = $result->fetch_row($result)) fputcsv($output, $row); // forgotten attribute
while ($row = $result->fetch_row()) fputcsv($output, $row);        // working just fine

【讨论】:

  • 是的,我的代码是“一团糟”!我是新手,所以我需要提高我的技能,我今天能做的多亏了你。下次我会更仔细、恰当地编写我的查询,并尊重约定。干杯。
【解决方案2】:

您正在循环您的 SQL 语句。你需要循环遍历你的结果。

while ($row = mysqli_fetch_assoc($result)) fputcsv($output, $row);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 2012-05-02
    • 2014-12-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    相关资源
    最近更新 更多