【问题标题】:How to get single column values using MySQLi?如何使用 MySQLi 获取单列值?
【发布时间】:2015-08-26 00:34:42
【问题描述】:

我正在尝试从 MySQL 数据库中获取一维数组中的列表或电子邮件。 但是,我得到的是多维数组,而不是数组:

$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" }

【问题讨论】:

    标签: php mysql arrays mysqli


    【解决方案1】:

    fetch_assoc

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

    【讨论】:

    • fetch_assoc 在这里是多余的,你需要知道确切的列名。使用 fetch_row 它更简单、更短并且普遍适用于任何查询
    【解决方案2】:

    上面的答案是正确的,但这里有一个示例,对您当前的源代码进行了最少的代码修改。

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

    现在$rows 将是一个包含电子邮件地址的一维数组。

    【讨论】:

      【解决方案3】:

      我会推荐以下三个选项之一:

      1. 您可以使用 foreach 并将您需要的列插入到新数组中。

        foreach ($result as $row) {
            $emailAddresses[] = $row['EmailAddress'];
        }
        
      2. 您可以将fetch_all()array_column() 一起使用

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

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

      【讨论】:

        【解决方案4】:

        在循环的这一点上,您可以访问您正在谈论的简单数组。

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

        因此,如果您想对该数组执行任何操作,请将其分配给某个变量或使用该数组调用函数,如下所示:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-12-17
          • 2013-12-06
          • 2013-03-28
          • 2011-07-31
          • 1970-01-01
          • 2017-06-18
          • 2011-03-27
          • 1970-01-01
          相关资源
          最近更新 更多