-2
$sql="select name from exp";    
$n1 = mysql_query($sql);
while ($row=mysql_fetch_array($n1)) {
   $msg[]=$row['name'];
}

echo json_encode($msg);

Please tell me what the mysql_fetch_array($n1) does and what it loops and what value will be assigned to $msg every time it loops.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Nithish Reddy J
  • 155
  • 3
  • 16
  • 4
    If you're new to PHP, I suggest you get acquainted with the [documentation](http://au2.php.net/mysql_fetch_array). Its sole purpose is to answer these exact questions. – Marty Feb 27 '14 at 05:51

3 Answers3

0

$n1 is a mysql resource.

mysql_fetch_array will talk to this resource and return you an array.

Here, as your request selects the "name" field of each line of the mysql table 'exp', the mysql_fetch_array() will return you the array : ["name"=>value] for each line of the table.

Loïc
  • 11,804
  • 1
  • 31
  • 49
0

Not may be the best explanation but anyway:

$sql="select name from exp";    
$n1 = mysql_query($sql);
//$n1 returns the whole result set from your query, this means it contains 
//all the values of 'name' from your table 'exp'

//mysql_fetch_array will retrieve each 'name' from the result set $n1
while ($row=mysql_fetch_array($n1)) {
//$msg is an array, writing [] makes it auto-increment its index
//depending on the order of your records, the first 'name' returned from your 
//table will be assigned to $msg and the second time it loops, the second 'name' 
//will be assigned and so on.
   $msg[]=$row['name'];
//so this will be saved as $msg[0] = 'first name', $msg[1] = 'second name'
//and so on till the end of records
}

echo json_encode($msg);
AyB
  • 11,609
  • 4
  • 32
  • 47
  • the second time it loops,will it be reassigned or will it push the element into $msg.. – Nithish Reddy J Feb 27 '14 at 05:53
  • @NithishReddyJ It will not be reassigned because of the `[]`, it auto-increments to the next array index. Yes, it will push it into `$msg`. – AyB Feb 27 '14 at 05:55
0

this function mysql_fetch_array fetch a row, each time you calling it; it depends on the number of rows returned from the query itself.

this line:

$msg[] = $row["name"];

takes the $row array, which is filled with the row's fields (name is one of them). The fields are determined by query itself ("select name..").

while ($row=mysql_fetch_array($n1)) {

You are actually saying here: as long there are rows to handle, give me the next one. The next one is stored in $row and you handle its fields.

You actually filling an array ($msg) with the field, so the resulting array will be like this:

$msg[0] = "some name";
$msg[1] = "another name";
...
  • could you explain me the diff btwn mysql_fetch_array() and mysql_fetch_row()? – Nithish Reddy J Feb 27 '14 at 06:03
  • [here](http://stackoverflow.com/questions/11480129/mysql-fetch-row-vs-mysql-fetch-assoc-vs-mysql-fetch-array) you can find some nice explanation –  Feb 27 '14 at 06:05