Prepared Statements, escape variables

前端 未结 2 639
攒了一身酷
攒了一身酷 2021-01-28 06:21

Do I need to do anything to protect the three variables, like using the escape string or binding them? I\'m not sure if I did this correctly, people just recommended using prepa

2条回答
  •  悲&欢浪女
    2021-01-28 07:19

    You are not using prepared statements in your code. Prepared statements would look more like this:

    $stmt = $db->prepare("INSERT INTO foo (bar, baz) VALUES (?, ?);");
    
    $stmt->bindValue(1, "Fez");
    $stmt->bindValue(2, "Hat");
    $stmt->execute();
    

    Your example code is potentially vulnerable to SQL injection because you are simply inserting the variables directly into the SQL string. You will want to either use prepared statements and bind the values (this is the preferred solution), or alternatively just make sure you escape all input to exec() correctly.

    It might also be worth mentioning that exec() is fine for totally hardcoded statements - e.g., $db->exec("SELECT foo FROM bar;"); - since the SQL is hardcoded, there is no potential for SQL injection. I, however, like to always use prepare instead, as a matter of style.

    To specifically execute the query in your code, you would do something like this:

    $stmt = $db->prepare("INSERT INTO faq (`order`, `heading`, `content`) " .
        "VALUES (?, ?, ?);");
    
    $stmt->bindValue(1, $order);
    $stmt->bindValue(2, $heading);
    $stmt->bindValue(3, $content);
    $stmt->execute();
    

    I would also recommend the official PHP documentation, as it shows some other ways of doing the same thing (namely, you can pass your parameters as an array to execute() instead of binding them individually): http://php.net/manual/en/pdo.prepare.php.

提交回复
热议问题