0

Basically I first query specific columns from a mysql table and want to echo them all using foreach() in php. Here is my code.

$sql = "SELECT id, name, roll_no, email, title, abstract, supervisor, sub_date
        FROM student_data";

$result = $conn->query($sql);
$array = $result->fetch_assoc();

foreach ($array as $x => $value)
{
    echo $array["id"] . " " . $array["name"] . " " . $array["roll_no"] . " " . $array["title"] . " " . $array["supervisor"] . " " . $array["sub_date"] ."<br><br>";
}

It simply keeps repeating the first entry.

2 Answers 2

2

You're only looping through the elements in the first result set. You need to iterate through the entire result set:

while($array= $result->fetch_assoc()) {
    echo $array["id"] . " " . $array["name"] . " " . $array["roll_no"] . " " . $array["title"] . " " . $array["supervisor"] . " " . $array["sub_date"] ."<br><br>";
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your main missunderstanding is that $array = $result->fetch_assoc(); returns only one result. To get the second one you should call $result->fetch_assoc() once again. So you should iterate in this way

while ($array = $result->fetch_assoc()) {
echo $array["id"] . " " . $array["name"] . " " . $array["roll_no"] . " " . $array["title"] . " " . $array["supervisor"] . " " . $array["sub_date"] ."<br><br>";
}

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.