I learned these 2 methods in PDO with OOP when I study it and I would like to ask which is safer to use? binding everything we used or just using ? and execute it.
1:
public function query($query) { $this->stmt = $this->dbh->prepare($query); } 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(){ return $this->stmt->execute(); } public function lastInsertId(){ $this->dbh->lastInsertId(); }
or 2:
public function insertRow($query, $params = []){ try { $stmt = $this->datab->prepare($query); $stmt->execute($params); return TRUE; } catch (PDOException $e) { throw new Exception($e->getMessage()); } }
Advertisement
Answer
you can use both but using bind it could be better with writing all with types instead using switch and to make it short you can use 2.
public function query($query, $params = []){ global $datab $stmt = $datab->prepare($query); $stmt->execute($params); return $stmt; }