0

I am new to using PHP to run SQL commands but what I'm trying to do is truncate specific tables within my database when the script is run. I can do this fine truncating just one table but when I attempt multiple table I run into issues! Code is below, any pointers?! Thanks in advance

 <?php
    var_dump($_POST);
    $myServer = $_POST['host'];
    $myUser = $_POST['user'];
    $myPass = $_POST['password'];
    $myDB = $_POST['db'];

    $con = mysqli_connect($myServer, $myUser, $myPass) or die("Connection 
    Failed");
    mysqli_select_db($con, $myDB)or die("Connection Failed");


    $query = ("
        SET FOREIGN_KEY_CHECKS = 0;

        TRUNCATE table customers;

        TRUNCATE table customers2;

        SET FOREIGN_KEY_CHECKS = 1;


    ");

    if(mysqli_query($con, $query)){
    echo "table empty";}
    else{
     echo("Error description: " . mysqli_error($con));}


    ?>
5
  • 3
    Possible duplicate of Two mysqli queries Commented Oct 4, 2017 at 14:04
  • Your query should not have parenthesis surrounding it. You cannot pass multiple statements into a mysqli query. Either do multiple queries or use mysqli_multi_query. Commented Oct 4, 2017 at 14:04
  • You said you run into issues. "issues" as? any error messages or something? Commented Oct 4, 2017 at 14:05
  • try executing one query per call to mysqli_query(). not 4 at once Commented Oct 4, 2017 at 14:05
  • Thank you all, you beautiful people! :-) Commented Oct 4, 2017 at 14:17

2 Answers 2

2

execute one query at a time

mysqli_query($con, "SET FOREIGN_KEY_CHECKS = 0;");
mysqli_query($con, "TRUNCATE table customers;");
mysqli_query($con, "TRUNCATE table customers2;");
mysqli_query($con, "SET FOREIGN_KEY_CHECKS = 1;");

or use mysqli_multi_query

mysqli_multi_query($con, "
SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE table customers;
TRUNCATE table customers2;
SET FOREIGN_KEY_CHECKS = 1;
");
Sign up to request clarification or add additional context in comments.

Comments

0

mysqli_query only allows one query at a time. If you want to use multiple queries at once, use mysqli_multi_query. Documentation: http://php.net/manual/en/mysqli.multi-query.php

In your code, you would change

mysqli_query($con, $query)

to

mysqli_multi_query($con, $query)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.