简体   繁体   English

SQL,PHP导出为CSV

[英]SQL, PHP export to CSV

I have created this php script to pull some data from my database and export it to CSV. 我创建了这个php脚本来从我的数据库中提取一些数据并将其导出为CSV。

I've got headers set to 0,1,2, but I need some static text in column 0. 我已将标头设置为0,1,2,但我需要在第0列中使用一些静态文本。

Eg static, stock code, QTY. 例如静态,股票代码,QTY。

The stock code, QTY are being pulled from the database. 股票代码QTY正从数据库中提取。

Any help would be appreciated. 任何帮助,将不胜感激。

My code is below. 我的代码如下。

// open connection to mysql database
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));

// fetch mysql table rows
$sql = "select ManufacturerPartNumber, (QuantityOnHand - QuantityOnSalesOrder) from iteminventory";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));

$fp = fopen('inventory.csv', 'w');

     fputcsv($fp, array('0', '1', '2'));


while($row = mysqli_fetch_assoc($result))
{
     fputcsv($fp, $row);
}

fclose($fp);

//close the db connection
mysqli_close($connection);

?> ?>

Try this: 尝试这个:

$header = array('Static', 'Stock code', 'QTY');

$fp = fopen('inventory.csv', 'w');

fputcsv($fp, $header);

If I understand correctly, you want to put some kind of ID into the first column of your csv, so you have to add the "static" item in the first position of the array you'll get from sql result. 如果我理解正确,你想将某种ID放入csv的第一列,所以你必须在你从sql结果获得的数组的第一个位置添加“static”项。

EDIT - updated to have static value in the first column 编辑 - 更新为在第一列中具有静态值

Example: 例:

...
while($row = mysqli_fetch_assoc($result))
{
    array_unshift($row, 0);
    fputcsv($fp, $row);
}
...

This worked 这很有效

   $id = 0; // or whatever else you want to have in the first column
   while($row = mysqli_fetch_assoc($result))
   {
    array_unshift($row, $id);
    fputcsv($fp, $row);
    $id;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM