PDO query()

PDO::query() — Executes an SQL statement, returning a result set as a PDOStatement object

  1. PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.
  2. For a query that you need to issue multiple times, you will realize better performance if you prepare a PDOStatement object using PDO::prepare() and issue the statement with multiple calls to PDOStatement::execute().

In PDO You can run such queries like this:

<?php

$db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');


$stmt = $db->query('SELECT * FROM table');

foreach($stmt as $row) {
    echo $row['field1'].' '.$row['field2']; //etc...
}

// Or
 
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

    echo $row['field1'].' '.$row['field2'];

}

// Or

$stmt = $db->query('SELECT * FROM table');

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Now, go ahead and use $results

The handling of errors by this function is controlled by the attribute PDO::ATTR_ERRMODE.



Use the following to make it throw an exception:

<?php
 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

If someone is suffering of the "MySQL server has gone away" problem after executing multiple queries, this is a solution that solved it for me. It's similar to the one needed for the exact same problem in mysqli.

<?php

$stmt=$db->prepare($query);
$stmt->execute();

do { 

    $stmt->fetch(); $stmt->closeCursor(); ++$line; 

} while($stmt->nextRowset());

?>

Let's move on to check PDO::prepare() in our next chapter.


Loading ...

Related Results :

  1. PDO query()
  2. PDO Prepare and Execute query
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author