dongyan7172 2013-09-10 20:15
浏览 50
已采纳

我在PHP中运行此代码时收到错误

I keep receiving some variant of this error message:

Warning: PDO::exec(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@email.com",5,2)' at line 1 in C:\xampp\htdocs\donations\index.php on line 31

The PHP it is referring to is this:

$db->exec("INSERT INTO donations(name, email, donation_amount, item_id) VALUES(\"" . $_POST['name'] . "\"," . $_POST['email'] . "\"," . $_POST['amount'] . "," . $_POST['radioButtons'] . ");");

Am I not escaping correctly or do I have too many quotes? Any help is appreciated!

  • 写回答

3条回答 默认 最新

  • dpvv37755 2013-09-10 20:22
    关注

    You're already on a right track using PDO. Now the next step is to use it properly by utilizing prepared statements.

    That being said your code might look something like this:

    //TODO Check, validate, sanitize your input...
    $name = $_POST['name'];
    $email = $_POST['email'];
    $donation_amount = $_POST['amount'];
    $item_id = $_POST['radioButtons'];
    
    try {
        $db = new PDO('mysql:host=localhost;dbname=your_db_name', 'user', 'password');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    
        //Construct your query with placeholders
        $sql = "INSERT INTO donations (name, email, donation_amount, item_id) 
                VALUES (?, ?, ?, ?, ?)";
        //Prepare your query
        $query = $db->prepare($sql);
    
        //Execute it passing parameters
        $query->execute(array($name, $email, $donation_amount, $item_id));
    
    } catch (PDOException $e) {
        echo "Exception: " . $e->getMessage(); //TODO better error handling
    }
    $query = null;
    $db = null;
    

    Further reading:

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

报告相同问题?

悬赏问题

  • ¥15 速帮,学校需要在外上班没空
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义