Hey jongens! Ik heb een tijdje geleden een mooi voorbeeld van een veilige PDO functie gemaakt die je kan gebruiken voor jouw project!
<?php
class DatabaseConnection {
private $host;
private $username;
private $password;
private $database;
private $charset;
private $pdo;
private $error;
private $stmt;
public function __construct($host, $username, $password, $database, $charset = 'utf8') {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->charset = $charset;
try {
$dsn = "mysql:host=$host;dbname=$database;charset=$charset";
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
);
$this->pdo = new PDO($dsn, $username, $password, $options);
} catch(PDOException $e) {
$this->error = $e->getMessage();
}
}
public function query($sql) {
$this->stmt = $this->pdo->prepare($sql);
}
public function bind($param, $value, $type = null) {
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute() {
try {
return $this->stmt->execute();
} catch(PDOException $e) {
$this->error = $e->getMessage();
}
}
public function resultSet() {
try {
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
$this->error = $e->getMessage();
}
}
public function single() {
try {
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
$this->error = $e->getMessage();
}
}
public function rowCount() {
return $this->stmt->rowCount();
}
public function lastInsertId() {
return $this->pdo->lastInsertId();
}
public function beginTransaction() {
return $this->pdo->beginTransaction();
}
public function endTransaction() {
return $this->pdo->commit();
}
public function cancelTransaction() {
return $this->pdo->rollBack();
}
public function getError() {
return $this->error;
}
}
?>
Je kan meer informatie vinden op de gitlab!