简体   繁体   中英

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;
    }

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

$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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM