Support » Plugins » Trouble using $wpdb to select from database

  • I am creating a plugin and I need to select a value from a custom table I have made. Here is the code I am using:

    global $wpdb;
    $mylink = $wpdb->get_row("SELECT * FROM wp_pennycounter WHERE id = 1");
    echo $mylink->pennycount;

    This is inside of a function inside of a file called ajax.php which is inside of my plugin folder. Ajax.php is called by an ajax function and the echo part of the above code is supposed to return the number zero. Here is what I have done so far in terms of debugging:

    • If I place these three lines of code in my actual wordpress site (somewhere randomly inside the body tags), it outputs a zero like it should. This means that the function itself is written correctly and that the database is cooperating.
    • If I Replace the above three lines of code inside of ajax.php with a simple echo “999”; the script works and 999 is displayed as it should be by the ajax script. This means that there is no problem with the ajax part of the script.
    • If I manually connect to the mysql database using the standard php mysql connect functions and then use a normal php select function, I can successfully get the ajax script to call the zero from the database and display it as it should.

    So, the problem is that for some reason, my ajax file found within my plugin directory doesn’t want to use the $wpdb function. How do I get this to work?

    Thanks for any help you may be able to give!

Viewing 1 replies (of 1 total)
  • Thread Starter pennycan

    (@pennycan)

    I believe I have figured out the root of my problem, but I still can’t figure out how to fix it. For some reason, in this file, $wpdb is not initialized. So, everything involving it fails. In other words, global $wpdb doesn’t work. I need to somehow include these functions some other way. How can I do this?

    I think it has to do with adding some code like this:
    include ('../../../wp-blog-header.php');

    But I can’t seem to figure it out.

Viewing 1 replies (of 1 total)
  • The topic ‘Trouble using $wpdb to select from database’ is closed to new replies.