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.
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.
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']; .
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 )
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With