dounao5856 2013-04-21 11:34
浏览 29
已采纳

为什么PDO中的INSERT INTO过于复杂? [关闭]

So I have to change all the mysql_ commands to PDO becuase they are officially depreciated and PDO is the most universal. Why the INSERT ones are so complex and what is benefit of this?

For example in my old code I do this:

mysql_connect("$host", "$username", "$db_password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");
mysql_query("INSERT INTO $tbl_name(this, that, him, her) VALUES('$this', '$that', '$him', '$her')")or die(mysql_error()); 

And with PDO

$conn = new PDO('mysql:host=HST_NAME;dbname=DB_NAME;charset=utf8', 'USER', 'PASSWORD');
$sql = "INSERT INTO books (this, that, him, her) VALUES (:this,:that,:him,:her)";
$q = $conn->prepare($sql);
$q->execute(array(':this'=>$this,
                  ':that'=>$that,
                  ':him'=>$him,
                  ':her'=>$her ));

When I have to input lots of data at once the PDO will get huge. What is the benefit of this?

Looking for a why to do answer and not a what to do

  • 写回答

2条回答 默认 最新

  • douchun3680 2013-04-21 12:23
    关注

    You should not be using variables directly in SQL statements; this leads to all sorts of security vulnerabilities.

    As you say, the mysql_ functions are getting deprecated. I know you may be reluctant to move to PDO if you’ve been using the mysql_ functions for a long time, but there’s various reasons why PDO is better than the old mysql_ functions:

    • It protects against SQL injection vulnerabilities out of the box
    • It’s faster than the mysql_ functions
    • It also has the advantage of it supports database engines other than MySQL

    PDO also separates your database query from parameters. Consider the following:

    $sql = "INSERT INTO users (first_name, last_name, email)
            VALUES (:first_name, :last_name, :email)";
    
    $smt->prepare($sql);
    $smt->bindParam(':first_name', $first_name);
    $smt->bindParam(':last_name', $last_name);
    $smt->bindParam(':email', $email);
    $smt->execute();
    

    Or the less “bloated” syntax:

    $sql = "INSERT INTO users (first_name, last_name, email)
            VALUES (:first_name, :last_name, :email)";
    
    $smt->prepare($sql);
    $smt->execute(array(
        ':first_name' => $first_name,
        ':last_name' => $last_name,
        ':email' => $email
    ));
    

    As you can see, the parameters are separated from the statement itself. It’s cleaner than interpolating variables into your statements, which look ugly and as I say, lead to injection vulnerabilities.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部