tags:

views:

23

answers:

2

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 />';
}
A: 

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.

Martin Bean
+1  A: 

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.

Alan Orozco