use extract() with query result

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
phpBever
Forum Commoner
Posts: 42
Joined: Fri Aug 07, 2009 10:23 am

use extract() with query result

Post by phpBever »

I'm trying to take the result of my mysqli_query and use extract() to get a set of scalar variables. I've tried things like the following, but can't get anything to work.
$sql = "select field1, field2, field3 from table1 where ID = 'nnnn'";
$res = mysqli_query($mysqli, $sql);
while ($values = mysqli_fetch_assoc($res)) {
extract($values);
//or: $newArray = $values;
extract($newArray);
}

I've also tried creating $newArray inside the while block and doing the extract on $newArray outside the block, but that didn't seem to work either.
I've also made various attempts using 'foreach()'.

All the examples I see do something "simple" like echo or printf. Is what I'm trying to do possible?

I can get results using mysqli_fetch_row(), but this doesn't give an associative array, it seems. And it would be tedious and risky to try to create 10 or more scalar variables from a large select query.

Thanks.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: use extract() with query result

Post by AbraCadaver »

What are you wanting to do? Assuming that your query was successful, you would use:

Code: Select all

$values['field1'], $values['field2'], etc...
With extract(), what does this show:

Code: Select all

while ($values = mysqli_fetch_assoc($res)) {
   echo $values['field1'];
   extract($values);
   echo $field1;
}
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
phpBever
Forum Commoner
Posts: 42
Joined: Fri Aug 07, 2009 10:23 am

Re: use extract() with query result

Post by phpBever »

That's working now. Thanks. I thought I had tried that early on and it wouldn't work. Don't know what I did wrong--probably gremlins.

Thanks again.
Post Reply