heron
heron

Reputation: 3659

How to output MySQL table in PHP

I'm testing this code

$query = "SELECT * from `items` where category_id=?";
$stmt = $mysqli->query($query);
$stmt->bind_param("s", $category_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $stmt->fetch_assoc()) {
    printf ("%s (%s)\n", $row['name'], $row['code']);
}

Is there any easier way to output whole table to HTML markup?

Upvotes: 1

Views: 1761

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157919

Is there any easier way to output whole table to HTML markup?

Sure.
Learn to use templates.

Just separate your prepared statements from output.
To do so, at first collect your data into array:

/* fetch values */
$data = array();
while ($row = $stmt->fetch_assoc()) {
    $data[] = $row;
}

and then start output with whatever HTML markup you like (preferably by means of including a separate template file:

<table>
<?php foreach($data as $row): ?>
  <tr>
    <td>
      <a href="?id=<?= htmlspecialchars($row['id']) ?>">
        <?= htmlspecialchars($row['name']) ?>
      </a>
    </td>
  </tr>
<?php endforeach ?>
</table>
  

Upvotes: 2

Vijin Paulraj
Vijin Paulraj

Reputation: 4648

The following code snippet can match your requirements..but i'm not sure whether this is easier way or not..Hope this will help.

For the php,

$pricequery="SELECT price FROM technoxchange";
$result=mysql_query($pricequery);

while($row= mysql_fetch_array($result)){
   $prices [] = $row['price'];
}

echo json_encode( array( 'prices' => $prices ) ); 

For the js,

var p;
$.get("getTechnoXchange.php", function(data){
    p = data.prices;
});

$('#priceUnicus').html( p[0] ); 
$('#priceHire').html( p[1] ); 
$('#priceMonsterArena').html( p[2] ); 

Upvotes: 0

Related Questions