简体   繁体   中英

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

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.

<?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");
}

?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM