开发者

PHP 1-liner each() with mysql_fetch_assoc()

Trying to create a 1-liner to loop through a mysql result set.

Example:

$sql = "SELECT uid, role FROM usr WHERE uid = '$this->uid'";
$r = db::q($sql);
if($r->rows()) {
  $q = mysql_fetc开发者_StackOverflow中文版h_assoc($r->result);
  while(list($k, $v) = each($q)) { // would like to omit line above and consolidate here
    $_SESSION['usr'][$k] = $this->$k = $v;
  }
}

problem is that consolidating while loop like so:

while(list($k, $v) = each(mysql_fetch_assoc($r->result))

returns an error a la each() not getting object or array, even though of course it is. I think the problem is a casting issue, but it does not seem you can do:

each( (array) mysql_fetch_assoc($r->result))

Any ideas? I like to code as tersely as possible, and having "$q = mysql_fetch_assoc($r->result)" everywhere will annoy me, does already.

Keep posted...

Thanks!


Do yourself a favor and use PDO:

$query->fetchAll();

MySQLi also has a similar method / function.


You could make the mysql_fetch_assoc call part of your while condition:

while (($q = mysql_fetch_assoc($r->result)) && list($k, $v) = each($q)) {
    $_SESSION['usr'][$k] = $this->$k = $v;
}


$_SESSION['usr'] = mysql_fetch_assoc($r->result);

or ( if $_SESSION['usr'] already contains some elements with other keys you want to keep)

$_SESSION['usr'] = array_merge($_SESSION['usr'], mysql_fetch_assoc($r->result));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜