Andy Ibanez
Andy Ibanez

Reputation: 12254

Fetching Database Records With PDO's Prepared Statements

I was using this code to fetch records from a database before:

function shapp_get_sections_with_company_id($db, $id)
{
    try
    {
        $que = $db -> query("SELECT * FROM company_sections WHERE company_id = '$id'");
        $result = $que -> fetchAll(PDO::FETCH_ASSOC);
        return $result;
    }catch(PDOException $ex)
    {
        echo $ex -> getMessage();
    }
}

It was working fine. It did its job.

But I'm trying to adapt it to use prepared statements instead.

I have modified the code to this, but I'm not having any luck. Apparently this returns an empty result set:

function shapp_get_sections_with_company_id($db, $id)
{
    try
    {
        $que = $db -> prepare("SELECT * FROM company_sections WHERE company_id = '?'");
        $que -> execute(array($id));
        $result = $que -> fetchAll(PDO::FETCH_ASSOC);
        return $result;
    }catch(PDOException $ex)
    {
        echo $ex -> getMessage();
    }
}

I have also tried returning "$que -> execute(...)" but it wasn't returning a result set. Can I get any help to make this work with prepared statements, please?

Upvotes: 0

Views: 81

Answers (1)

KGolding
KGolding

Reputation: 380

Remove the single quotes from the '?' in the prepare call

$que = $db -> prepare("SELECT * FROM company_sections WHERE company_id = ?");

Upvotes: 1

Related Questions