Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get all values in a column using PHP?

Tags:

arrays

php

mysql

I've been searching for this everywhere, but still can't find a solution: How do I get all the values from a mySQL column and store them in an array?

For eg: Table Name: Customers Column names: ID, Name # of rows: 5

I want to get an array of all the 5 names in this table. How do I go about doing that? I am using PHP, and I was trying to just:

SELECT names FROM Customers 

and then use the

mysql_fetch_array 

PHP function to store those values in an array.

like image 560
Gbert90 Avatar asked Mar 08 '11 07:03

Gbert90


People also ask

How can I fetch all data from a table in PHP?

The fetch_all() / mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both.

How can I get column sum in MySQL using PHP?

like this $sum= mysql_query("SELECT SUM(Value) FROM Codes"); with this i get Resource id #10 but not the sum of all values. Try $result = mysql_query('SELECT SUM(value) AS value_sum FROM codes'); $row = mysql_fetch_assoc($result); $sum = $row['value_sum']; .


2 Answers

Here is a simple way to do this using either PDO or mysqli

$stmt = $pdo->prepare("SELECT Column FROM foo"); // careful, without a LIMIT this can take long if your table is huge $stmt->execute(); $array = $stmt->fetchAll(PDO::FETCH_COLUMN); print_r($array); 

or, using mysqli

$stmt = $mysqli->prepare("SELECT Column FROM foo"); $stmt->execute(); $array = []; foreach ($stmt->get_result() as $row) {     $array[] = $row['column']; } print_r($array); 

Array (     [0] => 7960     [1] => 7972     [2] => 8028     [3] => 8082     [4] => 8233 ) 
like image 85
Félix Adriyel Gagnon-Grenier Avatar answered Sep 29 '22 19:09

Félix Adriyel Gagnon-Grenier


Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.


This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php

$result = mysql_query("SELECT names FROM Customers"); $storeArray = Array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {     $storeArray[] =  $row['names'];   } // now $storeArray will have all the names. 
like image 27
DhruvPathak Avatar answered Sep 29 '22 19:09

DhruvPathak