为什么你不应该使用 mysql_fetch_assoc 超过 1 次?
有人说你不应该多次使用mysql_fetch_assoc
,为什么呢?
例如:我想显示两个表,一个包含已付费会员的用户,另一个包含未付费会员的用户,因此我不是查询数据库两次,而是查询一次并获取两种类型的 $result
变量用户,然后我运行循环 mysql_fetch_assoc
并查看 list['membership'] = 'paid'
然后 echo ...
第二次循环 mysql_fetch_assoc
code> 并查看是否 list['membership'] = 'free'
然后 echo ...
考虑到注册和未注册的用户数量大约相同,什么使用更少的资源。
Some people say you should not use mysql_fetch_assoc
more than one time, why is that?
e.g.: I want to display two tables one with users who paid for membership, other with users who did not, so instead of querying database 2 times I query it one time and get $result
variable with both types of users then I run loop mysql_fetch_assoc
and see if list['membership'] = 'paid'
then echo ...
Second time I loop loop mysql_fetch_assoc
and see if list['membership'] = 'free'
then echo ...
What uses less resources considering I got about equal amount of users who registered and unregistered.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
将查询结果集视为一根香肠,将 mysql_fetch_assoc() 视为一把切下香肠的刀。每次你取一排香肠时,就会切下另一块香肠,而且它总是一块新香肠。你不能去切掉之前切过的一块,因为它已经被吃掉了。
Think of your query result set as a sausage, and mysql_fetch_assoc() as a knife that slices off a piece of that sausage. Every time you fetch a row, another piece of sausage is cut off, and it's always a NEW piece of sausage. You can't go and cut off a previously cut piece, because it's been eaten already.
由 Typer85 引用(链接):
Quote by Typer85 (link):
当有人说你不能调用
mysql_fetch_assoc()
两次,它们意味着针对相同的资源。您传递给mysql_fetch_assoc()
的资源结果是通过引用完成的。在再次使用 mysql_fetch_assoc() 之前,您需要重置指针的位置。编辑:为此,请尝试使用
mysql_data_seek()
。
When someone says you can't call
mysql_fetch_assoc()
twice, they mean against the same resource. The resource result you pass in tomysql_fetch_assoc()
is done by reference. You'll need to reset the position of the pointer before you can usemysql_fetch_assoc()
a second time.EDIT: And to do so, try using
mysql_data_seek()
.看来您想要做的是将查询结果视为数组(字段)的数组(行)。但这并不是 mysql 库真正提供的。事实上,我经常做的是将行复制到数组数组中(只需在 mysql_fetch 上循环直到为空),然后使用 PHP 为此目的提供的数组函数对我自己的行集执行我想要的操作。这也最大限度地减少了表被锁定的时间。
It appears that what you want to do is to treat the query result as an array (rows) of arrays(fields). But that's not really what the mysql library provides. What I will often do is in fact copy the rows into an array of arrays (just loop on mysql_fetch until empty) and then do what I want with my own rowset using array functions that PHP provides for the purpose. This also minimizes the amount of time the table is locked.