2017-01-01 38 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 == ''。現在一切都很好。

相關問題