Kevin Kromjong
Kevin Kromjong

Reputation: 174

MySQL in PHP gives error, MySQL in phpmyadmin does not

I want to truncate a table via PHP. It has some foreign keys, so I use the little trick where I set my foreign key check to zero:

$query_truncate_extension = "SET FOREIGN_KEY_CHECKS = 0; TRUNCATE TABLE extension; SET FOREIGN_KEY_CHECKS = 1;";

When I execute the script, the mysqli_error() gives me the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TRUNCATE TABLE extension; SET FOREIGN_KEY_CHECKS = 1' at line 1

So my table doesn't get truncated at all. But the weird thing is when I put this exact same query in the SQL-query section in phpmyadmin, it doesn't throw an error at all and my table is empty afterwards.

So my question is: why does this code gives an error in PHP, but not in phpmyadmin and how do I solve this?

Thanks in advance!

Upvotes: 1

Views: 288

Answers (2)

M I
M I

Reputation: 3682

If you wan to run multiple queries in one call then you need to use

mysqli_multi_query()

This is a function allows to run one or multiple queries which are concatenated by a semicolon.

To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().

You can read more detail here.

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

--------- Example Program at the link above -------------

$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query  = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";

/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
    } while ($mysqli->next_result());
}

/* close connection */
$mysqli->close();

You can change it according to your requirement.

Upvotes: 2

Rasel
Rasel

Reputation: 5734

Use single query in single call like

$query_truncate_extension = "SET FOREIGN_KEY_CHECKS = 0"

Upvotes: 0

Related Questions