vdhmartijn
vdhmartijn

Reputation: 104

how to echo table in php by mysql

Trying to show the table but isn't working, what am I doing wrong?

<?php

$query = "SELECT id menu_id menu_title FROM tbl_menu";
$result = mysql_query($query);

if(mysql_num_rows($result) > 0){
    while ($row = mysql_fetch_array($result)){
        echo $row['menu_title'];echo 'test';
    }
}

?>

Upvotes: 0

Views: 148

Answers (5)

sybear
sybear

Reputation: 7784

$query = "SELECT id, menu_id, menu_title FROM tbl_menu";
$result = mysql_query($query);

if($result && mysql_num_rows($result) > 0){
    while ($row = mysql_fetch_assoc($result)){
        echo $row['menu_title'];
    }
}

To note:

mysql_fetch_array() returns a number-indexed array

mysql_fetch_assoc() returns a string-indexed array (indices are names of your fields)

And please, stop using mysql, it is deprecated. Use mysqli instead.

Upvotes: 0

Jason
Jason

Reputation: 2727

$query = "SELECT id, menu_id, menu_title FROM tbl_menu";

Upvotes: 1

Ragen Dazs
Ragen Dazs

Reputation: 2170

$query = "SELECT id menu_id menu_title FROM tbl_menu";

Must Be

$query = "SELECT id, menu_id, menu_title FROM tbl_menu";

Your SQL have a typo

Upvotes: 0

Kermit
Kermit

Reputation: 34055

It doesn't look like you are connecting to anything. You also need to separate column names by commas:

SELECT id, menu_id, menu_title FROM tbl_menu

Here's a mysqli_ example from the documentation:

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT id, menu_id, menu_title FROM tbl_menu";

if ($result = mysqli_query($link, $query)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_assoc($result)) {
        echo $row[menu_id];
    }

    /* free result set */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157839

$result = mysql_query($query) or trigger_error(mysql_error());

Upvotes: 0

Related Questions