使用 PHP 数组输出 MySQL 查询 - foreach 循环错误“非法偏移”和“无效参数”

Posted

技术标签:

【中文标题】使用 PHP 数组输出 MySQL 查询 - foreach 循环错误“非法偏移”和“无效参数”【英文标题】:Output MySQL query with PHP array - foreach loop error "illegal offset" and "invalid argument" 【发布时间】:2019-02-04 08:11:50 【问题描述】:

为了让这更容易理解,我缩减了这个示例而不是我正在使用的实际代码,但我知道问题出在哪里,我只是不确定如何使用 foreach 来输出我的 mysql 查询的结果。

我有一个类似的数组

$thetablestructure = array(
 array('tableheader' => 'header 1', 'tablevalue' => 'value1'),
 array('tableheader' => 'header 2', 'tablevalue' => 'value2'),
);

我希望 html 输出是这样的:

<table>
 <tr>
  <th>header 1</th>
  <th>header 2</tth>
 </tr>
 <tr>
  <td>value 1</td>
  <td>value 2</td>
 </tr>
</table>

这是我尝试使用的代码,其中错误表示非法字符串偏移和非法值:

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) 
 die("Connection failed: " . $conn->connect_error);
 
$keywords = $_REQUEST['keywords'];

$sql = "SELECT * FROM `stock` WHERE `model` LIKE '%$keywords%'";
$result = $conn->query($sql);

$thetablestructure = array(
        array('tableheader' => 'Header 1', 'tablevalue' => 'value1'),
        array('tableheader' => 'Header 2', 'tablevalue' => 'value2'),
        );

echo "<table><tr>";

foreach ($thetablestructure as $thetablestructure) 
 echo "<th>".$thetablestructure[tableheader]."</td>";


echo "</tr>";
// output data of each row
while($row = $result->fetch_assoc()) 
 echo('<tr>');
 foreach ($thetablestructure as $thetablestructure) 
  echo "<td>".$row["$thetablestructure[tablevalue]."]."</td>";
 

echo('</tr>');


echo "</table>";
$conn->close();

最初这是我使用的代码,在尝试简化和浓缩之前:

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) 
 die("Connection failed: " . $conn->connect_error);
 

// Retrieve keyword for MySQL query and search database
$keywords = $_REQUEST['keywords'];

$sql = "SELECT * FROM `stock` WHERE `model` LIKE '%$keywords%'";

$result = $conn->query($sql);

if ($result->num_rows > 0) 
echo "
<table>
 <tr>
  <th>Heading 1</th>
  <th>Heading 2</th>
 </tr>";

// output data of each row
while($row = $result->fetch_assoc()) 
 echo('<tr>');
 echo "<td>".$row["$thetablestructure[tableheader]"]."</td>";
 echo "<td>".$row["value2"]."</td>";
 echo('</tr>');


echo "</table>";

 else 
 echo "<p>0 results for ".$keywords."

$conn->close();

希望这是有道理的,有人可以帮助我。

【问题讨论】:

除非在引号中使用,否则在$thetablestructure[tableheader] 周围使用tableheader 时需要加上引号(以及其他类似用途) 【参考方案1】:

你犯了下面的错误,key tableheader是一个字符串,所以你必须使用"'",另外,你在foreach里面使用了同名的数组'$thetablestructure'

foreach ($thetablestructure as $v) 
 echo "<th>$v['tableheader']</td>";

接下来对于每一个你使用字符串作为变量,以及其他的错误,我建议你先隔离在一个像$v这样的变量中,然后再尝试使用。

 while($row = $result->fetch_assoc()) 
    echo('<tr>');
    foreach ($thetablestructure as $t) 
      $v =$t['tablevalue'];
      echo "<td>".$row[$v]."</td>";
    

    echo('</tr>');
  

只是观察一下,如果您在代码中专门调用“value1”和“value2”,有时维护起来更好,同时易于理解,而不是使用像 $thetablestructure 这样的结构来动态构建您想要的任何东西.

【讨论】:

【参考方案2】:

你必须改变这个,你打电话给$thetablestructure[tableheader]

foreach ($thetablestructure as $thetablestructure) 
    echo "<th>".$thetablestructure[tableheader]."</td>";


echo "</tr>";
// output data of each row
while($row = $result->fetch_assoc()) 
    echo('<tr>');
    foreach ($thetablestructure as $thetablestructure) 
        echo "<td>".$row["$thetablestructure[tablevalue]."]."</td>";
     
//...

对此,$thetablestructureItem['tableheader']

foreach ($thetablestructure as $thetablestructureItem) 
    echo "<th>".$thetablestructureItem['tableheader']."</th>"; //You've opened th tag and close a td one


echo "</tr>";
// output data of each row
while($row = $result->fetch_assoc()) 
    echo('<tr>');
    foreach ($thetablestructure as $thetablestructureItem) 
        echo "<td>".$row[$thetablestructureItem['tablevalue']]."</td>";
     
//...

您首先没有正确命名foreach 循环中的值。您对集合和该集合的每个项目使用相同的名称。即使它以前可能工作过,但在对项目及其集合/数组使用相同名称的代码进行工作/调试时,这肯定会带来混乱。

您调用索引时忘记在索引名称周围加上引号。

$someArray = array('foo' => 42);
//access the value at index foo :
echo $someArray['foo'];

顺便说一句,您的查询容易受到SQL Injections 的攻击。

$keywords = $_REQUEST['keywords'];

$sql = "SELECT * FROM `stock` WHERE `model` LIKE '%$keywords%'";
$result = $conn->query($sql);

如果请求keyword

"lol'; DROP TABLE `users`;--"

查询将变为:

 $sql = "SELECT * FROM `stock` WHERE `model` LIKE '%lol'; DROP TABLE `users`;--";

我建议你看看php-PDO,特别是bindParam()

【讨论】:

以上是关于使用 PHP 数组输出 MySQL 查询 - foreach 循环错误“非法偏移”和“无效参数”的主要内容,如果未能解决你的问题,请参考以下文章

MySQL/PHP 输出数组重复查询然后显示结果,如何删除查询? [复制]

php按当前年份、季度、当月,查询mysql数据库并输出数组

PHP:输出以前的 MySQL 查询 [重复]

PHP如何将SQL查询结果转为多维数组,并按查询行输出

php中查询mysql select 第一个字段 第二个字段 from 表名。输出语句应

从 MySQL 结果创建 PHP 数组