【问题标题】:how i can slove this error,SQLSTATE[42000]? [duplicate]我该如何解决这个错误,SQLSTATE [42000]? [复制]
【发布时间】:2020-03-16 21:35:15
【问题描述】:

请帮我解决这个错误。我厌倦了寻找解决方案... 错误:SQLSTATE [42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MariaDB 服务器版本相对应的手册,以在第 1 行的“WHERE name=NULL”附近使用正确的语法

我的数据库有 3 列=id(int),name(varchar),comment(varchar),我想在其中插入评论。

我的 php 代码:

<?php
include "./Config.php";
include './MyPDO.php';

  $response = array() ;
  $connect = MyPDO::getInstance();

  $name = $_REQUEST['name'];
  $comment=$_REQUEST['comment'];

        $query =  " INSERT INTO user "
                . " (comment) "
                . " VALUES "
                . " (:comment) "
                . " WHERE name=:name ";

        $stmt = $connect->prepare($query);
        $stmt->bindParam(":name",$name);
        $stmt->bindParam(":comment",$comment);
        try {
                $stmt->execute();
                $response['massage'] = "sucess";
                echo json_encode($response);
                exit;
        } catch (PDOException $ex) { 
                $response['massage'] = "error";
                $response['error']=$ex->getMessage();
                echo json_encode($response);
        }







【问题讨论】:

  • INSERT 用于创建新行,UPDATE 用于创建新行。在 INSERT 查询中使用 WHERE 是没有意义的。
  • 谢谢,我刚学php一周..

标签: php mysql sql sql-update sql-insert


【解决方案1】:

看起来你在这里混合了语法。您似乎想要更新现有记录。使用

update user
set comment = :comment
where name = :name

insert 如果用于创建新记录。

【讨论】:

    【解决方案2】:

    insert into ... values() 语法不采用where 子句。

    如果你想insert,那么:

    insert into user(name, comment) values(:name, :comment)
    

    但实际上你可能想要update

    update users set comment = :comment where name = :name;
    

    前者在表中使用给定的名称和注释创建一条新记录。

    后者修改已存在的具有相同name 的记录并设置其comment 值。

    【讨论】:

      猜你喜欢
      • 2011-09-04
      • 1970-01-01
      • 2016-07-21
      • 2016-09-09
      • 2015-02-28
      • 2013-08-16
      相关资源
      最近更新 更多