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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。