dgmike
9/8/2010 - 6:00 PM

Simple way to use PDO

Simple way to use PDO

<?php

$login = 'login';
$senha = md5('senha');

$con = new Con;
$sth = $con->prepare('SELECT nome FROM usuario WHERE login = ? AND senha = ?');
$sth->execute(array($login, $senha));
$result = $sth->fetch(PDO::FETCH_OBJ);

print $result->nome;
<?php

// Simple way to use PDO

function getFruit($conn) {
    $sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
    foreach ($conn->query($sql) as $row) {
        print $row['name'] . "\t";
        print $row['color'] . "\t";
        print $row['calories'] . "\n";
    }
}

// Using...

$pdo = new PDO($dsn,$user,$pass);
getFruit($pdo);
<?php

class Con extends PDO
{
    function Con()
    {
        self::PDO(CONFIG_DNS, CONFIG_USER, CONFIG_PASS);
    }

    function get($table, $id)
    {
      return $this->query("SELECT * FROM $table WHERE id = $id");
    }

    function all($table)
    {
      return $this->query("SELECT * FROM $table");
    }
}

// Using...

$con  = new Con;
$book = $con->get('book', 3);
echo $book->title;

// using all books

foreach ($con->all('book') as $book) {
  echo $book->author;
}