PHP mySQL查询将单个字段作为2元素数组返回

时间:2022-01-13 03:35:51

I'm using a mySQL statement in a PHP script to return the email address for a given user. You'll see the function below:

我在PHP脚本中使用mySQL语句来返回给定用户的电子邮件地址。你会看到下面的功能:

    public static function getEmailAddress($username) {
    $conn = parent::connect();
    $sql = "SELECT emailAddress FROM " . TBL_USERS . " WHERE username = '". $username ."';";

    try {
        $st = $conn->prepare($sql);
        $st->bindValue("username", $username, PDO::PARAM_STR);
        $st->execute();
        $emailAddress = $st->fetch();
        return $emailAddress;
        parent::disconnect($conn);
    } catch(PDOException $e) {
        die("emailAddress lookup query failed: " . $e->getMessage());
    }
}

This returned an array with two elements, both being the correct email address. I changed the return statement to

这返回了一个包含两个元素的数组,它们都是正确的电子邮件地址。我将return语句更改为

    return implode(array_unique($emailAddress)); 
which solved the problem, but there has to be a better way to do this. This seems like pretty elementary stuff, and I'd like to do it right. What's wrong?

1 个解决方案

#1


0  

The problem is that the default response type of fetch is

问题是fetch的默认响应类型是

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

PDO :: FETCH_BOTH(默认值):返回由结果集中返回的列名和0索引列号索引的数组

I also find this quite confusing.

我也觉得这很令人困惑。

Specify the parameter fetch_style to either PDO::FETCH_ASSOC or PDO::FETCH_OBJ to get what you would expect.

将参数fetch_style指定为PDO :: FETCH_ASSOC或PDO :: FETCH_OBJ以获得您期望的结果。

http://php.net/manual/en/pdostatement.fetch.php

http://php.net/manual/en/pdostatement.fetch.php

Hope this helps

希望这可以帮助

#1


0  

The problem is that the default response type of fetch is

问题是fetch的默认响应类型是

PDO::FETCH_BOTH (default): returns an array indexed by both column name and 0-indexed column number as returned in your result set

PDO :: FETCH_BOTH(默认值):返回由结果集中返回的列名和0索引列号索引的数组

I also find this quite confusing.

我也觉得这很令人困惑。

Specify the parameter fetch_style to either PDO::FETCH_ASSOC or PDO::FETCH_OBJ to get what you would expect.

将参数fetch_style指定为PDO :: FETCH_ASSOC或PDO :: FETCH_OBJ以获得您期望的结果。

http://php.net/manual/en/pdostatement.fetch.php

http://php.net/manual/en/pdostatement.fetch.php

Hope this helps

希望这可以帮助