如何从WordPress中的functions.php执行SELECT

I have had a google about and found a few posts but not a full answer. I want to run my own query when a page is loaded into WordPress. I want to run this query from functions.php:

function performSelect() {
global $wpdb;
$result = $wpdb->query("SELECT ip_address FROM MyTABLE ORDER BY datetime DESC LIMIT 0,1"); 

print_r( $result);

}

I get a '1' outputting on my page. How do I go about getting ip_address back as an actual field? I have ran the query on the server and it does return an IP, not a 1 as in WordPress!

UPDATE 1

I have now have this working, but I'd like to put in a loop for queries that return more than one row:

$result = $wpdb->get_row("SELECT ip_address FROM MyTABLE ORDER BY datetime DESC LIMIT 0,1", ARRAY_A); 

echo $result['ip_address']; // WORKS

How would I go about looping through $result? I've tried a few methods and all error.

Try This

global $wpdb;
$result = $wpdb->get_results("SELECT ip_address FROM MyTABLE ORDER BY datetime DESC LIMIT 0,1");
foreach($result as $row) {
    echo 'Ip address:'.$row->ip_address;
}

$result isn't a string but a mysqli result, so you need to turn it into an array, then grab the ip address.

$result = $result->fetch_array(MYSQLI_ASSOC);
var_dump($result['ip_address'];

try get_row:

$result = $wpdb->get_row("SELECT ip_address FROM MyTABLE ORDER BY datetime DESC LIMIT 0,1"); 

get_row will immediately parse the sql result into a row; you can also assign a second parameter to turn the result into an object, see: http://codex.wordpress.org/Class_Reference/wpdb

Instead of get_row, you can also use get_results to retrieve multiple results from the database.

You can use get_var to directly fetch the result:

function performSelect() {
    global $wpdb;
    $result = $wpdb->get_var("SELECT ip_address FROM MyTABLE ORDER BY datetime DESC LIMIT 0,1"); 

    print_r($result);

}