user3140607
user3140607

Reputation: 303

Trying to get 1 array of strings from a database column with mysqli

I am trying to get all the values from a column with mysqli. I have tried

$emaildbs = $db->query("SELECT email from subscribers");
while($emaildbsrow = $emaildbs->fetch_row()) {
  $emaildbsrows[] = $emaildbsrow;
}
var_dump($emaildbsrows);

but the var_dump looks like this:

array(2) {
  [0]=>
  array(1) {
    [0]=>
    string(6) "asdasd"
  }
  [1]=>
  array(1) {
   [0]=>
   string(1) "s"
  }
}

and the expected output is

array(2) {
  [0]=> string(6) "asdasd"
  [1]=> string(1) "s"
}

I have also tried:

with fetch_assoc and I get smth similar. I searched on stackoverflow, and tried numerous functions instead of fetch_row but same thing. Where am I mistaking.

Upvotes: 0

Views: 43

Answers (3)

Your Common Sense
Your Common Sense

Reputation: 157870

You should use abstraction libraries instead of raw mysqli, such as PDO

$sql = "SELECT email from subscribers";
$emails = $pdo->query($sql)->fetchAll(PDO::FETCH_COLUMN, 0));

or safeMysql

$emails = $db->getCol("SELECT email from subscribers");

the purpose of an abstraction library is to get rid of all the dirty job, making your code cleaner and more readable. See - everything can be done in one single line, making your code four times shorter. Assuming 20 queries per page in average it can save you 60 lines of code.

However, to tell you truth, I don't believe myself you would follow this suggestion. According to my observations, PHP users rather inclined to writing as much code as possible, producing screens of code out of every trifle operation.

Upvotes: 1

Fluffeh
Fluffeh

Reputation: 33512

Each row is an array itself - but as you are selecting a single column, it is a single index array.

You might want to do the following instead:

$emaildbs = $db->query("SELECT email from subscribers");
while($emaildbsrow = $emaildbs->fetch_row()) {
  $emaildbsrows[] = $emaildbsrow[0];
}
var_dump($emaildbsrows);

This will add the single element from the array as a new element in $emaildbsrows. As you are only selecting a single column from the table, this will work nicely. Had you selected more than one column, this wouldn't work.

Upvotes: 1

Rikesh
Rikesh

Reputation: 26421

You're assigning complete row to $emaildbsrows array so just change it to,

$emaildbs = $db->query("SELECT email from subscribers");
while($emaildbsrow = $emaildbs->fetch_row()) {
  $emaildbsrows[] = $emaildbsrow[0];
}
var_dump($emaildbsrows);

Upvotes: 1

Related Questions