0

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.

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

2 Comments

My database connection is though mysqli, don't think it will work with PDO. BTW, is PDO faster or smth? I noticed that mysqli is most used.
PDO is saner. If your connection is mysqli you can use safeMysql as its built upon mysqli

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.