PHP:单引号与PDO逃脱

Gho*_*der 0 pdo escaping quote

我是PHP和PDO的新手.我有一个关于PDO和单引号转义的非常基本的问题.我认为逃避不是必要的,但我仍然遇到了一些问题.

例如......我的数据库类中的以下方法在数据库中创建一个新对象.它是抽象的,我的所有类都扩展了数据库类.

public function  create() {
    $attributes = $this->attributes();
    $question_marks = array();
    foreach ($attributes as $key => $value) {
        $question_marks[] = "?";
    }
    $place_holder = array_intersect_key($attributes, get_object_vars($this));
    $place_holder = array_values($place_holder);
    $sql = "INSERT INTO ".static::$table_name." (";
    $sql .= join(", ", array_keys($attributes));
    $sql .= ") VALUES (";
    $sql .= join(", ", array_values($question_marks));
    $sql .= ")";
    $query = $handler->prepare($sql);
    $query->execute($place_holder);
}
Run Code Online (Sandbox Code Playgroud)

如果我创建说例如新用户.我可以毫不费力地将James O'Reilly这个名字输入数据库......

但是,当我想使用我的更新方法....

public function update() {
   $attributes = $this->attributes();
   print_r($attributes);
    $attribute_pairs = array();
    foreach($attributes as $key => $value) {
      if(isset($value))
      $attribute_pairs[] = "{$key}='{$value}'";
    }
    $sql = "UPDATE ".static::$table_name." SET ";
    $sql .= join(", ", $attribute_pairs);
    $sql .= " WHERE id=". $this->id;
    $query = $handler->prepare($sql);
    $query->execute(array());
}
Run Code Online (Sandbox Code Playgroud)

它失败.如果我手动从数据库中的名称中删除引号,这个Update方法的工作方式是这个我希望转义的引用似乎是个问题.

在使用PDO时是否完全不必使用单引号,如果是这样,我将上面的更新方法设置为错误.

为了解决这些问题,我似乎无法将我的错误输出正常工作...这是我的设置,通过在这里审查优秀的Wiki,我认为是正确的...但当然可以随意点燃.

$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,   PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
$handler = new PDO('mysql:host=localhost;dbname=lung', 'root', 'fidelio', $opt);
Run Code Online (Sandbox Code Playgroud)

Bil*_*win 5

仅仅使用prepare()不会自动相应地引用所有变量.在prepare()将变量插入其中之后,所有看到的都是一个字符串.它没有办法告诉字符串的哪个部分来自变量,哪个部分来自代码中的文字字符串.

您必须使用所有值的参数,而不是将它们插入到字符串中.

public function update() {
    $attributes = $this->attributes();
    print_r($attributes);
    $attribute_pairs = array();
    $attribute_values = array();
    foreach($attributes as $key => $value) {
        if(isset($value)) {
            $attribute_pairs[] = "`{$key}`=?"; // use parameter placeholders
            $attribute_values[] = $value; // collect the corresponding values
        }        
    }
    $sql = "UPDATE `".static::$table_name."` SET ";
    $sql .= join(", ", $attribute_pairs);
    $sql .= " WHERE id=?"; // use a placeholder here too
    $attribute_values[] = $this->id; // and add to the collected values
    $query = $handler->prepare($sql);
    $query->execute($attribute_values); // pass the values here
}
Run Code Online (Sandbox Code Playgroud)

注意我还将您的表名和列名放在后面,以便在SQL标识符中使用保留字或特殊字符时帮助分隔它们.