无法通过php在mysql表中插入数据

时间:2017-03-05 05:29:46

标签: php mysql

我无法将数据插入到mysql表中。我的代码出了什么问题? 这是我用过的PHP代码。提交时我没有回复。 php在html表单所在的同一页面中使用,因此,我的属性是action =""和方法=" post"。请帮忙。 enter code here

<?php
    ob_start();
    session_start();
    require_once 'dbconnect.php';

    // if session is not set this will redirect to login page
    if( !isset($_SESSION['user']) ) {
        header("Location: index.html");
        exit;
    }
    // select loggedin users detail
    $res=mysql_query("SELECT * FROM users WHERE userId=".$_SESSION['user']);
    $userRow=mysql_fetch_array($res);


    if ( isset($_POST['sub']) ) {

        // clean user inputs to prevent sql injections
        $name1 = $_POST['name1'];
        $name2 = $_POST['name2'];
        $name3 = $_POST['name3'];
        $name4 = $_POST['name4'];
        $name5 = $_POST['name5'];
        $name6 = $_POST['name6'];
        $name7 = $_POST['name7'];
        $name8 = $_POST['name8'];
        $name9 = $_POST['name9'];


        if( !$error ) {

            $query = "INSERT INTO users(name1,name2,name3,name4,name5,name6,name7,name8,name9) VALUES('$name1','$name2','$name3','$name4','$name5','$name6','$name7','$name8','$name9') WHERE userId=".$_SESSION['user'];
            $res = mysql_query($query);

            if ($res) {
                $errTyp = "success";
                $errMSG = "Successfully registered, you may login now";
                unset($name1);

            } else {
                $errTyp = "danger";
                $errMSG = "Something went wrong, try again later...";   
            }
            }
}
?>

1 个答案:

答案 0 :(得分:0)

正如Alex.Barylski在评论中指出的那样,INSERT语句会创建一个新行,因此您不能使用WHERE子句(用于检查现有行......)。如果要更新已存在的行,请使用以下代替INSERT语句:

     $query = 'UPDATE users SET name1 = "$name1", name2 = "$name2", name3 = "$name3" WHERE userId=' . $_SESSION['user'];

另请注意,您可以使用mysql_affected_rows()检查您的UPDATE查询是否成功,请参阅此问题:How do I tell when a MySQL UPDATE was successful versus actually updated data?