I’m trying to figure out best practices for running multiple SQL queries using PDO in a single script. The database connection is made at the beginning of the script, but then I need to make multiple different queries. What I’m doing currently (which I’m not sure is best practice) is:
$db = new PDO('mysql:host='.$DBHOST.';dbname='.$DBNAME.';charset=UTF-8', $DBUSER, $DBPASSWORD);
$query = $db->prepare("SELECT count(*) as total from bande_ips WHERE ip=:ip");
$query->bindValue(':ip', $_SESSION['REMOTE_ADDR'], PDO::PARAM_STR);
$query->execute();
$array = $query->fetchAll(PDO::FETCH_ASSOC);
$query = NULL;
$query = $db->prepare("SELECT * from failed_login WHERE IP=:ip and email=:email");
$query->bindValue(':ip', $_SESSION['REMOTE_ADDR'], PDO::PARAM_STR);
$query->bindValue(':email', $email, PDO::PARAM_STR);
$query->execute();
$array = $query->fetchAll(PDO::FETCH_ASSOC);
as you can see i prepare two seperate queries in a single script. But I started setting $query = NULL; as the script was confusing the seperate queries beforehand (it was expecting parameters of an old query which i was no longer calling, which led me to this uncertainty of this being best practices or not.)
I just want to confirm this is best practice before I continue migrating to PDO.
This is the problem with your program flow in some other code. Most likely run in a loop.
As for the code you posted here, there is no need to set
$queryintoNULL– it will be overwritten by the next line anyway.Please note that valid charset for mysql is
utf8, notutf-8