obinoob
obinoob

Reputation: 657

Creating an array from query?

Is there a proper way to do this:

$i = 0;

while($row = mysql_fetch_array($queryResult)){
    $queryArray[$i] = $row['instructionValue'];
    $i++;
}

Upvotes: 2

Views: 115

Answers (3)

lonesomeday
lonesomeday

Reputation: 237865

There is no built-in functionality to do this with mySQL, but it is trivial if you move to using the PDO abstraction layer (which I would strongly advise you to do -- it's brilliant).

For instance:

$dbh = new PDO($dsn, $user, $pass);

$stmt = $dbh->prepare('SELECT name FROM user');
$stmt->execute();

$result = $stmt->fetchAll();

$result is now an array containing all the rows found in the query.

Upvotes: 3

dynamic
dynamic

Reputation: 48101

while($row = mysql_fetch_assoc($queryResult)){
    $queryArray[$i] = $row;
    $i++;
}

Changing $row['instructionValue']; to just $row You will get an $array with all records.

in the while i used mysql_fetch_assoc.

Note you can get rid of the $i by doing just $queryArray[]=$row;

Upvotes: 0

Doug
Doug

Reputation: 6442

You can replace

$queryArray[$i] = $row['instructionValue'];

with

$queryArray[] = $row['instructionValue'];

and get rid of the $i variable.

When you assign a value to an array this way (with braces, but no index) you automatically create a new item at the end of array and assign the value to it.

Upvotes: 3

Related Questions