简体   繁体   中英

PDO Query not printing anything

I have the following function which enables a query to run with a where condition. But it seems not to be producing any results.

I can connect to the database so that is not an issue.

Any help would be appreciated.

 public function executewhereQuery(Array $tableData, $fieldType, $table, $tableField){

    $dbh = $this->connect();

    try{    
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        /*** fetch into an PDOStatement object ***/
        $stmt = $dbh->prepare("SELECT * FROM ".$table." 
        WHERE ".$tableField." = :fieldValue");

        if($fieldType=='int'){
            $stmt->bindParam(':fieldValue', $fieldValue, PDO::PARAM_INT);
        }
        else{
            $stmt->bindParam(':fieldValue', $fieldValue, PDO::PARAM_STR);   
        }
         $stmt->execute($tableData);

        /*** fetch the results ***/
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return $results;

        /*** close the database connection ***/
        $dbh = null;
    }
    catch(PDOException $e){
        echo $e->getMessage();
    }
} 

I am calling the function using the following:

$mydb = new Dbpdo_Database();


$tableData = Array('fieldValue' =>  1); 

$table = 'news';
$tableField = 'newsID';
$fieldType = 'int';         

$results = $mydb->executewhereQuery($tableData, $fieldType, $table, $tableField);

foreach ($results as $row){
echo $row['newsTitle'].'-'.$row['newsText1'].'<br />';
}

Your problem seems to be that $fieldValue isn't set anywhere. You're passing an associative array that has the fieldValue key.

Also, setting $dbh to null doesn't close the DB connection, it only destroys the PDO instance. And either way, that line wouldn't execute because it follows a return statement.

Try echoing your SQL query to ensure your $table and $tableField variables are as expected. I can't see anything in the above that would cause no results to be returned, other than there's no data in your database matching the specified condition.

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