【问题标题】:PHP PDO SELECT query not showing resultsPHP PDO SELECT查询不显示结果
【发布时间】:2014-01-13 21:07:51
【问题描述】:

我正在 PHP 中运行此 PDO 查询:

$stmt = $pdo_conn->prepare("SELECT * from contacts where email = :email ");
$stmt->execute(array(':email' => $from ));
$contact = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($contact) > 0) {
    echo $contact["email"];
}

但它不回显联系人表中的电子邮件列

我知道那里绝对有一个价值,就好像我在回显“是”一样;在它显示的 if 语句中

我在这里做错了什么?

var_dump($contact);显示

array(1) { [0]=> array(22) { ["sequence"]=> string(3) "266" ["newsletter"]=> string(3) "yes" ["company_sequence"]=> string(3) "278" ["title"]=> string(2) "Mr" ["forename"]=> string(7) "Forename" ["surname"]=> string(4) "Surname" ["email"]=> string(22) "user@domain.com" ["password"]=> string(32) "**********" ["phone"]=> string(0) "" ["mobile"]=> string(11) "00000000000" ["notes"]=> string(0) "" ["contactstatus"]=> string(0) "" ["logintries"]=> string(1) "0" ["dob"]=> string(10) "0000-00-00" ["receive_allticketupdates"]=> string(3) "yes" ["receive_accountsemails"]=> string(3) "yes" ["can_edit_contacts"]=> string(3) "yes" ["view_all_tickets"]=> string(3) "yes" ["receive_orderemails"]=> string(0) "" ["can_login_online"]=> string(3) "yes" ["last_satisfaction_survey_received"]=> string(10) "0000-00-00" ["receive_domainemails"]=> string(0) "" } }

【问题讨论】:

  • 尝试在::fetchAll() 之后运行var_dump($contact);。这将帮助我们找出问题所在。
  • 什么是var_dump($contact)

标签: php mysql sql pdo


【解决方案1】:

因为您使用的是fetchAll(),所以即使您只期望一个结果,您也会收到一个二维数组。

要从中获得您的单一结果,您可以通过 $contact[0] 访问它:

echo $contact[0]['email'];

或者,如果您想要/期望单行,您可以使用fetch() 而不是fetchAll()

$contact = $stmt->fetch(PDO::FETCH_ASSOC);
if(count($contact) > 0) {
    echo $contact["email"];
}

【讨论】:

    【解决方案2】:

    似乎$contact 将包含一个行数组。因此,您需要访问特定行的 email 字段。像这样的:

    echo $contact[0]['email'];
    

    或者使用循环:

    if (!empty($contact)) {
      foreach ($contact as $thisContact) {
        echo $thisContact['email'];
      }
    }
    

    或者,使用fetchAssoc 代替fetchAll

    while ($contact = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo $contact['email'];
    }
    

    【讨论】:

      【解决方案3】:

      fetchAll 获取数组中的所有行,因此结果是一个多维数组。

      您可能正在寻找echo $contact[0]["email"];

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-18
        相关资源
        最近更新 更多