Reputation: 23
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';
}
?>
Upvotes: 0
Views: 80
Reputation: 319
There is a syntax error in your query. It should be as below,
$query = "SELECT food_type, calories FROM `foods`";
Upvotes: 0
Reputation: 1060
use this..
$result = mysql_query("SELECT food_type,calories FROM foods");
while($row = mysql_fetch_array($result))
{...}
Upvotes: 1
Reputation: 4110
It is a problem regarding of unknown column name you should use backtick as:
$query = "SELECT `food_type`, `calories` FROM foods";
Upvotes: 0
Reputation: 22711
Can you try this, added backticks in table foods
$query = "SELECT food_type, calories FROM `foods`";
Upvotes: 0
Reputation: 3647
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
Upvotes: 0
Reputation: 68476
Rewrite your query [Use Backticks instead of Single quotes]
$query = "SELECT 'food_type', 'calories' FROM 'foods'";
to
$query = "SELECT `food_type`, `calories` FROM foods";
Upvotes: 1