mysql fetch while,mysql_fetch_array和while循环在php中

I'm trying to get data from DB and print it on the page. I use next select:

$tableIndex=mysql_query('SELECT table_index FROM table_names');

When I use a while loop to print, it's ok.

Code:

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

echo $row[0].'
';}

Result:

1st

2nd

3rd

But without while loop, it gives me just first element of array.

Code:

$row = mysql_fetch_array($tableIndex);

echo $row[0].'
';

echo $row[1].'
';

echo $row[2].'
';

Result:

1st

_

_

(where "_" is blank space)

Can someone expalin why it works so strangely?

解决方案

You're fundamentally misunderstanding how these things work.

The "array" in mysql_fetch_array is not an array of all the records, but an array of the data within the current record.

In your case, you're only fetching a single field, so the array will only contain a single element (ie $row[0]), but the principle is the same -- it's an array of the single record that you have just read.

Only the data for the current record is in the array at any one time. That's what the while loop is for; it goes back any loads each record one after the other.

If you want to create an array that contains all the data, you need to do it like this:

$fullData = array()

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

$fullData[] = $row[0];

}

That will put all the data that you're reading into a single big array, which is what you're expecting. Now you can do what you wanted to do in the question:

echo $fullData[0].'
';

echo $fullData[1].'
';

echo $fullData[2].'
';

Hope that helps.

It's worth pointing out here that the mysql_xxx() family of functions are deprected and considered obsolete. If you're just learning PHP (which would seem to be the case), I strongly recommend that you stop learning these functions, and learn the PDO library instead. It is more modern and has a lot of features that the mysql functions can't provide. In addition, future versions of PHP will remove the mysql functions entirely, so you'll have to switch at some point -- it may as well be now, while you're still learning.

Also (to keep things relevant to the question), the PDO library has a feature that does in fact do what you're looking for in a single function: PDO::fetchAll(). Using this method means that you can fetch all the data into a single big array in one line with no need to do a while loop. The code would look a bit like this:

$sth = $dbh->prepare("SELECT name, colour FROM fruit");

$sth->execute();

$result = $sth->fetchAll();

(example taken from the PHP manual for PDO::fetchAll)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值