Which one is safer to use in OOP?

我的梦境 提交于 2020-06-28 04:56:24

问题


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()); 
  }
}

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/61680959/which-one-is-safer-to-use-in-oop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!