-5

After this question, what is the best way to get all the values of a single column in a MySQL database?

For instance, all values of:

SELECT Name FROM Customers

Looking for a non-deprecated answer.

Community
  • 1
  • 1
  • 2
    Closing this as a duplicate for now, let's see how resolving it on the original question works, and if it doesn't, return to the solution of a new Q&A. – Madara's Ghost Jan 07 '16 at 09:32
  • 1
    This was maybe a nicer and cleaner [awnser](http://stackoverflow.com/questions/6047724/pdo-fetchall-array-to-one-dimensional) and look for [example 2](http://php.net/manual/en/pdostatement.fetchall.php#example-1055) in php docs – Yoram de Langen Jan 07 '16 at 09:38

2 Answers2

7

Here is a simple way to do this using PDO

$stmt = $pdo->prepare("SELECT Column FROM foo LIMIT 5");
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_UNIQUE | PDO::FETCH_GROUP);
var_dump(array_keys($array));

array(5) {
  [0]=>
  int(7960)
  [1]=>
  int(7972)
  [2]=>
  int(8028)
  [3]=>
  int(8082)
  [4]=>
  int(8233)
}
Daan
  • 12,099
  • 6
  • 34
  • 51
  • What is the purpose of this question and this answer. I am genuinely asking, because I see it was meant to be an FAQ and you have 7 upvotes, but the duplicate target has much better answer of yours. – Dharman Oct 19 '19 at 21:15
  • @Dharman I wrote this new question after a discussion with PHP folks in the php chat about the duplicate link. We were not quite convinced that only writing an answer on the other question were to be sufficient, so we added both a new Q&A and an aswer to the other one. Time apparently prove us wrong. – Félix Adriyel Gagnon-Grenier Oct 19 '19 at 21:46
-3
$link = mysqli_connect($host, $user, $password) or die('DB Server Connection error'.mysqli_error());

mysqli_select_db($link, $database) or die('DB Selection error'.mysqli_error());

$sql = 'SELECT name FROM Customers';

$query = mysqli_query($link, $sql);

if (0 < mysqli_num_rows($query)) {
    while ($data = mysqli_fetch_assoc($query)) {
        $resultArray[] = $data['name'];
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
shalini
  • 1,291
  • 11
  • 13