php - 从MySQL数据库获取数据时查询失败

标签 php mysql

我正在尝试从我在 phpMyAdmin 中创建的数据库获取数据。我的问题是,无论我如何更改查询,我都会使用 mysql_error() 函数收到相同类型的错误消息:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''foods'' at line 1

PHP代码索引文件:

<?php
require 'connect.inc.php';

$query = "SELECT 'food_type', 'calories' FROM 'foods'";

if($query_run = mysql_query($query)){

    while ($query_row = mysql_fetch_assoc($query_run)){
        $food = $query_row('food_type');
        $calories = $query_row('calories');

        echo $food.' has '.$calories.' calories ';
    }
}else{
    echo mysql_error();
}
?>

PHP代码数据库连接文件:

<?php
$connectionError = 'Can\'t connect.';

$mySqlHost = 'localhost';
$mySqlUser = 'root';
$mySqlPassword = 'Bhu8Nji9';

$mySqlDataBase = 'my_first_database';

if(!@mysql_connect($mySqlHost, $mySqlUser, $mySqlPassword) || !@mysql_select_db($mySqlDataBase)){
    die($connectionError);
}else{
    //echo 'Connected';
}
?>

最佳答案

重写您的查询[使用反引号而不是单引号]

$query = "SELECT 'food_type', 'calories' FROM 'foods'";

$query = "SELECT `food_type`, `calories` FROM foods";

关于php - 从MySQL数据库获取数据时查询失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20855101/

相关文章:

javascript - 解码 youtube base.js 密码 2016

php - 使用 Google API 根据城市和州生成邮政编码

php - 插入数据库时​​如何获取ID

从 Latin-1 到 UTF-8 的 MySQL 编码

mysql - 查询建立带内连接的临时表

php - 从具有每个用户限制的同一个表中获取记录

php - 更新后的 Imagemagick/ghostscript PDF 错误

php - Mysql搜索字段不同的顺序

Java Hibernate Web 应用程序无法使用 MySQL 数据库显示数据

MySQL 分解字符串?