Replacing mysql_* functions with PDO and prepared statements

后端 未结 4 1624
抹茶落季
抹茶落季 2020-11-27 19:59

I\'ve always done the simple connection of mysql_connect, mysql_pconnect:

$db = mysql_pconnect(\'*host*\', \'*user*\', \'*pass*\');         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-11-27 20:25

    To answer the length question, specifying it is optional unless the param you are binding is an OUT parameter from a stored procedure, so in most cases you can safely omit it.

    As far as safety goes, escaping is done behind the scenes when you bind the parameters. This is possible because you had to create a database connection when you created the object. You are also protected from SQL injection attacks since by preparing the statement, you are telling your database the format of the statement before user input can get anywhere near to it. An example:

    $id = '1; MALICIOUS second STATEMENT';
    
    mysql_query("SELECT * FROM `users` WHERE `id` = $id"); /* selects user with id 1 
                                                              and the executes the 
                                                              malicious second statement */
    
    $stmt = $pdo->prepare("SELECT * FROM `users` WHERE `id` = ?") /* Tells DB to expect a 
                                                                     single statement with 
                                                                     a single parameter */
    $stmt->execute(array($id)); /* selects user with id '1; MALICIOUS second 
                                   STATEMENT' i.e. returns empty set. */
    

    Thus, in terms of safety, your examples above seem fine.

    Finally, I agree that binding parameters individually is tedious and is just as effectively done with an array passed to PDOStatement->execute() (see http://www.php.net/manual/en/pdostatement.execute.php).

提交回复
热议问题