如何在多维数组中保存查询?

时间:2018-08-21 18:54:42

标签: php mysql

我每天都会执行此脚本作为Cron作业,以更新剩余天数以支付发票。我首先查询表的每一行,然后尝试将数据存储在多维数组中,但这似乎将查询的所有内容存储在数组的第一个元素中。

这是我的剧本:

<?php
  include '../inc/dbinfo.inc';

  ini_set("log_errors", 1);
  ini_set("error_log", "/tmp/php-error.log");
  error_log( "#################################################     UpdateVendorInvoiceDays.php    #################################################" );

  $three = 3;

  $fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
  $getInvoices = $conn->prepare($fetchAllInvoices);
  $getInvoices->bind_param("i", $three);
  $getInvoices->execute();
  $result = $getInvoices->get_result();

  $rows = array();
  $j = 0;

  while($row = $result->fetch_assoc())
  {
    $rows[$j][] = $row;
    $j++;
  }

  echo json_encode($rows[0][0]);    //Only outputs one row

  //UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
  $updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
  $setDays = $conn->prepare($updateDaysRemaining);

  $k = 0; //incrementor
  $numberOfEntries = $rows['COUNT(*)'];

  for($k;$k<$numberOfEntries;$k++){
     $setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"], 
     $rows[$k]['VENDORINVOICEID'], $three);
    if($setDays->execute()){
      error_log('Cron success');
    }else{
      error_log('Cron fail');
    }
  }
?>

当前,我的第一个查询的输出是: [[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]

并且我的错误日志仅通知我$rows['COUNT(*)']未定义(这很有意义)

我在这里查看了其他答案,但它们似乎与我的结构不同。

编辑:我的数据库中也有2行,但这仅输出1行。我忘了提了。

1 个答案:

答案 0 :(得分:0)

对所有行进行了一些简化。代替...

while($row = $result->fetch_assoc())
  {
    $rows[$j][] = $row;
    $j++;
  }

  echo json_encode($rows[0][0]);

您可以只使用https://demos.captcha.com/demos/features/captcha-demo.aspx ...

返回所有行。
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);

然后对整个数组进行编码,而不仅仅是对一个元素进行编码-$rows[0][0]向您展示的内容。

关于您的其他问题-将select语句更改为

COUNT(*) as rowCount

然后您可以将此别名用作字段引用...

$rows['COUNT(*)']

成为

$rows['rowCount']