【问题标题】:Mysql syntax error in select statement选择语句中的Mysql语法错误
【发布时间】:2016-12-26 06:29:07
【问题描述】:

我有一张表main_tag,其结构为

1   id int(100) 
2   name varchar(100)   
3   description varchar(1000)
4   added_on timestamp  

并具有php的功能如下

function all_data_of_main_tag_table(){

        include_once 'db.php';
        $conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
        $json = array();
        $nameQuery ='SELECT * FROM `main_tag` WHERE 1';
        echo '<br>'.$nameQuery.'<br>';
        $rsnameQuery = $conn->query($nameQuery);      
        if($rsnameQuery === false){
            echo 'hi'.'<br>';
            trigger_error('Wrong SQL: '.$nameQuery.' Error: '.$conn->error, E_USER_ERROR);
        }
        else{
           $rows_returned = $rsnameQuery->num_rows;
        }
        while($row = $rsnameQuery->fetch_assoc()){
            $json =$row;
        }
        $conn->close();
        return $json;
    }

运行此函数时出现错误:

{
  "description": null,
  "name": null,
  "id": null
}
MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1

【问题讨论】:

  • 你试过查询为:SELECT * FROM main_tag
  • 您的查询似乎没问题。
  • “错误的 SQL”位在哪里?也许此错误消息指的是不同的查询
  • 您确定是收到错误的查询吗?您的代码中的错误消息以Wrong SQL: 开头,但您的消息显示MySQL error:。它也不会像您的 trigger_error() 调用那样打印 $nameQuery
  • 另外,如果你想推入一个数组,你应该使用$json[] = $row;。你每次都覆盖变量,所以你只得到最后一行。

标签: php mysql mariadb


【解决方案1】:

在您的查询中,您没有指定查看位置

Where 1

它没有指定任何列

// it should be something like this 
Where id = 1

所以你的查询是这样的

$nameQuery ='SELECT * FROM `main_tag` WHERE id = 1

【讨论】:

    【解决方案2】:

    我的错误是我的查询没问题,错误是其他查询。然而

    while ($row = mysqli_fetch_assoc($rsnameQuery)) {
       $json[] = $row;
    }
    

    这是要写的,而不是

    while($row = $rsnameQuery->fetch_assoc()){
         $json =$row;
    }
    

    这没有返回数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      相关资源
      最近更新 更多