Steve Gear
Steve Gear

Reputation: 21

will mysqli->rollback(), rollback every query that has been previously committed?

I want to know if mysqli->rollback will rollback all the queries that have been committed before the rollback.

For example, in the code below, the first query will be committed, but the second query will fail because of misspelling 'username'. Does that mean that the query before the rollback will or will not get executed?

$mysqli->autocommit(FALSE);

$query = "INSERT INTO users (username, password) VALUES ('user123', '1apple')";
$query2 = "INSERT INTO users (**usernam**, password) VALUES ('user987', '2apple')";

if($resrouce = $mysqli->query($query)){

    $mysqli->commit();

    if($resource2 = $mysqli->query($query2)){

        $mysqli->commit();

    }else{

        $mysqli->rollback();

    }

}else{
    $mysqli->rollback();
}

Upvotes: 2

Views: 4056

Answers (3)

Alexander
Alexander

Reputation: 11

modify line 8 and add a line in the end in your code:

$mysqli->autocommit(FALSE);

$query = "INSERT INTO users (username, password) VALUES ('user123', '1apple')";
$query2 = "INSERT INTO users (**usernam**, password) VALUES ('user987', '2apple')";

if($resrouce = $mysqli->query($query)){

    //$mysqli->commit(); this not necesary

    if($resource2 = $mysqli->query($query2)){

        $mysqli->commit();

    }else{

        $mysqli->rollback();

    }

}else{
    $mysqli->rollback();
}

$mysqli->close();

Upvotes: 1

Feras
Feras

Reputation: 2184

Personally I find the PDO library better for database access than mysqli. You can check: http://php.net/manual/en/pdo.begintransaction.php

which does exactly what you need... Hope that helps

Upvotes: -3

ogres
ogres

Reputation: 3690

Once you commit the transaction , you can not rollback it , you can only rollback the statement which is not comited yet

Upvotes: 4

Related Questions