0

I've been trying to simplify my php code and am having difficulty figuring out why my php function does not work as designed:

In this case I am experimenting with a Karaoke Catalog's artist database: $db = a PDO connection, and $ta is an Artist table.

The function:

function getRow($q, $pr = []){
    $stmt = $db->prepare($q);
    $stmt->execute($pr);
    return $stmt->fetch(PDO::FETCH_OBJ);
}

Call:

$st = getRow("SELECT * FROM $ta WHERE id=?" , ["313"]);

When I run this code I get an error message that there is an illegal call of the prepare function on a non-object.

Interestingly, when I reformat my code a bit it works, but I don't understand why it does not work as above.

Working code:

function getRow($q, $pr = []){
    $stmt = ($q);
    $stmt->execute($pr);
    return $stmt->fetch(PDO::FETCH_OBJ);
}

Working call:

$st = getRow($db->prepare("SELECT * FROM $ta WHERE id=?"), ["313"]);
echo $st->prefix.' '.$st->fname.' '.$st->artist.'<br>';

using local server: Ampps and PHP 5.5

Oh, Artist record 313 happens to be: Billy Joel. :) Any thoughts would be appreciated.

Qirel
  • 25,449
  • 7
  • 45
  • 62

0 Answers0