简体   繁体   English

导出多个MySQL结果到CSV

[英]Export multiple MySQL results to CSV

I have the following PHP script below.我在下面有以下 PHP 脚本。

It checks the person table for rows with the reference PK001 & PK002 .它检查person表中引用PK001PK002的行。

When I run my script below, the output is the following:当我在下面运行我的脚本时,output 如下:

ID,Reference,Email
1,PK001,mcg@gmail.com

I would prefer the output to be:我希望 output 是:

ID,Reference,Email
1,PK001,mcg@gmail.com
2,PK002,mcg@hotmail.com

~ ~

PHP PHP

$data = array("PK001","PK002");
$count = count($data);

foreach ($data as $value) {

  $sql = "SELECT * FROM person WHERE reference = '$value'";
  $result = $con->query($sql);

  $csvheaders = ["ID","Reference","Email"];

  $fp = fopen('php://output', 'w');
  if ($fp && $result) {
      header('Content-Type: text/csv');
      header('Content-Disposition: attachment; filename="export.csv"');
      header('Pragma: no-cache');
      header('Expires: 0');
      fputcsv($fp, $csvheaders);
      while ($row = $result->fetch_array(MYSQLI_NUM)) {
          fputcsv($fp, array_values($row));
      }
      die();
  }

}

die();

Can someone please explain how I resolve this?有人可以解释一下我是如何解决这个问题的吗?

You can use IN() to compare to multiple values.您可以使用IN()与多个值进行比较。 See https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_in for documentation on IN() .有关IN()的文档,请参阅https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#operator_in

Also you should use query parameters.您还应该使用查询参数。 Please do not interpolate values directly into SQL expressions.请不要将值直接插入到 SQL 表达式中。 That's a good way to produce insecure, buggy code.这是生成不安全、错误代码的好方法。

You need one separate parameter placeholder for each value in the array.数组中的每个值都需要一个单独的参数占位符。 You can't use a single parameter for a list of values.您不能对值列表使用单个参数。

Here's how I would write it:这是我的写法:

$data = ["PK001","PK002"];

$placeholders = implode(",", array_fill(1, count($data), "?"));

$sql = "SELECT ID, reference, email FROM person WHERE reference IN ({$placeholders})";

$stmt = $con->prepare($sql);
$stmt->bind_param(str_repeat("s", count($data)), ...$data);
$stmt->execute();
$result = $stmt->get_result();

Then proceed to loop over $result as you have done.然后像您所做的那样继续循环遍历$result

FYI, PDO is even easier, because you don't need to do any binding.仅供参考,PDO 更容易,因为您不需要进行任何绑定。 Just pass the array to execute() :只需将数组传递给execute()

$stmt = $con->prepare($sql);
$stmt->execute($data);

I would prefer to use PDO instead of mysqli in any PHP project.我宁愿在任何 PHP 项目中使用 PDO 而不是 mysqli。

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

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