Wrap PDO execution code?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Shaun
Forum Newbie
Posts: 1
Joined: Sun Dec 29, 2013 2:05 pm

Wrap PDO execution code?

Post by Shaun »

Hi,

Is it possible to do something like this:
function runPDO($sql){

Code: Select all

                $stmt = $dbh->prepare($sql);
                $stmt->execute();
                $arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $row = $stmt->fetch();
}

in a function and pass the sql statements in as needed? It isn't working. I wish to run $arrValues and $row in a loop so I can put the values in a table but it doesn't work. This code works fine outside a function.

I connect to the database in a seperate file that is included in the page. I believe it is a scope issue.

Perhaps there is another way to run queries without repeating the PDO code over and over?

Thanks
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Wrap PDO execution code?

Post by Celauran »

"It doesn't work" is not helpful. What's happening? Or not happening?

I agree scope seems to be part of the problem; you're referencing $dbh, which doesn't appear to exist.
Post Reply