php - PDO can I reuse the same Statement Handle for multiple queries? -
i using pdo access data base , looping using 2 while loops fetch @ same time, seen below:
$dbh = new pdo('mysql:host=localhost;dbname=database;charset=utf8',$dblogin,$dbpass); $sql = 'select * table'; $sth = $dbh->prepare($sql); $sth->execute(); while ($bm_table = $sth->fetch(pdo::fetch_assoc)) { //sql query $sql1 = 'query here'; $sth1 = $dbh->prepare($sql1); $sth1->execute(); //loops through using different handle, if used sth again? while ($row = $sth1->fetch(pdo::fetch_assoc)) { somefunction($bm_table,$row); } }
as can see above using different statement handle (sth, sth1 etc.) necessary? or can use 1 statement handle everything. reason have used multiple handles $bm_table value uses sth, still in use while fetching $row wouldn't change value of $bm_table or stop fetch working? how handles pdo work? when in case have 2 simultaneous fetch loops running @ same time using same pdo connection.
so main thing looking here if have 2 statements running simultaneously important used different handles? can continue use same connection?
thanks,
$sth
, sth1
not statement handles, they're php variables. can reassign variable if no longer need old value. in case of code, still need old value.
if assign $sth
inside outer loop handle returned second prepare()
call, when gets top of loop , re-executes $sth->fetch()
test, try fetch second query, not first one. end outer loop because rows have been read.
you can reuse statement handle repetitions of same query. useful when query has parameters:
$stmt = $dbh->prepare("select * tablename id = :id"); $stmt->bindparam(':id', $id); foreach ($id_array $id) { $stmt->execute(); $row = $stmt->fetch(); // stuff $row }
Comments
Post a Comment