1

I'm trying to make a very abstract PDO select function, but for some reason, I'm getting an empty array returned.

function listAllProducts () {
    return select('products', '', '');
} 

function select( $tableName, $property, $value ){
    switch($tableName)
    {
        case "products":
            $tbl = 'products';
            break;
        case "cart":
            $tbl = 'cart';
            break;
    }
    switch($property){
        case "id":
            $property = 'id';
            break;
        case "name":
            $property = 'name';
            break;
    }

    $db = new PDO('mysql:host=localhost;dbname=ecom;charset=utf8', 'root', 'PASSWORD');
    if( strcmp($value, '') != 0 ){ //if $value is not empty
        $query = "SELECT * FROM $tbl WHERE $property = :value";
        $stmt = $db->prepare($query);
        //bind params
        $stmt->bindValue(':value', $value);

    }
    else{
        $query = "SELECT * FROM $tbl";
        $stmt = $db->prepare($query);
    }
    //execute
    try{
        $stmt->execute();
        $result = $stmt->fetchAll();
        return $result;
    }
    catch(Exception $e){
        return $e;
    }
}

Is there something simple I'm missing?

EDIT: Thanks for the help, but after adding a switch and removing table and columns from my bound params, I'm still getting an empty result set :(

EDIT 2: I've found a somewhat convoluted solution, added it above, but it looks like it's working for now! More testing is necessary.

Samuel Hill
  • 176
  • 1
  • 13
  • *"but the function isn't throwing an exception or complaining at all."* - add `$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);` right after the connection is opened, and you'll see it complain. ;) – Funk Forty Niner Oct 03 '14 at 18:33
  • Thanks Fred -ii-! I've added a few things from the link you referenced - however, I'm back to where I started with the empty result set. – Samuel Hill Oct 03 '14 at 18:44
  • You're welcome Samuel. I reopened the question, will see if someone picks up on it now. Remember to keep that link handy about how you can't bind tables and/or columns. If only PDO would let us, but there's a reason for it ;) – Funk Forty Niner Oct 03 '14 at 18:50
  • If you replace `if( strcmp($value, '') != 0 ){ //if $value is not empty` with `if( $value )` code will be much cleaner and comment won't be necessery. – Stanislav Shabalin Oct 03 '14 at 18:57
  • If there're no errors and function still returns an empty array, maybe there're no records in the database? Plenty of things could go wrong theoretically, try debugging "with prints": put `echo $stmt->queryString` (or `error_log $stmt->queryString`) before executing to double check what's going on. – Stanislav Shabalin Oct 03 '14 at 18:59

0 Answers0