user2710234
user2710234

Reputation: 3225

PHP PDO SELECT query not showing results

i am running this PDO Query in PHP:

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

but its not echoing the email column from the contacts table

i know there is defiantly a value there as if i do echo 'yes'; inside the if statement it shows

what have i done wrong here?

var_dump($contact); shows

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) "[email protected]" ["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) "" } }

Upvotes: 0

Views: 281

Answers (3)

newfurniturey
newfurniturey

Reputation: 38456

Because you're using fetchAll(), you're receiving a 2-dimensional array of results even when you expect just one.

To get your single result from this, you can access it via $contact[0] instead:

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

Alternatively, if you want/expect a single row, you can use fetch() instead of fetchAll():

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

Upvotes: 1

jeroen
jeroen

Reputation: 91792

fetchAll fetches all rows in an array, so the result a multi-dimensional array.

You are probably looking for echo $contact[0]["email"];.

Upvotes: 0

showdev
showdev

Reputation: 29188

It seems that $contact will contain an array of rows. So you'll need to access the email field of a particular row. Something like this:

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

Or use a loop:

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

Or, using fetchAssoc instead of fetchAll:

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

Upvotes: 1

Related Questions