Mysql插入查询问题

时间:2014-02-14 14:39:55

标签: php html 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>';

        }
    }
?>

4 个答案:

答案 0 :(得分: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()(以获取错误代码)和{{ 3}}(获取错误消息)。它会告诉你查询有什么问题。

答案 1 :(得分:1)

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

答案 2 :(得分:1)

试试这个

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

答案 3 :(得分:0)

您也可以尝试使用此工作插入语句,但稍后您将在现实世界中实现代码,出于安全考虑,您必须对其进行编辑。

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