0

I'm trying to get data from an database that I have created in phpMyAdmin. My problem is that however I change my query I'm getting the same type of error message using the mysql_error() function:

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 code index file:

<?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 code database connection file:

<?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';
}
?>
halfer
  • 19,824
  • 17
  • 99
  • 186
BuzzLajtjer
  • 23
  • 1
  • 3
  • 2
    In your query, swap those apostrophes for backticks. Since none of them are reserved words, you can get away with removing them too. – halfer Dec 31 '13 at 09:36

6 Answers6

1

Rewrite your query [Use Backticks instead of Single quotes]

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

to

$query = "SELECT `food_type`, `calories` FROM foods";
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
1

use this..

$result = mysql_query("SELECT food_type,calories FROM foods");
while($row = mysql_fetch_array($result))
{...}
GOPI
  • 1,042
  • 8
  • 30
0

Do not use single quotes around table name and field names.

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

Also avoid mysql_* functions.

Why shouldn't I use mysql_* functions in PHP?

Read following to know when or why to use backticks

Using backticks around field names

Community
  • 1
  • 1
chanchal118
  • 3,551
  • 2
  • 26
  • 52
0

Can you try this, added backticks in table foods

$query = "SELECT food_type, calories FROM `foods`";
Krish R
  • 22,583
  • 7
  • 50
  • 59
0

It is a problem regarding of unknown column name you should use backtick as:

$query = "SELECT `food_type`, `calories` FROM foods";
Dinesh
  • 4,066
  • 5
  • 21
  • 35
0

There is a syntax error in your query. It should be as below,

$query = "SELECT food_type, calories FROM `foods`";
Adarsh Nahar
  • 319
  • 3
  • 10