How to get single column values using MySQLi?

孤街醉人 提交于 2021-02-13 05:44:08

问题


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) "abc@abc.com" } [1]=> array(1) { [0]=> string(17) "hello@gmail.com" } }
//This is how array should be
$MyV = array("abc@abc.com", "hello@gmail.com");
var_dump($MyV); //this is an array I need to have: array(2) { [0]=> string(11) "Abc@abc.com" [1]=> string(11) "hello@g.com" }

回答1:


do fetch_assoc

while($row = $result->fetch_assoc()) {
  $rows[]=$row['EmailAddress'];
}



回答2:


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);
}



回答3:


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.




回答4:


You could also use foreach and save just the single column into a new array.

foreach ($result as $row) {
    $rows[] = $row['EmailAddress'];
}


来源:https://stackoverflow.com/questions/30761740/how-to-get-single-column-values-using-mysqli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!