dqypcghd381390 2018-08-17 20:11
浏览 53
已采纳

尝试将数据从文本字段插入数据库时​​获取MySQL错误

I am getting this error when trying to insert data into my database from my website:

Error: INSERT INTO newtask (new_category, new_department, new_required, 
new_name, new_address, new_contact, new_email,  new_logged, new_description) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
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 '?, ?, ?, ?, ?, ?, ?, 
?, 
?)' at line 1

Here is my code:

<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'tasks_db';


$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO newtask (new_category, new_department, new_required, 
new_name, new_address, new_contact, new_email,  new_logged, new_description) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?> 

Not sure what i am doing wrong here?

  • 写回答

1条回答 默认 最新

  • douzi1117 2018-08-17 20:19
    关注

    This is a prepared statement, so you need to prepare it, bind your values, and then execute it:

    $stmt = $conn->prepare("INSERT INTO newtask (new_category, new_department, new_required, 
    new_name, new_address, new_contact, new_email,  new_logged, new_description) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    
    // One "s" per placeholder value, plus one value per "s" after
    $stmt->bind_param("sssssssss", $new_category, $new_department, ...);
    
    if ($stmt->execute()) {
      echo "New record created successfully";
    } else {
      echo "Error: " . $sql . "<br>" . $conn->error;
    }
    

    Where $new_category is whatever value is going into that column and so on. This is all covered in the documentation.

    The mistake is you were trying to run a SQL query with placeholder values and no data. ? is not a valid value in MySQL. It's replaced at the driver level by the bind_param operation on statements produced with prepare. The query function executes code as-is with no changes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题