【问题标题】:Why isn't this simple insert statement working (PDO)?为什么这个简单的插入语句不起作用(PDO)?
【发布时间】:2012-01-10 13:14:47
【问题描述】:

代码很简单——从表单中获取一个值,将其插入到 mysql 数据库中。这是一个sn-p:

//connect to DB
$dbh = new PDO($db_pdo, $db_user_name, $db_password);

//capture value from form
$first_name = $_POST['first_name'];

//insert value into DB (doesn't work- no new entry created in requests)
$dbh->exec("INSERT INTO requests(first_name) VALUES($first_name)");

//this echo statement works (outputs the value of $first_name):
echo "\$first_name ".$first_name;

//this insert statement works: 
$dbh->exec("INSERT INTO requests(first_name) VALUES('oleg')");

【问题讨论】:

    标签: php mysql pdo


    【解决方案1】:

    没错,你必须引用你的字符串。

    $dbh->exec("INSERT INTO requests(first_name) VALUES('$first_name')");
    

    但此代码易受 SQL 注入攻击。我不确定你如何在 PHP 中防止这种情况发生。

    【讨论】:

    • 我不喜欢依赖 PHP 来找出文本中的变量...我至少会尝试 $dbh->exec("INSERT INTO requests(first_name) VALUES('{$first_name}')");
    • 值得一提的是,有准备好的语句 PDO 可用
    • @JoshToth:现代 IDE 突出了这种拼接,这不是问题。还是你的意思是别的?
    • @Sergio Tulentsev:不,无聊到无法再描述它了)
    • 谢谢。我意识到它很容易受到一系列问题的影响——我的下一步是安全——只是想让基本的数据库正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多