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

60 Views Asked by At

I want to begin a transaction with multiple queries in MySQL and through self-learning, I write my 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 * FROM table1 WHERE table1.id = 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    if ($row = $stmt->fetch()) {
        // There should be only one row so I used if
    }
    else {
    }

    // Second Query

    $sql2 = "SELECT * FROM table2 WHERE 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 my code I used the same $pdo twice like

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

and then

$pdo->commit();

When it is just one stmt the code will show the database data fine.

I haven't successfully tested it since there are syntax errors in other files that prevent this from running. I'm very new to PDO, so could anyone tell me if this is fine to run? Thanks!

1

There are 1 best solutions below

4
Jose Marques On

Example (PDO) using '?'

<?php
/* Execute a prepared statement by passing an array of values */
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->execute(array(150, 'red'));
$red = $sth->fetchAll();
$sth->execute(array(175, 'yellow'));
$yellow = $sth->fetchAll();
?>

Looking to the example you can see your mistakes.

first:

$sql = "SELECT * FROM table1 WHERE table1.id = ?";

second:

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

Sorry for my English but it's not my mother tongue.