proPhet
proPhet

Reputation: 1228

Only 1 out of 5 mysql statements run when executed php do

My statements are prepared like this:

$statement_1 = $DBH->prepare("
    DROP TABLE IF EXISTS `table_1`;
    CREATE TABLE `table_1` (
        ... statements are all running fine in phpmyadmin when executed separately
");
$statement_2 = $DBH->prepare("
    DROP TABLE IF EXISTS `table_2`;
    CREATE TABLE `table_2` (
        ... statements are all running fine in phpmyadmin when executed separately
");
$statement_3 = $DBH->prepare("
    DROP TABLE IF EXISTS `table_3`;
    CREATE TABLE `table_3` (
        ... statements are all running fine in phpmyadmin when executed separately
");
$statement_4 = $DBH->prepare("
    DROP TABLE IF EXISTS `table_4`;
    CREATE TABLE `table_4` (
        ... statements are all running fine in phpmyadmin when executed separately
");
$statement_5 = $DBH->prepare("
    DROP TABLE IF EXISTS `table_5`;
    CREATE TABLE `table_5` (
        ... statements are all running fine in phpmyadmin when executed separately
");

Then I try and execute the statements in separate if statements so that I can see that all the statements were executed successfully, like so:

if($statement_1->execute()){
    echo "statement_1 executed successfully!";
}else{
    echo "statement_1 failed to execute!";
}

if($statement_2->execute()){
    echo "statement_2 executed successfully!";
}else{
    echo "statement_2 failed to execute!";
}
....

.. and so on and so on for the rest of the statements.

My issue is when I try to run all the statements in the ifs, only the first statement runs (statement_1). The rest are unsuccessful.

Do I need to run all the statements as one long string? Or in a transaction block?

Upvotes: 1

Views: 44

Answers (1)

Richard87
Richard87

Reputation: 1622

Close the statement when you're done with it...

if($statement_1->execute()){
    $statement_1->closeCursor();
    echo "statement_1 executed successfully!";
}else{
    echo "statement_1 failed to execute!";
}

if($statement_2->execute()){
    $statement_2->closeCursor();
    echo "statement_2 executed successfully!";
}else{
    echo "statement_2 failed to execute!";
}

Good luck

Upvotes: 1

Related Questions