0

I am trying to echo out the number of agility that is set in the database. This is my current code, if you could check it out and see if there is anything i need to change to get it working. Currently im getting the error

Notice: Undefined offset: 0 in

$dbserver = "localhost";
$dbusername = "root";
$dbpassword = "*******";
$db     = "********";

//CREATE CONNECTION
  $conn = new mysqli($dbserver, $dbusername, $dbpassword, $db);
$id = $_SESSION['loggedin'];
$query = "SELECT * FROM stats WHERE id='$id'";
$stmt = mysqli_query($conn, $query);
$result = mysqli_fetch_all($stmt,MYSQLI_ASSOC);



<div class="Agility">
       <h2>Agility</h2>
       <p><?php echo $result[0]['agility']; ?></p>
    </div>
Peterssoen
  • 157
  • 3
  • 12
  • seems like there is no $result[0] as your error notice says that. This can happen when there are no records found in the DB – Mr.Moe Nov 24 '17 at 23:38
  • The fastest, quickest way to see what is going on... is to inspect what $result actually is. You can do that by adding a line var_dump($result); after you have assigned it i.e after your $result=mysqli_fetch_all()..... statement. What do you get? – TimBrownlaw Nov 24 '17 at 23:53

1 Answers1

2

First off, since your id field is probably unique, you should limit the query to one. Then, check the number of rows returned by the query before displaying the results in case there are none.

$query = "SELECT * FROM stats WHERE id='$id' LIMIT 1";
$stmt = mysqli_query($conn, $query);

if(mysqli_num_rows($stmt) > 0){
    $result = mysqli_fetch_all($stmt,MYSQLI_ASSOC);

?>
<div class="Agility">
       <h2>Agility</h2>
       <p><?php echo $result[0]['agility']; ?></p>
    </div>

<?php } else { ?>
<p>There are no results.</p>
<?php } ?>
ShoeLace1291
  • 4,551
  • 12
  • 45
  • 81
  • Sorry, but why should he limit the query to one if the column is already unique? I tried to find that out myself, but I found that: https://stackoverflow.com/questions/3848390/is-there-any-point-using-mysql-limit-1-when-querying-on-indexed-unique-field – grobmotoriker Nov 24 '17 at 23:48