0

This way the while loop works fine:

$results = mysqli_query($dbcon, "SELECT `name`, `date` FROM `table1` WHERE `user` = $user_id);

while($data = mysqli_fetch_array($results)) {
    echo '<tr>
        <td>' . $data['name'] . '</td>
        <td>' . $data['date'] . '</td>
        </tr>'
}

However it does not want to work with user-defined function. It's just looping first row infinitely:

function camp_data() {
    global $user_id;
    $query = mysqli_query($dbcon, "SELECT `name`, `date` FROM `table1` WHERE `user` = $user_id");
    return (mysqli_fetch_array($query));
}

while($data = camp_data()) {
    echo '<tr>
        <td>' . $data['name'] . '</td>
        <td>' . $data['date'] . '</td>
        </tr>'
}

When I do print_r(mysqli_fetch_array($results)) and print_r(camp_data()) - both return absolutely identical array. What is wrong here?

2
  • Syntax higligher shows some syntax error !! Commented Feb 26, 2014 at 12:38
  • check $dbcon if its available inside the function !! Commented Feb 26, 2014 at 12:39

2 Answers 2

4

No matter how much times you are calling the function externally, it will perform mysqli_fetch_array() only on the first row. Calling the function second time (on the second iteration in the external loop) will not know that it was executed before and will not proceed to the next row. Also looping with while on array is not the best choice you can have, it may result to an infinite loop.

You have to loop through the results in your function and build an array of them. Returning mysqli_fetch_array, is not looping.

while($data = mysqli_fetch_array($results)) {
    $rows[] = $data;
}
return $rows

And then perform foreach() on your function:

foreach (camp_data() as $data) {
   echo '<tr>
    <td>' . $data['name'] . '</td>
    <td>' . $data['date'] . '</td>
    </tr>'
}
Sign up to request clarification or add additional context in comments.

Comments

0

in each interation you call all code in camp_data(), not just last line, so refactor it:

function camp_data($query) {
    return (mysqli_fetch_array($query));
}

//execute query only once
$query = mysqli_query($dbcon, "SELECT `name`, `date` FROM `table1` WHERE `user` = $user_id");

//fetch result row by row
while($data = camp_data($query)) {
    echo '<tr>
        <td>' . $data['name'] . '</td>
        <td>' . $data['date'] . '</td>
        </tr>'
}

as you see method camp_data in this case is only simple wrapper for mysqli_fetch_array, so it can be replaced by mysqli_fetch_array

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.