views:

32

answers:

1

An example of my scenario is a large setup page for an application, the method I use is for example:

//query 1
$stmt = $dbh->prepare("...");
$stmt->execute();

//query 2
$stmt = $dbh->prepare("...");
$stmt->execute();

Would this be an accepted method to write more queries? I have no clue how it's supposed to be done (or who does what, rather), I assume writing the second $stmt is the most acceptable way, as there is no need to create other variables, am I right?

I really wish to know how people do this sort of thing.. I don't want to release 'ugly' code if I have to.

+3  A: 

Yes, that is perfectly acceptable way to execute queries. No need to create new $stmt objects.

Also, if you ever get the error Lost connection to MySQL server during query when performing multiple queries within a single page, always issue this with the query: This will tell the MySQL driver to use the buffered versions of the MySQL API.

PDO::setAttribute("PDO::MYSQL_ATTR_USE_BUFFERED_QUERY", true);

So that your query looks like:

$db->prepare('select * from tablename', array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
$db->execute();
shamittomar
So I do not need to execute() each query after preparing it (only at the end)? I'm not 100% sure what you mean, because I need to check if the query returns rows for example after each execute.
John
No, you definitely need to `execute()` the query after processing. Otherwise they will not get executed. All I am saying is that IF you get `lost connection` errors THEN you can use the `PDO::MYSQL_ATTR_USE_BUFFERED_QUERY`. I have updated the answer to remove confusion. they way you're currently doing it is fine.
shamittomar
Alright, thank you. I'm confident in my application, it's coming quite well!
John