Jonathan Thurft
Jonathan Thurft

Reputation: 4173

Simple Select statement is not working using PDO

I am trying to select a user id (uID) just to check if it exists... I am getting stuck at just the most basic select statement...

I've searched and tried different people's code but either my code always returns true (if i dont use fetch) or it says that it is not an object and i cant not use fetch....

$sql = 'SELECT uID FROM ldc_user_details where uID=3';
$q = $this->db->prepare($sql);
$i=$q->execute();

     foreach ($i->fetch() as $key => $val){
      echo 'key='.$key." val =".$val;
     }

ERROR: Call to a member function fetch() on a non-object in /home/pdwdev/public_html/ldc_main.php

Upvotes: 1

Views: 123

Answers (2)

Yousuf Memon
Yousuf Memon

Reputation: 4798

<?php

$sql = 'SELECT uID FROM ldc_user_details where uID=3';

// no need to use prepare() here unless there's a user input

$q = $this->db->query($sql);

// a check for rowCount would be good
if ($q->rowCount() > 0) {

    // all results will be in $i
    $i = $q->fetchAll();

     foreach ($i as $key => $val){

         echo "Key : {$key} <br> Val : {$val}";
     }
}
else {
    die("Zero Results returned");
}

?>

Upvotes: 2

user1726343
user1726343

Reputation:

You need to call fetch on $q, not $i. execute returns a boolean value indicating success or failure.

 if($i){ //indicates whether the query succeeded
     foreach ($q->fetchAll() as $key => $val){
         echo 'key='.$key." val =".$val;
     }
 }

Note that I am using fetchAll to get all rows. fetch will return just one, and advance the pointer to the next row.

Upvotes: 4

Related Questions