我正在创建一个具有基本功能的博客,其中之一是将帖子添加到数据库。
这是我编写的代码,当用户单击提交时将数据插入数据库:
if(isset($_POST['submit'])){
//Assign the variables
$title = mysqli_real_escape_string($db->link, $_POST['title']);
$category = mysqli_real_escape_string($db->link, $_POST['category']);
$body = mysqli_real_escape_string($db->link, $_POST['body']);
$author = mysqli_real_escape_string($db->link, $_POST['author']);
$tags = mysqli_real_escape_string($db->link, $_POST['tags']);
// //Simlpe Validation
if($title == '' || $category='' ||$body == '' || $author == ''){
//Set Error
$error = 'Please fill out all the required fields.';
}
else{
$query = "insert into posts (title, body, author, tags, category) values ('$title','$body', '$author', '$tags',$category)";
$insert_row = $db->insert($query);
}
}
错误提示:
You 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
奇怪的部分来了。
当我排除 if 和 else 语句并直接在 if 和 else 语句之外运行查询时,如下所示:
$query = "insert into posts (title, body, author, tags, category) values ('$title','$body', '$author', '$tags',$category)";
$insert_row = $db->insert($query);
// Simlpe Validation
// if($title == '' || $category='' ||$body == '' || $author == ''){
// //Set Error
// $error = 'Please fill out all the required fields.';
// }
// else{
// }
但是使用上面的代码,查询运行完美并且数据库得到更新。
有人能解释一下吗?
我很难理解为什么它会这样。
顺便说一句,这是数据库类中用于插入的方法:
/*
* Insert
*/
public function insert($query){
$insert_row = $this->link->query($query) or die($this->link->error);
//Validate insert
if($insert_row){
header("Location: index.php?msg=".urlencode('Record Added'));
exit();
}
else{
die('Error: ('.$this->link->errno.') '.$this->link->error);
}
}
编辑: 有人问“类别”。嗯,$_POST['category'] 是一个整数,显然 posts 表的列类别也是一个整数。这就是为什么我没有在查询中保留 $category 周围的任何引号。
最佳答案
感谢 @FDavidov 建议我开始登录这两个场景。我发现在 if 语句中,而不是这样:
$constant == ''
我写了这个:
$constant =''
这覆盖了 $category
的值,因此查询中存在一个前导 ,
(额外的逗号),从而导致语法错误。
我将其更正为$constant == ''
。现在一切都很好。
关于php - 谁能解释 MariaDB 这种奇怪的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41414292/