PDO
PDO simple set-up
Simple PDO class for simple SQL queries, typically used when one connection is sufficient.
<?php
// Define DB Params
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "geheim");
define("DB_NAME", "mydatabase"
class DB{
protected $dbh;
protected $stmt;
protected $resultSet;
public function __construct(){
$this->dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASS);
$this->resultSet=[];
}
public function execute($query){
$this->stmt = $this->dbh->prepare($query);
$result = $this->stmt->execute();
if (! $result) {
die('Oops, Error execute query '.$query.'Result code: '.$result.);
}
$this->resultSet = $this->stmt->fetchAll(PDO::FETCH_ASSOC);
return count($this->resultSet);
}
public function getRow(){
if (count($this->resultSet) >0 ){
return array_shift($this->resultSet);
} else {
return 0;
}
}
?>
Example use of this class
<?php
// This creates a new object $DB
// When you want to queries to be acitve
// ( f.e. at the same time update row by row where the rows are the result of a query )
// Create a second connection, f.e. $secondCon = new DB
require_once('db.php');
$sqlquery="SELECT name, age FROM USERS";
$DB->execute($sqlquery);
// get rows (not for updates or inserts)
while ($row = $DB->getRow()) {
echo $row['name']." is ".$row['age']." years old";
}
?>