Page 1 of 1

use extract() with query result

Posted: Tue Jun 01, 2010 2:48 pm
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.

Re: use extract() with query result

Posted: Tue Jun 01, 2010 2:57 pm
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;
}

Re: use extract() with query result

Posted: Tue Jun 01, 2010 4:14 pm
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.