1

I am trying to get list or emails in a one-dimensional array from MySQL database. However, I am getting multidimensional array, rather then array:

$query = "SELECT DISTINCT `EmailAddress` FROM `Emails` WHERE `JobID` = 1";
$result = $conn->query($query);
if (!$result) {
    printf("Query failed: %s\n", $mysqli->error);
    exit;
}
while ($row = $result->fetch_row()) {
    $rows[] = $row;
}
$result->close();
$conn->close();
var_dump($rows); // This will return array(2) { [0]=> array(1) { [0]=> string(24) "[email protected]" } [1]=> array(1) { [0]=> string(17) "[email protected]" } }
//This is how array should be
$MyV = array("[email protected]", "[email protected]");
var_dump($MyV); //this is an array I need to have: array(2) { [0]=> string(11) "[email protected]" [1]=> string(11) "[email protected]" }
0

4 Answers 4

5

do fetch_assoc

while($row = $result->fetch_assoc()) {
  $rows[]=$row['EmailAddress'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

fetch_assoc is rather superfluous here, you need to know the exact column name. with fetch_row it's simpler, shorter and universally applicable to any query
5

The answers above are correct, but here's an example with minimum code modifications to your current source.

while($row = $result->fetch_row()) {
  $rows[]=$row[0];
}

Now $rows will be a one dimensional array populated with email addresses.

Comments

2

I would recommend one of the following three options:

  1. You could use foreach and insert just the column you need into a new array.

    foreach ($result as $row) {
        $emailAddresses[] = $row['EmailAddress'];
    }
    
  2. You can use fetch_all() with array_column()

    $emailAddresses = array_column($result->fetch_all(MYSQLI_ASSOC), 'EmailAddress');
    
  3. Using fetch_column():

    while($email = $result->fetch_column()) {
        $emailAddresses[] = $email;
    }
    

Comments

0

At this point in your loop, you have access to the simple array you are talking about.

while($row = $result->fetch_row()) {
  $rows[]=$row;
}

So if you want to do anything with that array assign it to some variable or call a function with the array, something like this:

while($row = $result->fetch_row()) {
    doSomethingFun($row);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.