Reputation: 151
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());
}
}
Upvotes: 1
Views: 67
Reputation: 136
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;
}
Upvotes: -1
Reputation: 157880
The second one is much better, but still there is a cargo cult catch
. And it doesn't return anything. Should be
public function query($query, $params = []){
$stmt = $this->datab->prepare($query);
$stmt->execute($params);
return $stmt;
}
an it can be used for any query, not only insert, but also select, update, delete and so on.
Upvotes: 2