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.

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

报告相同问题?

悬赏问题

  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器
  • ¥15 关于#爬虫#的问题:请问HMDB代谢物爬虫的那个工具可以提供一下吗
  • ¥15 vue3+electron打包获取本地视频属性,文件夹里面有ffprobe.exe 文件还会报错这是什么原因呢?
  • ¥20 用51单片机控制急停。
  • ¥15 孟德尔随机化结果不一致