Replacing mysql_* functions with PDO and prepared statements

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

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

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


        
4条回答
  •  Happy的楠姐
    2020-11-27 20:29

    I never bother with bindParam() or param types or lengths.

    I just pass an array of parameter values to execute(), like this:

    $stmt = $dbh->prepare("SELECT * FROM `users` WHERE `id` = :user_id");
    $stmt->execute( array(':user_id' => $user_id) );
    
    $stmt = $dbh->prepare("INSERT INTO `users` (username, email)
                            VALUES (:username, :email)");
    $stmt->execute( array(':username'=>$username, ':email'=>$email) );
    

    This is just as effective, and easier to code.

    You may also be interested in my presentation SQL Injection Myths and Fallacies, or my book SQL Antipatterns: Avoiding the Pitfalls of Database Programming.

提交回复
热议问题