Ciao a tutti. Ho scritto questa classe per la connessione al db che utilizza l'oggetto PDO. Vorrei avere le vostre opinioni sulla sicurezza e la correttezza di quanto scritto. Vi ringrazio in anticipo.
Codice PHP:
class Db {
private $pdo; private $sQuery; private $bConnected = false;
public function __construct(){ $this->Connect(); } private function Connect() {
$database = 'my_db'; $host = 'localhost'; $user = 'user'; $pass = 'pass'; try{ $this->pdo = new PDO("mysql:dbname=".$database."; host=".$host."", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'")); $this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $this->pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false ); return $this->bConnected = true;
}catch (PDOException $e) {
die($e->getMessage()); }
}
private function Stmt($query, $args) { if (!$this->bConnected) { $this->Connect(); } try { $this->sQuery = $this->pdo->prepare($query); if(count($args) > 0) { $this->args = $args; if(count(array_keys($this->args)) == count(array_values($this->args))) { foreach($this->args as $key => $value) { if(substr($key, 0, 1) != ':') { die('Errore nella scrittura della proprietà args'); }else { 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->sQuery->bindValue($key, $value, $type); } }else { die('Gli elementi chiave/valore non sono di pari numero.'); } }else { die('Mancano gli argomenti della query'); } $this->sQuery->execute();
} catch (PDOException $e) { die($e->getMessage()); } $this->args = array(); }
public function query($query, $args, $result = null) {
$this->Stmt($query, $args); switch($result) { case 'select_all': return $this->sQuery->fetchAll(); / break;
case 'obj': return $this->sQuery->fetch(PDO::FETCH_OBJ); break;
case 'select': return $this->sQuery->fetch(PDO::FETCH_ASSOC); break;
case 'insert': return $this->pdo->lastInsertId(); break;
case 'update': return $this->sQuery->rowCount(); break;
default: return $this->sQuery->fetchAll(PDO::FETCH_ASSOC); } }}