James.T
James.T

Reputation: 31

How do I echo items from a mysql into a html table?

Hello I am trying to echo items from a Mysql table into a html table this is my code:

    <?php
        $host="localhost";
        $username="root";
        $password="";
        $db_name="content_management"; 
        $tbl_name="houses";

        mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
        mysql_select_db("$db_name")or die("cannot select DB");

        $sql = "SELECT * FROM $tbl_name";
        $result=mysql_query($sql);

        while ( $row = mysql_fetch_assoc($result) ) {
            echo "<img src='" . $row['picture'] . "'>";
                echo $row['price'];
                echo $row['type'];
            echo $row['location'];
            echo $row['description'];
        }
    ?>

I want to echo the picture, price, type, location and the description of the house.

I have tried using various ways (Which most of them didn't work unless I screwed up somewhere) can you give me recommendations I should use?

Upvotes: 0

Views: 64

Answers (2)

Ravi Singh
Ravi Singh

Reputation: 76

<?php 

echo item();    

function item()
 {
    $html='';
    $host="localhost";
    $username="root";
    $password="";
    $db_name="content_management"; 
    $tbl_name="houses";

    mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
    mysql_select_db("$db_name")or die("cannot select DB");

    $sql = "SELECT * FROM $tbl_name";
    $result=mysql_query($sql);

    $html .="<table>";

   while ( $row = mysql_fetch_assoc($result) )
   {

       $html .="<tr><td><img src='" . $row['picture'] . "'></td>";
       $html .="<td>".$row['price']."</td>";
       $html .="<td>".$row['type']."</td>";
       $html .="<td>".$row['location']."</td>";
       $html .="<td>".$row['description']."</td></tr>";

    }
 $html .="</table>";

return $html;
}
?>

Upvotes: 1

O. Jones
O. Jones

Reputation: 108641

How about using something like this?

    echo '<table>';
    while ( $row = mysql_fetch_assoc($result) ) {
        sprintf('<tr><td><img src="%s"></td> <td>%s</td> <td>%s</td><td>%s</td><td>%s</td></tr>\n',
             $row['picture'], 
             $row['price'], $row['type'], $row['location'],
             $row['description']);
    }
    echo '</table>';

sprintf() formats a string. It uses %s as a placeholder for each parameter in its call. This generates the html table row markup for your information, putting each column from your query in its own <td> cell.

Upvotes: 0

Related Questions