Joe Cory
Joe Cory

Reputation: 45

How to run 2 sql queries in one php if statement?

This is the code i have so far

if (isset($_POST['button1']))
    {
        $sql = "DELETE FROM UpcomingRota";
        $E1 = $_POST["MondayAMFirstEmployee"]; $E2 = $_POST["MondayAMSecondEmployee"]; $E3 = $_POST["MondayAMThirdEmployee"];
        $sql = "INSERT INTO UpcomingRota (DayAndTime, FirstEmployee, SecondEmployee, ThirdEmployee) VALUES ('MondayAM', '$E1', '$E2', '$E3')";

    }

Both the $sql statements work perfectly on there own but when i have both in the if statement it seems to bypass the first one and just run the last $sql statement.

How can i get it to run as many $sql statements as i need it to.... going to have around 15 - 20 in there.

Thanks in advance.

More code as requested.

$servername = "db568845851.db.1and1.com";
    $username = "dbo568845851";
    $password = "";
    $dbname = "db568845851";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    if (isset($_POST['button1']))
    {
        $sql = "DELETE FROM UpcomingRota";
        $E1 = $_POST["MondayAMFirstEmployee"]; $E2 = $_POST["MondayAMSecondEmployee"]; $E3 = $_POST["MondayAMThirdEmployee"];
        $sql = "INSERT INTO UpcomingRota (DayAndTime, FirstEmployee, SecondEmployee, ThirdEmployee) VALUES ('MondayAM', '$E1', '$E2', '$E3')";

    }

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }

Upvotes: 1

Views: 1598

Answers (3)

Joe Cory
Joe Cory

Reputation: 45

Turns out because i am just doing lots of inserts into my table i should be doing this.

INSERT INTO TABLE (column1, column2) VALUES ('data', 'data'), ('data', 'data')

and its working so far.

Upvotes: 0

user1358298
user1358298

Reputation:

The second statement is overwriting the first one. You can append the second query to the first one using the following syntax:

$sql = "First statement;"; // Statements are separated by a ;
$sql .= "Second statement;";

// (Notice the . before the = on the second line)
// $sql now contains "First statement;Second Statement;"

You will also need to make sure you are executing the query using a database adapter in a way that supports multi-queries:

http://php.net/manual/en/mysqli.multi-query.php

Upvotes: 1

Grumpy
Grumpy

Reputation: 2243

$sql = "DELETE FROM UpcomingRota";
$myResult = mysql_query($sql);
        $E1 = $_POST["MondayAMFirstEmployee"]; $E2 = $_POST["MondayAMSecondEmployee"]; $E3 = $_POST["MondayAMThirdEmployee"];
        $sql = "INSERT INTO UpcomingRota (DayAndTime, FirstEmployee, 
SecondEmployee, ThirdEmployee) VALUES ('MondayAM', '$E1', '$E2', '$E3')";
$myResult = mysql_query($sql);

You have to execute the querys.

Upvotes: 1

Related Questions