fetch(PDO::FETCH_ASSOC); code example

Example 1: PDO::FETCH_OBJ

It should be mentioned that this method can set even non-public properties. It may sound strange but it can actually be very useful when creating an object based on mysql result.
Consider a User class:

<?php
class User {
   // Private properties
   private $id, $name;

   private function __construct () {}

   public static function load_by_id ($id) {
      $stmt = $pdo->prepare('SELECT id, name FROM users WHERE id=?');
      $stmt->execute([$id]);
      return $stmt->fetchObject(__CLASS__);
   }
   /* same method can be written with the "name" column/property */
}

$user = User::load_by_id(1);
var_dump($user);
?>

fetchObject() doesn't care about properties being public or not. It just passes the result to the object. Output is like:

object(User)#3 (2) {
  ["id":"User":private]=>
  string(1) "1"
  ["name":"User":private]=>
  string(10) "John Smith"
}

Example 2: php fetch

while ($row = mysqli_fetch_assoc( $result)) {}

Example 3: php pdo fetch from db

$dbhost = @mysql_connect($host, $user, $pass) or die('Unable to connect to server');

@mysql_select_db('divebay') or die('Unable to select database');
$search = $_GET['searchdivebay'];
$query = trim($search);

$sql = "SELECT * FROM auction WHERE name LIKE '%" . $query . "%'";



if(!isset($query)){
echo 'Your search was invalid';
exit;
} //line 18

$result = mysql_query($trim);
$numrows = mysql_num_rows($result);
mysql_close($dbhost);

Example 4: php pdo fetch from db

$pdo = new PDO('mysql:host=$host; dbname=$database;', $user, $pass);
$stmt = $pdo->prepare('SELECT * FROM auction WHERE name = :name');
$stmt->bindParam(':name', $_GET['searchdivebay']);
$stmt->execute(array(':name' => $name);