Jump to content

Querying with PDOStatement


arenaninja

Recommended Posts

Hey all. I'm using this sort of thing to query with my application:

        try
        {
            $stmt = $this->db->prepare($sql);
            /* Bind parameter if id was passed, ensure it's of integer type */
            if(!empty($id))
            {
                $stmt->bindParam(":id", $id, PDO::PARAM_INT);
            }
            $stmt->execute();
            $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $stmt->closeCursor();

            return $results;           
        }
        catch(Exception $e)
        {
            die($e->getMessage());
        }

which has been working out great, with the only annoyance that sometimes, I need to run a query and I know I'm supposed to get only one row. However, I have to access associated elements via $results[0]['fieldName']. How do I run a query to return exactly one result so I can just use $results['fieldName']?

Link to comment
Share on other sites

Or try the object oriented approach:

 

try
{
$stmt = $conn->prepare($sql);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_OBJ);
$stmt->closeCursor(); 
}
catch(Exception $e)
{
die($e->getMessage());
}

You can easily access it like so:

 

echo $results->field_name;

Link to comment
Share on other sites

oooo much appreciated. Any upside to using the object oriented approach? So far I like having to differ between an array and an object in my application, it reminds me I'm still dealing with MySQL. It seems like less of a pain to keep track of quotation marks, but honestly I think I'll stick to fetch() for now. Many thanks to you both!

Link to comment
Share on other sites

Well object oriented programming is where the future is headed, so mines well start now =]. But yeah there are some upsides to it, besides it being easier to type, you can do some cool things with it like load data directly into a class for direct manipulation. If you ever get curious, take a look here: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.