0

I started learning PHP and Databases today.

What I tried so far and worked is to access information from a database using a simple updateScores.php file.

DB high_scores:


  names  | scores |
___________________
 player1 |  20    |

 player2 |  69    |

My code:

$host="localhost";
$database="players";
$user="root";
$password = "";
$error = "Cant connect";

$con = mysqli_connect($host, $user, $password);
mysqli_select_db($con, $database) or die("Unable to connect!");

$query = "SELECT * FROM high_scores";
$result = mysqli_query($con, $query);
$n = mysqli_num_rows($result);

for($i=0; $i<$n; $i++){

    $name = mysqli_fetch_assoc($result)["name"];
    $score = mysqli_fetch_assoc($result)["score"];
    echo "Name  : ".$name;
    echo "Score : ".$score;
}
?>

This works fine when i execute http://localhost/updateScores.php

However when i change the last two lines to

echo $name."\t";
echo $score."\n"; 

I only get the first name (player1) and the last score (69) Why this is happening? Any help and additional link would be great. Thanks.

enter image description here

1
  • use: header('Content-Type: text/plain'); for it to work in browser Commented Sep 4, 2019 at 22:17

2 Answers 2

4

Your problem is that your for loop has two calls to mysqli_fetch_assoc, each of which fetches a new row from the database:

$name = mysqli_fetch_assoc($result)["name"];
$score = mysqli_fetch_assoc($result)["score"];

So you will end up getting the name from one row with the score from the next. The normal way of writing this loop is using while, with the fetch as the condition for the loop and then accessing the individual values from the fetched row:

while ($row = mysqli_fetch_assoc($result)) {
    $name = $row["name"];
    $score = $row["score"];
    echo "Name  : ".$name;
    echo "Score : ".$score;
}
Sign up to request clarification or add additional context in comments.

Comments

2

MySQLi result is traversable. You could simply use foreach.

$result = mysqli_query($con, $query);
foreach($result as $row) {
    echo "Name  : ".$row['name'];
    echo "Score : ".$row['score'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.