gpt4 book ai didi

php - 为什么这个简单的插入语句不起作用(PDO)?

转载 作者:行者123 更新时间:2023-11-29 06:11:44 25 4
gpt4 key购买 nike

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

//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')");

最佳答案

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

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

但是这段代码很容易受到 SQL 注入(inject)攻击。我不确定如何在 PHP 中防止这种情况。

关于php - 为什么这个简单的插入语句不起作用(PDO)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8798838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com