您的 SQL 语法有误;查看与您的 MariaDB 服务器版本对应的手册,了解在第 1 行附近使用的正确语法

have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near at line 1

<?php 
include('config.php');
if (isset($_POST['btn'])) {
if (isset($_POST['books'])) {
$b1 = implode(',' , $_POST['books']);



$sql = "INSERT INTO books(book_name) VALUES ('$b1)";
 if($conn->query($sql)=== TRUE){

   echo "your data is saved";
}else{
    echo"try again".$conn->error;
}



$conn->close();?>


<form action="index.php" method="post">
    <h3>Select your Books</h3>
    <input type="checkbox" name="books[]" value="book1">Book 1

    <input type="checkbox" name="books[]" value="book2">Book 2

    <input type="checkbox" name="books[]" value="book3">Book 3
    <input type="submit" name="btn">

</form>

我是 PHP 的初学者,我正在尝试使用复选框在数据库中插入数据,但每次都会出现错误 " 您的 SQL 语法有错误;请查看与您的 MariaDB 服务器版本对应的手册,了解在第 1 行的 ''book1,book2,book3)' 附近使用的正确语法"

改行:-

$sql = "INSERT INTO books(book_name) VALUES ('$b1)";
-------------------------------------------------^
             missing single quote around the value

至:-

$sql = "INSERT INTO books(book_name) VALUES ('$b1')";
$sql = "INSERT INTO books(book_name) VALUES ('$b1')"; 

您遗漏了一个单引号,但对于插入查询来说这仍然是一个不好的做法,因为您对 sql 注入持开放态度。将很快更新我关于优化查询以使其更安全使用的答案。

准备语句更新

$stmt = $conn->prepare("INSERT INTO books(book_name) VALUES (?)");
$stmt->bind_param("s", $b1);

if ($stmt->execute()) { 
 echo "your data is saved";
}else{
    echo"try again".$conn->error;
}

此查询使用 mysqli 准备语句保护您免受 sql 注入。正如您所说,您是 php 的新手,所以最好从一开始就学习正确的方法。在开发中,有很多方法可以做事,但并非所有方法都是正确的,有些方法会让您面临威胁。 Here is a great answer from Whosebug to have a look as well.

试试这个代码

<?php 
include('config.php');
if (isset($_POST['btn'])) {

$b1 = implode(',' , $_POST['books']);


$sql = mysqli_query($conn,"INSERT INTO books(book_name) VALUES ('$b1')");
 if($sql=== TRUE){

   echo "your data is saved";
}else{
    echo"try again".$conn->error;
}


}
$conn->close();
?>


<form action="index.php" method="post">
    <h3>Select your Books</h3>
    <input type="checkbox" name="books[]" value="book1">Book 1

    <input type="checkbox" name="books[]" value="book2">Book 2

    <input type="checkbox" name="books[]" value="book3">Book 3
    <input type="submit" name="btn">

</form>