簡體   English   中英

MYSQL/PHP:使用 FetchAll 和 PDO 創建一個數組

[英]MYSQL/PHP: Create an Array using FetchAll with PDO

我是 PDO 的新手,無法將獲取的結果放入數組中。

以下代碼成功查詢數據庫。 但是,我想將結果放入一個數組中,以便我可以單獨處理該數組的元素。 我不確定下面的$result到底是什么。 它已經是一個數組了嗎? 或者是什么。 我想我需要使用fetchAll來獲取數組。 如果是這樣,將不勝感激正確的代碼來做到這一點。 或者如果下面的$results已經是一個數組,那么它和我用fetchAll得到的有什么區別?

//USE PDO TO CONNECT TO DBASE
$hostdb = "my host";
$namedb = "mydb";
$passdb = "bypass";
$userdb = "myusername";

try {
  // Connect and create the PDO object
  $conn = new PDO("mysql:host=$hostdb; dbname=$namedb", $userdb, $passdb);
  $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

  // Define and perform the SQL SELECT query
  $sql = "SELECT * FROM `comments` WHERE `userid` IN(118)";
  $result = $conn->query($sql); // THIS WORKS
// $result = $sql->fetchAll(PDO::FETCH_OBJ);  //THIS DOES NOT WORK
   if($result !== false) {

    // Parse the result set
    foreach($result as $row) {
      echo $row['id']. ' - '. $row['name']. ' - '. $row['category']. ' - '. $row['link']. '<br />';
    }
  }

  $conn = null;        // Disconnect
}
catch(PDOException $e) {
  echo $e->getMessage();
}

fetchAll 會將完整的結果集返回到一個變量中。 該變量是一個數組,結果集中的每一行出現一次。 根據您在 fetchAll 中使用的參數,它將是一個行數組或行對象數組。

但是你的語法有一些小錯誤

// Define and perform the SQL SELECT query
$sql = "SELECT * FROM `comments` WHERE `userid` IN(118)";

$result = $conn->query($sql); 
if($result !== false) {

    // use $result here as that you PDO::Statement object
    $allRows = $result->fetchAll(PDO::FETCH_OBJ); 

    // Parse the result set
    foreach($allRows as $row) {
        // also amend here to address the contents of the allRows i.e. $row as objects
      echo $row->id. ' - '. $row->name. ' - '. $row->category. ' - '. $row->link. '<br />';
    }

首先,要確定$result是什么,請使用var_dump($result)因為PDO::query方法返回一個 PDOStatement 對象。 此外,在您的情況下,它不是數組,而是 PDOStatement 對象。 請參閱http://php.net/manual/en/pdo.query.php 之后,我建議使用PDO::prepare()PDO::execute()方法來運行您的 SQL 查詢,因為它是性能友好的,特別是如果您要多次運行它並且通過防止 SQL 注入來更安全. 請參閱http://php.net/manual/en/pdo.prepare.php 畢竟, PDO::fetchAll()將返回一個您已經想要的結果集數組。 請參閱 PHP PDO::fetchAll()手冊。 所以我會做的是:

$sql = "SELECT * FROM `comments` WHERE `userid` IN(118)";

$statement = $conn->prepare($sql);
if($statement->execute())
{
    $results = $statement->fetchAll('Your prefered fetch style');

    foreach($results as $result) {
      ...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM