首页 > 解决方案 > Fail to pass a boolean value through a SQL request

问题描述

I want to pass the values of the below form in a database set up with phpMyAdmin:

<form action="recordBook.php" method="post">
    <input type="text" name="title" placeholder="Enter the book title">
    <input type="text" name="author" placeholder="Enter the author's name">
    <input type="checkbox" name="read" value="1">
    <br><input type="submit">
</form>

The following piece of php works fine when I don't pass the last variable $read. Whenever I pass $read, an error of SQL syntax is thrown. I tried multiple variant to replace 1 and 0: true, TRUE, etc with no positive result. In my database, the column "read" is set as tinyint

<?php

include "db_connect.php";

$title = $_POST['title'];
$author = $_POST['author'];
$read = isset($_POST['read']) ? 1 : 0;

echo "<script>console.log('".$title.$author.$read."');</script>";
$sql=("INSERT INTO books (title,author_name, read) VALUES ('$title','$author', '$read')");

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

Would someone know what could cause this error ?

标签: phpsqlformsphpmyadminboolean

解决方案


Please try this:

$read = $letter = isset($_POST['read']) ? 1 : 0;

推荐阅读