Have working sql query… trying to adjust it to use $wpdb
Question
So I have this code that queries a custom plugin generated table in the wp database. It works perfectly as is. But I'm trying to adjust it to use $wpdb instead of the $con function I have set up.
Here is the code that works perfectly, but not using $wpdb:
<?php
$q = strtolower($_GET["q"]);
if (!$q) return;
$isArabic = is_arabic($q);
$con=mysql_connect("localhost","admin","*****");
if($con){
mysql_select_db("arabic_student",$con);
}
else{
die("Could not connect to database");
}
mysql_query("SET NAMES utf8");
$sql = "SELECT DISTINCT en_word, ar_word FROM wp_enar_words WHERE en_word LIKE '$q%' OR ar_word LIKE '$q%'";
$rsd = mysql_query($sql) or die(mysql_error());
if($isArabic){
while($rs = mysql_fetch_array($rsd)) {
$en_word = $rs['en_word'];
$ar_word = $rs['ar_word'];
echo "$ar_word\n";
}
}else{
while($rs = mysql_fetch_array($rsd)) {
$en_word = $rs['en_word'];
$ar_word = $rs['ar_word'];
echo "$en_word\n";
}
}
?>
Here is my noob attempt to use $wpdb:
global $wpdb;
$sql = $wpdb->get_results("SELECT en_word, ar_word FROM wp_enar_words WHERE en_word LIKE '$q%' OR ar_word LIKE '$q%'");
$rsd = $wpdb->query('$sql');
But it gets a Fatal error: Call to a member function get_results() on a non-object in.... So maybe missing something obvious but hoping I could get some guidance on how to port my existing code to using $wpdb.
Thanks in advance!
UPDATE: so I'm starting to think that the problem is that this code is being called with a jquery plugin. I'm using jquery autocomplete and calling the above php code to populate the form autocomplete:
$("#search_words").autocomplete("<?php bloginfo('template_directory'); ?>/search_ac.php", {});
Could this be the problem? I'm confused because my original code that directly calls the database works perfectly, but once I use $wpdb, it no longer functions
Solution
Your error message means that $wpdb in your code is currently pointing to a null pointer. Either WP is not loaded, or you're missing a simple global $wpdb;
statement, or both.
If you need to load WP, include wp-load.php.
Or better, in your JS, use ajaxurl:
url = ajaxurl + '?action=youraction'
alongside (assuming the above code):
add_action('wp_ajax_youraction', 'yourcode');
there's an unauthenticated version of the same (see wp-admin/admin-ajax.php)
OTHER TIPS
Try this:
$sql = $wpdb->prepare( "SELECT en_word, ar_word FROM {$wpdb->prefix}enar_words WHERE en_word LIKE '%1\$s%%' OR ar_word LIKE '%1\$s%%'", $q );
$results = $wpdb->get_results( $sql );