【问题标题】:Unable to use multiple foreach function from same PDO SQL query无法从同一个 PDO SQL 查询中使用多个 foreach 函数
【发布时间】: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'];
} 

?>

【问题讨论】:

  • 该行的结果集已到达末尾,这就是原因。将结果放在一个数组中,以便您可以在每次需要时重复使用它。使用-&gt;fetchAll()
  • @Kevin,谢谢你,凯文,它对我有用。如果您可以发布相同的评论作为答案,我将选择它作为此问题的答案。
  • 你需要照顾它,如果你加载太多数据它会变得很慢,所以你可能需要在某些时候限制和偏移

标签: php pdo


【解决方案1】:

感谢 Kevin,以下代码对我有用。

try{
    $sql = "SELECT * FROM phonespecs WHERE pid IN(102883,102889,102894)";
    $result = $pdo->query($sql);
    $results = $result->fetchAll();

    


} catch(PDOException $e){
    die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
 
// Close connection
unset($pdo);


    foreach($results as $row){
    echo $row['os'];
} 

    foreach($results as $row){
    echo $row['brand'];
} 

?>

【讨论】:

    猜你喜欢
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2015-08-09
    • 1970-01-01
    相关资源
    最近更新 更多