Skip to main content

PDO

Voorbeeld PDO Simple

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "student";

try {
   $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
   echo "Connected successfully";
}
catch(PDOException $e) {
   echo "Connection failed: " . $e->getMessage();
}

$sql="SELECT * FROM student";
$rows = $conn->query($sql)->fetchAll(); // get ALL rows

foreach($rows as $row) {
  // the tabel student has 4 columns
  echo "$row[0], $row[1], $row[2], $row[3]";
  echo "<br>";
}

$sql="SELECT max(id) FROM student";
$rows = $conn->query($sql)->fetch(); // get ONE rows

echo "Last (max) id is: $rows[0];";

$sql="INSERT INTO student (voornaam, achternaam, email) values ('Max','Bisschop','mb@email.com')";
$rows = $conn->query($sql);

?>

Voorbeeld PDO  (OOP en Ass. Array)

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";
}
?>