PDO bindParam into one statement?

前端 未结 5 1804
刺人心
刺人心 2020-12-02 19:14

Is there a way I can put these bindParam statements into one statement?

$q = $dbc -> prepare(\"INSERT INTO accounts (username, email, password) VALUES (:u         


        
5条回答
  •  时光说笑
    2020-12-02 20:05

    +1 to Matthew Flaschen for the accepted answer, but I'll show you another tip. If you use SQL parameters with names the same as the entries in $_POST, you could take advantage of the fact that $_POST is already an array:

    $q->execute($_POST);
    

    The SQL parameter names are prefixed with a colon (:) but the keys in the $_POST array are not. But modern versions of PDO account for this - you no longer need to use colon prefixes in the keys in the array you pass to execute().

    But you should be careful that anyone can add extra parameters to any web request, and you should get only the subset of $_POST params that match parameters in your query.

    $q = $dbc -> prepare("INSERT INTO accounts (username, email, password) 
      VALUES (:username, :email, :password)");
    $params = array_intersect_key($_POST, array("username"=>1,"email"=>1,"password"=>1));
    $q->execute($params);
    

提交回复
热议问题