Reputation: 27
<?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>
i'm beginner in PHP i'm trying to insert data in db using check boxes but an error appear every time " have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''book1,book2,book3)' at line 1"
Upvotes: 0
Views: 11303
Reputation: 8348
$sql = "INSERT INTO books(book_name) VALUES ('$b1')";
You were missing a single quote but still it's a bad practice for insert queries as you are wide open to sql injection. Will update my answer shortly about optimizing your query to make it more secure to use.
Prepared statement Update
$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;
}
This query is using mysqli prepared statement securing you from sql injection. As you said you are really new in php so it's better to learn the correct ways from the start. In development there are many ways to do things but not all of them are right and some leave you open to threats. Here is a great answer from stackoverflow to have a look as well.
Upvotes: 2
Reputation: 167
try this code
<?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>
Upvotes: 0
Reputation: 2634
Change the line:-
$sql = "INSERT INTO books(book_name) VALUES ('$b1)";
-------------------------------------------------^
missing single quote around the value
to:-
$sql = "INSERT INTO books(book_name) VALUES ('$b1')";
Upvotes: 0