joebegborg07 joebegborg07 - 2 years ago 66
SQL Question

PHP - mysql_fetch_assoc() issue

I'm new to PHP and I'm trying to learn how to display data I select from a mysql database (phpmyadmin). My current php code consists of 2 files and connecting.php: is the file used to establish connection with the database:

//MYSQL details

$db_conn_error='Could not connect to database';

if(mysql_connect($mysql_server, $mysql_user, $mysql_user_pass)
and mysql_select_db($mysql_db)){
echo 'Connection is ok'.'<br>';
echo 'Connection is not ok';

while the other file (connecting.php) should display any records in the particular table called food :

require '';

$query = "SELECT 'food', 'calories' FROM food ORDER BY 'id'";

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

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

echo $food . ' has '.$calories.' calories.<br>';

echo 'Query Failed';

Additional details:

  • server name : localhost

  • user : root

  • password : 12345678

  • database name : test

  • table name : food

  • field names : id, food, calories, healthy_unhealthy

Ths issue is that whenever i execute code in the file connecting.php i always get the following:

  • Connection is ok

  • food has calories calories.

  • food has calories calories.

When it should say

  • Connection is ok

  • Pizza has 1000 calories

  • Salad has 200 calories

Help is highly appreciated :)

Thanks in advance,

Joe :)

Answer Source


$query = "SELECT `food`,`calories` FROM `food` ORDER BY 'id'";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download