php - In a mysql transaction, can $pdo handle be used for multiple queries or just once? -


i want begin transaction multiple queries in mysql , through self-learning, write code like:

$pdo = new pdo('mysql:host=localhost;dbname=project', '', '', array(     pdo::attr_errmode => pdo::errmode_exception,     pdo::attr_emulate_prepares => false ));  $pdo->begintransaction();  try {      // first query      $sql = "select * table1 table1.id = 1";     $stmt = $pdo->prepare($sql);     $stmt->execute();     if ($row = $stmt->fetch()) {         // there should 1 row used if     }     else {     }      // second query      $sql2 = "select * table2 table2.id = 1";     $stmt2 = $pdo->prepare($sql2);     $stmt2->execute();     if ($row = $stmt2->fetch()) {     }     else {     }     $pdo->commit();     echo "ok!"; }  catch(exception $e) {     echo $e->getmessage();     $pdo->rollback(); } 

so in code used same $pdo twice

$stmt = $pdo->prepare($sql); $stmt2 = $pdo->prepare($sql2); 

and

$pdo->commit(); 

when 1 stmt code show database data fine.

i haven't tested since there syntax errors in other files prevent running. i'm new pdo, tell me if fine run? thanks!

example (pdo) using '?'

<?php /* execute prepared statement passing array of values */ $sth = $dbh->prepare('select name, colour, calories     fruit     calories < ? , colour = ?'); $sth->execute(array(150, 'red')); $red = $sth->fetchall(); $sth->execute(array(175, 'yellow')); $yellow = $sth->fetchall(); ?> 

looking example can see mistakes.

first:

$sql = "select * table1 table1.id = ?"; 

second:

 $stmt = $pdo->prepare($sql);     for($id=1;$id<3;$id++){         $stmt->execute($id);         $result=$stmt->fetchall();     } 

sorry english it's not mother tongue.


Comments