带有WHERE子句的PDO INSERT

时间:2015-03-18 11:16:14

标签: php sql insert

我想使用带PDO的MySQL将数据插入到现有表中。我不知道如何在INSERT INTO查询中使用WHERE语句。我的代码:

if(isset($url)){
        if(preg_match($pattern, $url) ){
            $user = $_SESSION['user'];
            try {
                // prepared statement to insert user data
                $sql = "INSERT INTO user (website) where username = :username VALUES (:website)";
                $stmt = $conn->prepare($sql);
                $stmt->bindParam(':website', $url);
                $stmt->bindParam(':username', $user);
                $stmt->execute();
            }
            //Exception handling
            catch(PDOException $e)
            {
                $urlError =  $e->getMessage();
            }

每次我尝试INSERT都失败了。我是php的新手,所以请不要对我太过刻意。

2 个答案:

答案 0 :(得分:2)

我猜你不想要insert。你真的想要update

UPDATE user
    SET website = :website
    WHERE username = :username;

UPDATE更改现有行中的列。 INSERT将新行添加到表格中。

答案 1 :(得分:1)

检查一下:

if(isset($url)){
    if(preg_match($pattern, $url) ){
        $user = $_SESSION['user'];
        try {
            // prepared statement to insert user data
            $sql = "UPDATE user SET website = :website WHERE username = :username";
            $stmt = $conn->prepare($sql);
            $stmt->bindParam(':website', $url);
            $stmt->bindParam(':username', $user);
            $stmt->execute();
        }
        //Exception handling
        catch(PDOException $e)
        {
            $urlError =  $e->getMessage();
        }
    }
}