4

So today, I'm finally making the transition from standard PHP MySQL functions to PDO. I noticed when fetching data as an object, we must run a line similar to the following:

$STH = $DBH->query('SELECT name, addr, city from folks');
$STH->setFetchMode(PDO::FETCH_OBJ);

$result = $STH->fetch();

My question is regarding line 2. Is there a way to set this as the default behavior so that we don't need to set the fetch mode every single time we wish to run a query? This seems pretty annoying to me. Surely it's not necessary to do this?

1

1 Answer 1

8

You can set the default fetch mode for the PDO object:

$DBH->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

This, of course, you do as soon as you've initialized your $DBH (PDO) object.

(For detailed documentation on this, see http://www.php.net/manual/de/pdo.setattribute.php)

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for, thanks! I'll accept this answer as soon as I can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.