PHP将所有行作为数组获取

im trying to grab all the row values from a database column like this:

$products = mysqli_fetch_assoc(mysqli_query($con,"SELECT product_id FROM am_product"));
print_r($products);

expecting to get something like if i do this:

$products = array(1,2,3,4,5) 

in the first place so i can use it in other functions. But instead i only get this: Array ( [product_id] => 1 ).

How can i get all the values and not only the first one?

Thank you.

In your post: $products should be renamed to $product to better understand your code and to understand your problem. fetch_assoc() only returns ONE element and increases a 'pointer'. Upon reaching the end of a list the function will return false. Thats why you mostly use while(fetch_assoc()) for this purpose.

Maybe this will help:

$entries = array();
while($entry = $result->fetch_assoc()) {
    foreach($entry as $key => $value) $entries[$i][$key] = $value;
    $i++;
}

You can use mysqli_fetch_all() together with array_values():

$productIds = array_values(mysqli_fetch_all($result));

__

Update:

It seems like you have a PHP version < 5.3 installed. Versions < 5.3 don't have mysqli_fetch_all(). You have to following alternatives:

  • If you have PHP >= 5.1, you can use PDO. PDOStatement has a method fetchAll()
  • If you don't have PHP >= 5.1 (why?) or you can't/won't use PDO you need to loop over the result set...

... like this:

$productIds = array();
while($product = mysqli_fetch_array($result, MYSQLI_NUM)) {
    $productIds []= $product[0];    
}

mysqli_fetch_assoc will only fetch the first row. To keep fetching until you have exhausted all the rows, use mysqli_fetch_assoc inside a while loop.

To fetch the first column of all rows:

$products = array_map('current', mysqli_fetch_all($result));

If you have many rows, it would be more memory friendly to pick the first column of each row while you iterate over the result set. Also, in < 5.3 you can't use mysqli_fetch_all():

$result = mysqli_query($con,"SELECT product_id FROM am_product");
// assuming $result is fine
$products = array();
while (($row = mysqli_fetch_array($result, MYSQLI_NUM)) !== null) {
    $products[] = $row[0];
}