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';
}
?>
1
  • 2
    In your query, swap those apostrophes for backticks. Since none of them are reserved words, you can get away with removing them too. Commented Dec 31, 2013 at 9:36

6 Answers 6

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";
Sign up to request clarification or add additional context in comments.

4 Comments

Or just SELECT food_type, calories FROM foods - and now change your password.
@Strawberry, Yes but it is always a good practice to enclose the columns under backticks.
It is good practice, but it's also incredibly irritating IMHO. A better idea is to avoid the use of reserved words.
@Strawberry, Exactly. +1
1

use this..

$result = mysql_query("SELECT food_type,calories FROM foods");
while($row = mysql_fetch_array($result))
{...}

Comments

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

Comments

0

Can you try this, added backticks in table foods

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

Comments

0

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

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.