Skip to content

Commit

Permalink
Taking our previous PDO example, and now using the fetchObject comman…
Browse files Browse the repository at this point in the history
…d instead of fetch() or fetchAll(), plus example class to go with that object.
  • Loading branch information
JonTheNiceGuy committed May 6, 2012
1 parent 2f0ca53 commit 2e8bdb0
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions sources/04_using_fetchObject.php
@@ -0,0 +1,41 @@
<?php
try {
$db = new PDO("mysql:host=localhost;dbname=mysite", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "select userid, realname, lastloggedin, username, password "
. "from users where username = ? and password = ?";
$query = $db->prepare($sql);
$query->execute(array($_POST['username'], $_POST['password']));
$data = $query->fetchObject('user');
if ($data != false) {
echo $data;
}
} catch (PDOException $e) {
error_log("User unable to login: " . $e->getMessage());
}

class user
{
// Columns from the database
protected $userid = null;
protected $realname = null;
protected $lastloggedin = null;
protected $username = null;
protected $password = null;
// Processed Data
protected $transformed_lastloggedin = null

public function __construct()
{
if ($this->lastloggedin != null) {
$this->transformed_lastloggedin = date("H:i:s", strtotime($this->lastloggedin))
. " on " . date("d-M-Y" , strtotime($this->lastloggedin);
}
}

public function toString()
{
echo "Hello {$this->realname}, your userid is {$this->userid} and "
. "you last logged in at {$this->transformed_lastloggedin}";
}
}

0 comments on commit 2e8bdb0

Please sign in to comment.