Justian Meyer
Justian Meyer

Reputation: 3703

Running MySQL Query in Wordpress Causes HTML Markup to Disappear?

We're having an issue adding MySQL queries to our page. It seems that whenever something is run at the top of the page, the rest of the markup and php functions to follow don't show up/aren't run.

Here's a sample query that causes this issue:

global $wpdb;

$add_query = "CREATE TABLE thetesttable
        (
           id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
           product VARCHAR(50)
        )";

$wpdb->query($add_query) or die(mysql_error());

Loading the page once results in a blank page.

The second time, we see Table 'thetesttable' already exists, which means that our queries are getting through.

There are no other errors on the page or anything else detected by Google Chrome.

What could be causing this problem?

Many thanks,

Justian Meyer

Upvotes: 1

Views: 730

Answers (2)

jeroen
jeroen

Reputation: 91792

The problem is that your query is returning 0 which is interpreted as false in your statment:

$wpdb->query($add_query) or die(mysql_error());

From the wpdb class reference:

The function returns an integer corresponding to the number of rows affected/selected. If there is a MySQL error, the function will return FALSE. (Note: since both 0 and FALSE can be returned, make sure you use the correct comparison operator: equality == vs. identicality ===).

What you should do is something like:

$result = $wpdb->query($add_query);
if ($result === false)
{
  die('Could not run query');
}

Edit: By the way, also note that you should not use mysql_error() like you do when you use the wpdb class. To get the last error, you can use $wpdb->print_error();.

Upvotes: 3

RRStoyanov
RRStoyanov

Reputation: 1172

After all additional comments, than I suggest adding additional query which is

SHOW TABLES LIKE 'thetesttable';

Run the CREATE TABLE query if no results from above one and skip it if table exist.

Upvotes: -1

Related Questions