2014-02-14 207 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); 
      }