2017-01-01 129 views
0

我正在创建一个具有基本功能的博客,其中一个是向数据库添加帖子。任何人都可以解释MariaDB的这种奇怪的行为吗?

这里是一个将数据插入到数据库中,我已经写的代码,当用户点击提交:

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); 
     } 
    } 

但是,当我提交此表: enter image description here

我得到这样的错误: enter image description here

错误说:

您的SQL语法有错误;检查 对应于您MariaDB的服务器版本正确的语法使用 附近“)”在行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附近保留任何引号。

+0

首先,请在两种情况下添加正在向MySQL发送的字符串的日志记录。根据错误消息,字符串中存在语法错误,所以我们最好在挖掘您的代码之前开始分析该特定元素。 – FDavidov

+0

我在phpmyadmin上运行了相同的查询,并且没有错误,查询执行完美。 – madhuspot

+1

是的,我从你的帖子了解到。不过,在这两种情况下添加日志并将其发布。 – FDavidov

回答

2

感谢@FDavidov建议我在两种情况下开始登录。而且我发现,在if语句,而不是这样的:

$constant == '' 

我写了这个:

$constant ='' 

哪个改写的$category值,因此本有领先, (额外的逗号)导致语法错误。

我改正了它回到$constant == ''。现在一切都很好。

相关问题