John
John

Reputation: 3318

PHP/PDO: style of write many queries on one page?

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.

Upvotes: 1

Views: 802

Answers (1)

shamittomar
shamittomar

Reputation: 46692

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();

Upvotes: 3

Related Questions