【问题标题】:PHP Last item in array is empty within foreachPHP数组中的最后一项在foreach中为空
【发布时间】:2020-02-27 02:31:09
【问题描述】:

当我将结果插入数据库时​​,由于某种原因,数组中的最后一项 ($item) 为空。

$foo = 0;
$bar = 0;
$item = array(); // the problem array

foreach ($_POST as $key => $value){
     $query = "SELECT data FROM table0 WHERE column = '$value'";
     $result = mysqli_query ($dbc, $query) or trigger_error();

     $data = mysqli_fetch_array ($result, MYSQL_NUM);

     if ($data[0] =='1'){
          $foo = $foo + 1;
          $bar = $bar + $data[1];
     }else{
          $item[] = $data[2];
     }
}

foreach ($item as $number){
     $query2 = "SELECT data FROM table1 WHERE column = '$number'";
     $result2 = mysqli_query ($dbc, $query2) or trigger_error();

     $row = mysqli_fetch_array ($result2, MYSQL_NUM);

     $query3 = "INSERT INTO table2 (col1, col2, col3) VALUES ('', '$row[0]', '$row[1]')";
     $result3 = mysqli_query ($dbc, $query3) or trigger_error();
}

从 $query3 插入的最后一行没有值,因为 $item 数组的末尾有一个空值。

$item 最终看起来类似于 array ([0]=>1 [1]=>2 [2]=>3 [3]=>),但 $_POST 数组中没有任何内容。

感谢您提前提供任何反馈。

【问题讨论】:

  • 您可能在$_POST 中有一个值,而该值在表中没有匹配的值。您应该检查$data 是否为空。
  • if ($data) { // code to add to $item }
  • 您需要检查您的 $_POST 变量。您的值与您的表不匹配。这很可能是您的提交按钮,即<input type="submit" value="submit"/>。提交输入也包含在发布请求中,你知道..
  • 您应该使用准备好的语句来防止 SQL 注入。
  • 你对SQL Injections敞开心扉!

标签: php arrays database foreach


【解决方案1】:

您需要检查SELECT 查询是否找到了一些东西。

foreach ($_POST as $key => $value){
     $query = "SELECT data FROM table0 WHERE column = '$value'";
     $result = mysqli_query ($dbc, $query) or trigger_error();

     $data = mysqli_fetch_array ($result, MYSQL_NUM);
     if ($data) {
         if ($data[0] =='1'){
              $foo = $foo + 1;
              $bar = $bar + $data[1];
         }else{
              $item[] = $data[2];
         }
     }
}

【讨论】:

  • 感谢@Barmar,因为大多数错误都与拼写有关,并且它位于 $_POST 数组中。
猜你喜欢
  • 2021-05-06
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-30
  • 2013-01-07
  • 1970-01-01
  • 2014-11-11
相关资源
最近更新 更多