WordPress.org

Forums

[resolved] Access database outside of WordPress 3.9 (4 posts)

  1. SFGolfer
    Member
    Posted 2 years ago #

    I have been using the code below in a custom .php file outside of WordPress. The code worked without any issues until upgrading to 3.9 or 3.9.1.

    define( 'SHORTINIT', true );
    
    require_once( $_SERVER['DOCUMENT_ROOT'] . '/blog/wp-load.php' );
    
    global $wpdb;
    $tourney = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM database WHERE player_name='".$player."' And season='".$season."' And status='' ORDER BY date DESC", $null ), ARRAY_N );

    Now this error appears:

    Call to undefined function __() in /home1/public_html/blog/wp-includes/wp-db.php

    What would be the proper method of querying a database outside of WordPress?

  2. SFGolfer
    Member
    Posted 2 years ago #

    It seems using $wpdb>prepare does not work outside of WordPress.

    Omitting $wpdb>prepare in my query now works but I'd sure like to know why it worked before and not now if it is included.

    $tourney = $wpdb->get_results( "SELECT * FROM database WHERE player_name='".$player."' And season='".$season."' And status='' ORDER BY date DESC", ARRAY_N );

  3. RossMitchell
    Member
    Posted 2 years ago #

    Your problem is that you are not using prepare correctly. This is what you need (assuming that player and season are strings):

    $tourney = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM database WHERE player_name='%s' And season='%s' And status='' ORDER BY date DESC", $player, $season ), ARRAY_N );

    It really is important to prevent user input being passed through to database functions. This is a common attack called "SQL injection", here is a cartoon about this http://xkcd.com/327/

  4. SFGolfer
    Member
    Posted 2 years ago #

    Thank you. That worked.

    I will replace $null within my code to be the variable names of the values being passed.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.