0

I'm querying a server and iterating through multiple databases using PHP, but for some reason this $sql2 query (which I have read works in countless threads) is returning a syntax error:

$res = mysqli_query($conn,"SHOW DATABASES");

if (!$res){
    // Deal with error
}

while ($d = mysqli_fetch_array($res)){

    $db = $d['Database'];

    $sql1 = "USE $db";
    $query1 = mysqli_query($conn, $sql1);

    if (!$query1){
        // Deal with error
    }

    $sql2 = "IF (EXISTS (SELECT *
                 FROM INFORMATION_SCHEMA.TABLE
                 WHERE TABLE_SCHEMA = '$db'
                 AND TABLE_NAME = 'appusers'))
             BEGIN
                 SELECT * FROM `appusers`
             END";

    $query2 = mysqli_query($conn, $sql2);

    if (!$query2){
        // Deal with error
    }
}

This is the error I receive:

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 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLE WHERE TABLE_S' at line 1

My MySQL Server version is 5.6.27 and my PHP interpreter is 5.6

Jodo1992
  • 745
  • 2
  • 10
  • 32

2 Answers2

2

You can't use an IF statement as a query, only in a stored procedure. You'll need to perform two separate queries.

$sql = "SELECT COUNT(*) AS count
        FROM INFORMATION_SCHEMA.TABLES
        WHERE TABLE_SCHEMA = '$db'
        AND TABLE_NAME = 'appusers'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn);
$row = mysqli_fetch_assoc($result);
if ($row['count'] != 0) {
    $sql2 = "SELECT * FROM appusers";
    $query2 = mysqli_query($conn, $sql2);
    ...
} else {
    // deal with error
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

There is no if in SQL (although mysql has a function called if)

Apparently, you want to run a query if the table exists. The more common way would be to try running the query and check whether the error you get says that the table doesn't exist.

E.g. if you run the query in the mysql command line application, you might get this:

mysql> SELECT * FROM appusers;
ERROR 1146 (42S02): Table 'test.appusers' doesn't exist

You see two codes:

In your case, checking the SQL state might be better because it covers more cases. E.g., all of these mysql error codes map to SQL state 42S02:

  • 1051 - Unknown table '%s'
  • 1109 - Unknown table '%s' in %s
  • 1146 - Table '%s.%s' doesn't exist
Markus Winand
  • 8,371
  • 1
  • 35
  • 44