简体   繁体   中英

MYSQL/PHP: Create an Array using FetchAll with PDO

I am new to PDO and having trouble placing the results of a fetch into an array.

The following code succeeds in querying the database. However, I would like to place the results into an array so that I can then work with the elements of the array individually. I am not sure what exactly $result below is. Is it already an array? Or what is it. I think I need to use fetchAll to get the array. If so, would appreciate proper code to do this. Or if $results below is already an array, then what is the difference between that and what I would get with 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 will return the complete resultset into a variable. That variable is an array, one occurance for each row in the resultset. Depending on the parameter you use in fetchAll it will be an array of row arrays or and array of row objects.

But you have a few little error in your syntax

// 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 />';
    }

First of all, to be sure what $result is use var_dump($result) since PDO::query method returns a PDOStatement object. Further, in your case it is not an array, it is a PDOStatement object. Refer to http://php.net/manual/en/pdo.query.php . Afterwards, I would suggest to use PDO::prepare() and PDO::execute() methods to run your SQL query since it is performance friendly, especially if you are going to run it multiple times and safer by preventing you from SQL injections. Refer to http://php.net/manual/en/pdo.prepare.php . And after all, PDO::fetchAll() will return an array of your result set which is what you already want. Refer to PHP PDO::fetchAll() manual. So what I would do is:

$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) {
      ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM