2016-04-24 105 views
1

我正要解決這個問題。我的代碼中的一行似乎正在起作用。它返回與其他人似乎並不想運行它。它沒有錯誤,但它不會將其移動到數據庫。正如標題所說,這是一個if語句中的mysqli_query。這裏是代碼,我已經把箭頭放在錯誤似的地方。mysqli_query不能在If語句中工作

 $t_name = $_POST['topic_name']; 
     $content = $_POST['con']; 
     $date = date("y-m-d"); 

     if(isset($_POST['submit'])) { 
      if($t_name && $content) { 
       if(strlen($t_name) >= 10 && strlen($t_name) <= 70) { 
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv 
        if($query = mysqli_query($connect, "INSERT INTO topics('topic_id', 'topic_name', 'topic_content', 'topic_creator', 'date') VALUES ('', '".$t_name."', '".$content."', '".$_SESSION["username"]."', '".$date."')")) { 
         echo "<font color = 'green'>Topic posted!</font>"; 
        } else { 
         echo "<font color='red'>Unknown failure, time to panic!</font>"; 
        } 
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
       } else { 
        echo "<font color='red'>Topic name must be between 10 and 70 characters long!</font>"; 
       } 
      } else { 
       echo "<font color='red'>All fields must be filled out!</font>"; 
      } 
     } 
    } else { 
     include('header.php'); 
     echo "You must be logged in to access this page. Click <a href='login.php'>here</a> to login."; 
    } 
    include('footer.php'); 

是的,我知道SQL注入和其他事情的危險,一旦我有我的代碼關閉,我會處理它。

+0

您是否嘗試從插入中刪除主題ID列? –

+1

哦,離開mysql處理日期!使用「now()」功能! https://dev.mysql.com/doc/refman/5.5/zh-CN/date-and-time-functions.html#function_now –

+1

@HizerCache從來不知道,謝謝! – SkrillexNukehulk

回答

2

您的topic_id不能設置爲空。而是刪除topic_id或給它一個default值。

此外,就像@HizerCache提到的那樣,您可以使用MySQL函數NOW()插入當前時間。

事情是這樣的:

"INSERT INTO topics(topic_id, topic_name, topic_content, topic_creator, date) VALUES (default, '".$t_name."', '".$content."', '".$_SESSION["username"]."', NOW())" 

此外,使用mysqli_error()調試錯誤。

if($query = mysqli_query($connect, "INSERT INTO topics('topic_id', 'topic_name', 'topic_content', 'topic_creator', 'date') VALUES ('', '".$t_name."', '".$content."', '".$_SESSION["username"]."', '".$date."')")) { 
    echo "<font color = 'green'>Topic posted!</font>"; 
} else { 
    echo "Error : " . mysqli_error($connect); 
} 
+0

在服務器上,我將topic_ID設置爲自動增量。這應該不夠嗎? – SkrillexNukehulk

+0

是的,'default'將起作用。或者你可以把它作爲@ObjectManipulator提到 – user3284463

+0

@SkrillexNukehulk通過傳遞'''',它告訴MySQL插入一個空字符串,它不能。使用'default'並將'topic_id'分配到其默認值 – user3284463

3

請刪除引號每列名:「topic_id」,「TOPIC_NAME」 ....「日期」

$query = mysqli_query($connect, "INSERT INTO topics(topic_id, topic_name, topic_content, topic_creator, date) VALUES ('', '".$t_name."', '".$content."', '".$_SESSION["username"]."', '".$date."')") 

爲了瞭解你的錯誤,我建議您調試查詢。嘗試使用mysqli_error()函數。

if (...) { 

} else { 
    die(mysqli_error($connect)); // Add this 
}