【问题标题】:PHP for each loop每个循环的 PHP
【发布时间】:2012-02-23 02:35:56
【问题描述】:

这就是我想要实现的目标。如果从下拉菜单中选择了全部,那么我会从我的数据库中选择所有客户端。然后,对于每个客户端,它将运行创建 html 页面和 pdf 的脚本。这是我必须要做的,但我不能让它为每个客户生成一个 html 页面和 pdf。

<?php
$client_id=$_POST["client_id"];
$date_start=$_POST["date_start"];
$date_end=$_POST["date_end"];

if ($client_id == 'ALL') 
{
  $con = mysql_connect("localhost","user","password");
  if (!$con)
  {
    die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("mydatabase", $con);  

  $query = "select client_id from ca_client_account";

  $result = mysql_query($query) or die(mysql_error());

  while($row = mysql_fetch_array($result))
  {
    $command="php $result.php $result $date_start $date_end > $result.html";
    exec($command, $output, $status);
    echo $command;
    if ($status!=0) {print_r($output); die("wget failed with status $status"); }

    $command="wkhtmltopdf-i386 --margin-left 5mm --margin-right 5mm $result.html $result.pdf";
    exec($command, $output, $status);
    if ($status!=0) die("htmltopdf failed");
  }

}
else
{
  $command="php $client.php $client_id $date_start $date_end > $client.html";
  exec($command, $output, $status);
  if ($status!=0) {print_r($output); die("wget failed with status $status"); }

  $command="wkhtmltopdf-i386 --margin-left 5mm --margin-right 5mm $client.html $client.pdf";
  exec($command, $output, $status);
  if ($status!=0) die("htmltopdf failed");
}
?>

对于单个客户来说,一切都是完美的。当我尝试生成所有客户端语句时,我无法让它工作。

我做错了什么?

非常感谢

【问题讨论】:

  • 你得到什么输出。有什么错误吗?
  • $result 变量不会按预期输出每个 client_id。它输出资源 id 3。
  • 很好奇,你为什么要exec 一个php 文件而不是include 文件并像其他任何函数一样运行函数?对我来说似乎不那么麻烦了。

标签: php syntax if-statement foreach


【解决方案1】:

$result 不会在这里提供您所期望的。您需要指定要回显的确切字段。在这种情况下,$row['client_id'] 可以工作。

【讨论】:

  • 谢谢,它快到了,但我现在得到 Undefined offset:1。我使用 $row[1] 而不是 $row['client_id'] - 我确定这不是原因
  • @TheManiac 你是对的。我并不是要更改它们,它们是一个静态文件 myfile.php - 我在此处复制时不假思索地更改了它们以使帖子通用
  • 太棒了——还有一件事:如果你想使用$row['client_id'] 而不是$row[1](前者更具描述性并且通常是更好的做法)替换你对mysql_fetch_array 的调用mysql_fetch_assoc
【解决方案2】:

您对数据库调用的工作方式存在根本性的误解。在您的$command 中,您使用$result,这是一个数据库重新查询结果句柄。它不是来自查询的值,它不能被 mysql_*() 函数以外的任何东西使用。标准查询序列如下所示:

$sql = "SELECT ...";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);

echo $row['some_field'];

$result 包含一个表示查询结果的语句句柄。您使用此语句句柄来获取一行数据。在您获取的 $row 数据中,将是您在查询中指定的各个数据字段。您将传递给外部脚本的那些数据位。

【讨论】:

    猜你喜欢
    • 2017-04-28
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    • 2015-10-06
    • 2016-10-15
    • 2012-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多