PHP 1-liner each () with mysql_fetch_assoc ()

An attempt to create a 1-liner to execute the mysql result set.

Example:

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

the problem is that joining in a loop like this:

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

returns an a la error each()without receiving an object or array, although of course it is. I think the problem is casting, but it doesn't seem to be that way:

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

Any ideas? I like to code as short as possible, and when " $q = mysql_fetch_assoc($r->result)" everywhere annoys me, it already does.

Continue publishing ...

Thank!

+3
source share
3 answers
$_SESSION['usr'] = mysql_fetch_assoc($r->result);

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

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

PDO:

$query->fetchAll();

MySQLi /.

+3

mysql_fetch_assoc while:

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

Source: https://habr.com/ru/post/1745651/


All Articles