$sql="select name from exp";
$n1 = mysql_query($sql);
while ($row=mysql_fetch_array($n1)) {
$msg[]=$row['name'];
}
echo json_encode($msg);
請告訴我是什麼mysql_fetch_array($n1)
做什麼它循環,什麼價值將被分配到每一次$msg
它循環。
$sql="select name from exp";
$n1 = mysql_query($sql);
while ($row=mysql_fetch_array($n1)) {
$msg[]=$row['name'];
}
echo json_encode($msg);
請告訴我是什麼mysql_fetch_array($n1)
做什麼它循環,什麼價值將被分配到每一次$msg
它循環。
此功能mysql_fetch_array讀取行,每次調用它的時間;它取決於查詢本身返回的行數。
這一行:
$msg[] = $row["name"];
會從$排陣,這是充滿了該行的領域(name
是其中之一)。 這些字段由查詢本身決定("select name.."
)。
while ($row=mysql_fetch_array($n1)) {
你實際上是說在這裏:as long there are rows to handle, give me the next one
。 下一個存儲在$row
中,您處理其字段。
你居然填充領域的陣列($msg
),因此產生的陣列將是這樣的:
$msg[0] = "some name";
$msg[1] = "another name";
...
你能解釋我的差異btwn mysql_fetch_array()和mysql_fetch_row()? –
[here](http://stackoverflow.com/questions/11480129/mysql-fetch-row-vs-mysql-fetch-assoc-vs-mysql-fetch-array)你可以找到一些很好的解釋 – 2014-02-27 06:05:46
$ n1是一個mysql資源。
mysql_fetch_array將與此資源交談並返回數組。
這裏,當您的請求選擇mysql表'exp'每行的「name」字段時,mysql_fetch_array()將返回數組:表中每行的[「name」=> value] 。
沒有可能是最好的解釋,但無論如何:
$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);
它第二次循環,它會被重新分配或將它推入$味精。 –
@NithishReddyJ它不會被重新分配,因爲'[]',它會自動增加到下一個數組索引。是的,它會將它推入'$ msg'。 –
如果你是新來的PHP,我建議你用[文件]熟悉( http://au2.php.net/mysql_fetch_array)。其唯一目的是回答這些確切的問題。 – Marty