【发布时间】:2020-08-04 11:51:36
【问题描述】:
我想使用 PHP 从 SQL 中获取数据,并使用不同的表格部分在页面的多个部分中显示结果。不能在一个 foreach 函数中包含表格。
这是我正在使用的代码。
echo $row['os']; 正确显示,但 echo $row['brand']; 根本没有显示。
我该如何解决?我想在 SQL 代码部分之外使用多个 echo $row['valuex'];。
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try{
$pdo = new PDO("mysql:host=localhost;dbname=databasename", "username", "password");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
// Attempt select query execution
try{
$sql = "SELECT * FROM phonespecs WHERE pid IN(102883,102889,102894)";
$result = $pdo->query($sql);
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close connection
unset($pdo);
foreach($result as $row){
echo $row['os'];
}
foreach($result as $row){
echo $row['brand'];
}
?>
【问题讨论】:
-
该行的结果集已到达末尾,这就是原因。将结果放在一个数组中,以便您可以在每次需要时重复使用它。使用
->fetchAll() -
@Kevin,谢谢你,凯文,它对我有用。如果您可以发布相同的评论作为答案,我将选择它作为此问题的答案。
-
你需要照顾它,如果你加载太多数据它会变得很慢,所以你可能需要在某些时候限制和偏移