1

Working on a Highscore system in PHP. To get data from MySQL database I use this code.

<?php
$sql_query = "SELECT id,name, exp FROM user ORDER by exp DESC";
try {
    $conn = new PDO('mysql:host=localhost;dbname=game', 'root', 'pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $rst = $conn->query($sql_query);
    $users= $rst->fetchAll(PDO::FETCH_OBJ);
    echo '' . json_encode($users) . '';
}
catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>

Output from that code looks like:

[{"id":"1","name":"Player","exp":"22060"}

I need to echo that data in tags separately. For example.

<td><?php echo $users->name ?></td>
<td><?php echo $users->exp ?></td>
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Martin Bariak
  • 31
  • 1
  • 7

1 Answers1

0

This should do the trick:

<?php
$sql_query = "SELECT id,name, exp FROM user ORDER by exp DESC";
try {
    $conn = new PDO('mysql:host=localhost;dbname=game', 'root', 'pass');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $rst = $conn->query($sql_query);
    $users= $rst->fetchAll(PDO::FETCH_OBJ);

    foreach($users as $user) {
        echo "<td>{$user->name}</td>";
        echo "<td>{$user->exp}</td>";
    }
}
catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
Jim Wright
  • 5,905
  • 1
  • 15
  • 34