2014-02-14 204 views
-1

我有這個查詢的問題,它不插入由於某種原因。它有什麼問題嗎?Mysql插入查詢問題

<?php  
    if (isset($_POST['submit'])) { 

     $email = $_POST['email']; 
     $name = $_POST['name']; 
     $comment = $_POST['comment']; 

     if($email && $name) { 

      if($comment) { 

       $connect = mysql_connect("dragon.kent.ac.uk", "repo", "3tpyril"); 

       mysql_select_db("repo"); 

       $query = mysql_query("INSERT into comments(comment, name,email, newsitemId) VALUES ('$email', '$name','$comment',':newsitemId'=> $_POST[newsitemId])"); 

       echo '<script type="text/javascript">alert("Your blog post has been added");</script>'; 
      } else { 

       echo '<script type="text/javascript">alert("Please provide some details");</script>'; 

      } 

     } else { 

      echo '<script type="text/javascript">alert("All fields required");</script>'; 

     } 
    } 
?> 
+2

'':newsitemId'=> $ _POST [newsitemId]'這是錯誤的。嘗試''newsitemId'= $ _ POST [newsitemId]'。此外,mysql_ *函數已被棄用。 –

+0

請減少您的問題,使其涉及_one_語言。不是四個。還學會縮進你的代碼。 –

+0

你在這裏有一個語法錯誤:''':newsitemId'=> $ _POST [newsitemId])''。如果你有任何錯誤,你也可以用''mysql_error()''來檢查。無論如何,你應該切換到MySQLi,因爲這些功能已被棄用。 – sobyte

回答

1

是的。你正在嘗試使用準備好的語句,但完全錯誤的方式。這應該可以解決它:

$query = mysql_query("INSERT into comments(comment, name,email, newsitemId) VALUES ('$email', '$name','$comment','" . mysql_real_escape_string($_POST['newsitemId']) . "')"); 

要使用準備好的聲明中工作,你必須使用PDO和主要思想是將變量綁定到這樣的查詢:

$query = 'INSERT INTO table (column) VALUES (:myValue);'; 
$binds = array(
    'myValue' => $_POST['myValue'] 
); 
$db->Execute($query, $binds); 

(這僅僅是一個點如何它的工作原理,而不是例如本身)

編輯:在未來,如果你將仍然使用mysql_ *功能,您的SQL查詢將看起來像斷了,使用功能mysql_errno()(獲得錯誤代碼)和mysql_error()(獲取錯誤信息)。它會告訴你你的查詢有什麼問題。

1
"INSERT into comments(comment, name,email, newsitemId) VALUES ('$email', '$name','$comment','{$_POST['newsitemId']}')" 
1

試試這個

$query = mysqli_query("INSERT into comments VALUES ('$email', '$name','$comment', '$_POST[newsitemId]')"); 
0

您也可以嘗試這個工作的INSERT語句,但後來,你去和在現實世界中實現你的代碼,你必須編輯出於安全考慮。

$con=mysqli_connect("hostname","username","password","databasename"); 

      if (mysqli_connect_errno()) 
      { 
       echo "Failed to connect to MySQL: " . mysqli_connect_error(); 
      } 
      else 
      { 
       mysqli_query($con,"INSERT INTO comments VALUES ('$email', '$name','$comment', '$_POST[newsitemId]'); 
       mysqli_close($con); 
      }