参见英文答案 > How to use PDO to fetch results array in PHP? 3个
我试图通过PHP和PDO FetchAll()与Prepared Statements填充来自MysqL表的一列的所有结果,但我的代码只返回一行而不是所有结果.我在这里看到这个问题(PHP PDO returning single row)与我的问题类似但我没有用这个问题改进我的代码.
我按照PHP手册页面(http://php.net/manual/en/pdostatement.fetchall.php)中的示例尝试将我的代码构造/调整为MySeql表中一列的fetchAll()结果:
PHP手册页 – 带print的FetchAll示例:
<?PHP
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);
?>
我使用HTML select标签基于上面的示例调整了我的代码:
<select name="category" class="form-control" required>
<option value="0" selected="selected" disabled="disabled" style="display: none">Select one category</option>
<?PHP
require_once 'pdo_connection.PHP';
$sth = $dbh-> prepare( 'SELECT * FROM categories' );
$sth-> execute();
$result = $sth-> fetchAll(); ?>
<?PHP foreach( $result as $row ) ?>
<option value="<?PHP echo $row['category_id'];?>"><?PHP echo $row['category'];?></option>
</select>
而且,这是我的PDO数据库连接:
<?PHP
$dbh = new PDO('MysqL:host=localhost;dbname=system_vip;charset=utf8', 'root', '');
?>
我可以做些什么来改进我的代码,使用预处理语句和PDO连接从MysqL表上的一列填充所有结果?
解决方法:
fetchAll()没问题.如果你var_dump($result)你会看到所有行都在那里.
这就是问题:
<?PHP foreach( $result as $row ) ?>
<option value="<?PHP echo $row['category_id'];?>"><?PHP echo $row['category'];?>
不使用大括号或替代语法在foreach之后对语句进行分组,只会重复foreach之后的第一个语句.在这种情况下,foreach之后的第一个语句是什么都没有.关闭的PHP标记意味着instruction separator,所以你实际上是这样说的:
foreach( $result as $row );
即对于每一行,什么也不做.在循环之后仍然将$row定义为数组的最后一行,这是您最终得到的一个选项.
以下是用于包含两个语句的备用语法示例:
<?PHP foreach( $result as $row ): ?>
<option value="<?PHP echo $row['category_id'];?>"><?PHP echo $row['category'];?></option>
<?PHP endforeach; ?>