Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Taking our previous PDO example, and now using the fetchObject comman…
…d instead of fetch() or fetchAll(), plus example class to go with that object.
- Loading branch information
1 parent
2f0ca53
commit 2e8bdb0
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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}"; | ||
} | ||
} |