I am using WordPress 3.4.2, latest version! I have no plugins installed except the one that I am writing.
So Here’s the deal, I’m reading a json feed and i’m trying to import its content into a table that i created in my wordpress database. I’ve used a similar set of code in another plugin that I wrote and it works fine there. I do not understand why it does not work here.
When i run this different plugin that i am writing i am get the dreaded and oh so clear “WordPress database error: [Query was empty]”.
Here is my code…
// Setup the array
$values = array();
foreach ($bugs as $bug) {
$status_text = $bug['text'];
$tContent = htmlSpecialChars(html_entity_decode($status_text));
$imported = 2;
[ shortened to keep this post short, but other values are listed here. ]
// for the values insert part
$values[] = '("'.$tContent. '", "'.$imported.'")';
}
if(is_array($values)) {
echo "<hr><strong>WHAT TO IMPORT?</strong><br/>";
var_dump(implode(',', $values));
}
This output all of the values as expected. Everything is wrapped in parentheses and seperate by a comma.
Then i do this…
global $wpdb;
$table_name = $wpdb->prefix . "bugtbl_temp";
$sql = $wpdb->prepare (
"INSERT INTO $table_name
(`post_content`, `imported`)
VALUES ". implode(',', $values) . " ON DUPLICATE KEY UPDATE imported = 1"
);
$wpdb->query($sql); // execute query
$wpdb->print_error(); // any errors?
$wpdb->last_query; // show the qry
$wpdb->flush(); // cleanup
And then when i run this function I get the “WordPress database error: [Query was empty]” and nothing is imported into my table.
I saw on here one other guy was having problems with $wpdb->prepare. Am I using it incorrectly?
As you can read in the Codex, it’s a simple No.
You have to use it like
sprintf/printf()
. The only allowed inputs are%s
%d
Example
Disclaimer: The â shown query, doesn’t necessarily mean that it will give you results, just because you then used the
$wpdb->prepare()
right.I’ve had the same error when I forgot to add the last numeric argument in an update statement; Check that your arguments match up with the replacement tokens.
Say you have an sql string like this:
The solution is obviously to add the id
Success! I got the wpdb->prepare to work FINALLY and I’d love to share my code snippet here — Hopefully someone else will find this useful.
My Situation
I was trying to import data from a feed into a custom table from a plugin I am writing. Several websites and even the guys that replied to this thread encouraged me to protect my import queries. However, even after reading the codex, I was not able to get this to work correctly or at all.
Noteworthy Mistakes
A couple of things that I was doing wrong were:
A Solution
This probably isnt the only way to do this, but this is the way I was able to make it to work. Here is the final working code snippet. I put this in my foreach statement. Hope it helps.
Thanks to those guys that answered my original post.