1

So my problem is that I'm trying to get all first_name from a students table, but when I do mysqli_fetch_array and output the results using print_r()1, it outputs only the first first_name in the table.

Students Table

students_id | first_name | last_name | teacher_id
1           | abc        | efg       | 10
2           | 123        | xyz       | 10

So the output is Array ( [0] => wda [first_name] => wda ). But I want it to output both the first_name.

Also I'm getting a duplicate of the same data.

Example

Array ( [0] => abc [first_name] => abc )

The array is storing abc twice, so how can I not get a duplicate of the data?

PHP Code

<!DOCTYPE html>
<html>
<head>
    <title>Name Tags</title>
</head>
<body>
    <?php 

        require '../../connect.php';

        $results = mysqli_query($link, "SELECT first_name FROM students");

        if($results) {
            $results_arr = mysqli_fetch_array($results);

            print_r($results_arr);

            if(is_array($results_arr)) {
                foreach ($results_arr as $fname) {
                    echo "

                        <h1>$fname</h1>

                    ";
                }
            } else {
                echo '<h1>Empty</h1>';
            }
        } else {
            echo 'Sorry, we ran into an error, please try again later.';
        }

     ?>
</body>
</html>

2 Answers 2

1

mysqli_fetch_array() (and the other mysqli_fetch_XXX() functions) just returns one row of the results. You have to call it in a loop to get all the rows. You don't need to loop over this array, just access the columns you want.

while ($row = mysqli_fetch_assoc($results)) {
    $fname = $row['first_name'];
    echo "<h1>$fname</h1>";
}
Sign up to request clarification or add additional context in comments.

Comments

0

Mysqli_fetch_array() only retrieves a single row of output:

while($r=mysqli_fetch_array($result)) {
  print $r[0] . "<br />";
}

Comments

Your Answer

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