0
$q = "SELECT * FROM user";
$res = mysqli_query($conn, $q) or die(mysql_error());
$userList = "";
while($user = mysqli_fetch_array($res))
{
    $userList .= $user['userList'].";;";
}
echo $userList;

I don't understand the while part:

  1. Why assign the mysqli_fetch_array to $user using while?
  2. How can the $user have index of userList?
  3. Why concatenate with ;;?
1
  • Do you have a problem or are you just asking how this works? Commented Nov 23, 2013 at 1:01

1 Answer 1

3

To answer your questions:

i) mysqli_fetch_array() has two possible return values. It either returns an array of the current row that the database result set pointer points to, then advances the pointer to the next row, or it returns false if you have reached the end of the result set. The while() evaluates the value that is set to $row either continuing the loop if it is an array or stopping the loop if $row equals false

ii) The $user array has both numerical indexes for each field (i.e. 0,1,2,... [#fields - 1]) and associative indexes of the column names for the table (i.e. 'field1', 'field2', etc.). In this case one of the fields in the database is userList, so accessing $user['userList'] returns that column value for the row being worked with. BNote that the query itself would have beeter been written as SELECT userList FROM user since that is the only field you are interested in. There is no reason whatsoever to select and transfer all field data if you have no need for it. It is also rarely useful to use just mysqli_fetch_array(), as you rarely need both numerical and associative indexes on the record.It is usually best to specifically request ther associative or numerical array result depending on which you need.

iii) This code is simply building a string rather than an array of results which might be more common. For whatever reason the code writer decided values in the string should be separated by ;;.

Sign up to request clarification or add additional context in comments.

3 Comments

ii) is interesting, the query of select * made the confusion. what if I use select userList? what should be in the while loop?
@CybalRankine The while loop would not change at all.
I'm mean while($user = mysqli_fetch_array($res)) { // this $userList .= $user['userList'].";;"; }

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.