【发布时间】:2018-07-04 20:46:07
【问题描述】:
我正在尝试使用foreach 从关联数组中打印 SQL 查询的结果。我正在尝试不同的事情,一个工作,而另一个给出错误。
我特意问的是为什么$row[first_name] 这部分会给出不同的结果。
此代码有效:
<?php
include 'connect_db.php';
$stmt = $conn->query("SELECT people.first_name, people.last_name FROM people");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
echo "<form action='/test.php' method='post'>
<input type='text' name='first_name' value=$row[first_name]>
<input type='submit' value='Click'> <br>
</form>";
}
?>
但是下面的代码给出了一个错误提示:Notice: Use of undefined constant first_name - assumed 'first_name'
<?php
include 'connect_db.php';
$stmt = $conn->query("SELECT people.first_name, people.last_name FROM people");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
echo $row[first_name];
}
?>
我显然在第二个示例中错误地使用了$row[first_name],但我不知道怎么做。
【问题讨论】:
标签: php arrays syntax-error associative-array