sql >> Base de Datos >  >> RDS >> Mysql

PHP PDO MySQL Estructura del código de transacción

Algunas notas generales:No use bindParam() a menos que use un procedimiento que modifique el valor del parámetro. Por lo tanto, use bindValue() . bindParam() acepta el valor del argumento como una variable referenciada. Eso significa que no puede hacer $stmt->bindParam(':num', 1, PDO::PARAM_INT); - genera un error. Además, PDO tiene sus propias funciones para controlar transacciones, no necesita ejecutar consultas manualmente.

Reescribí su código ligeramente para arrojar algo de luz sobre cómo se puede usar PDO:

if($_POST['groupID'] && is_numeric($_POST['groupID']))
{
    // List the SQL strings that you want to use
    $sql['privileges']  = "DELETE FROM users_priveleges WHERE GroupID=:groupID";
    $sql['groups']      = "DELETE FROM groups WHERE GroupID=:groupID"; // You don't need LIMIT 1, GroupID should be unique (primary) so it's controlled by the DB
    $sql['users']       = "DELETE FROM users WHERE Group=:groupID";

    // Start the transaction. PDO turns autocommit mode off depending on the driver, you don't need to implicitly say you want it off
    $pdo->beginTransaction();

    try
    {
        // Prepare the statements
        foreach($sql as $stmt_name => &$sql_command)
        {
            $stmt[$stmt_name] = $pdo->prepare($sql_command);
        }

        // Delete the privileges
        $stmt['privileges']->bindValue(':groupID', $_POST['groupID'], PDO::PARAM_INT);
        $stmt['privileges']->execute();

        // Delete the group
        $stmt['groups']->bindValue(":groupID", $_POST['groupID'], PDO::PARAM_INT);
        $stmt['groups']->execute();

        // Delete the user 
        $stmt['users']->bindParam(":groupID", $_POST['groupID'], PDO::PARAM_INT);
        $stmt['users']->execute();

        $pdo->commit();     
    }
    catch(PDOException $e)
    {
        $pdo->rollBack();

        // Report errors
    }    
}