1

I want to use the wpdb class on my external page not associated with wordpress.

I tried to include the following on the php file:

// include wordpress functions
include( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
require_wp_db();
global $wpdb;

Now I made a query using $wpdb->query

$product_info_query = $wpdb->query("select p.products_id, p.products_type, p.img_display, p.products_sku, pd.products_name, pd.products_description, p.products_model, p.products_quantity, p.products_image, pd.products_url, p.products_price, p.products_tax_class_id, p.products_date_added, p.products_last_modified, p.products_date_available, p.manufacturers_id, gp.likes from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd, " . TABLE_GLOBAL_PRODUCTS . " gp where p.products_status = '1' and p.products_id = '" . (int)$_GET['products_id'] . "' and pd.products_id = p.products_id and gp.products_id = p.products_id and pd.language_id = '" . (int)$languages_id . "'");
$product_info = mysql_fetch_array($product_info_query);

However, its not working. It returned a warning:

Warning: mysql_fetch_array() expects parameter 1 to be resource

What seems to be the problem? How to fix this and probably use wpdb class correctly on running queries outside wordpress?

3
  • Have you tried doing a simple query like SELECT * FROM sometablename to see if it's actually working? Btw: You're missing all the funkyness of the $wpdb class like prepare()...
    – kaiser
    Nov 19 '12 at 15:09
  • YES.. I tried the query using native mysql_query() and its working.. I also tried adding $wpdb->prepare() and the problem persists.
    – Ken
    Nov 19 '12 at 15:12
  • I meant if a simply query works with $wpdb...
    – kaiser
    Nov 19 '12 at 15:15
3

You can't mix wpdb with mysql_fetch_array. They are not compatible. You need to use wpdb methods, plus PHP functions like while, foreach, and for. wpdb does not return the references that PHP's mysql functions use. It returns an object, and array, or sometimes a string.

In your case, though, the database part is done. You just want to foreach over the result set.

foreach ($products as $op) {
    // do stuff
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.