PHP Retrieving Value from MySql Error
I have a php script that I've put together from examples开发者_JAVA百科 on the internet.
I'm not very familiar with php and I'm getting an error.
I am trying to get the last post date of my Wordpress blog for my program to show when the last date that we put important information for the user on it.
This is my code:
<?php
function lpd_post_date( $date_format, $echo, $modified_date = false )
{
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpass = 'xxx';
$dbname = 'xxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
mysql_select_db($dbname);
// include 'config.php';
// include 'opendb.php';
global $wpdb;
$date_col = 'post_date';
if ( $modified_date ) $date_col = 'post_modified';
$sql = " SELECT $date_col FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type = 'post' ORDER BY $date_col DESC LIMIT 1 ";
$mysql_date = $wpdb->get_var( $sql );
if ( ! $date_format ) $date_format = get_option('date_format');
$formatted_date = mysql2date( $date_format, $mysql_date );
echo $formatted_date;
mysql_close($conn);
}
?>
I am getting this error:
Fatal error: Call to a member function on a non-object in /homepages/38/d157689362/htdocs/suburban/updates/last/last.php on line 21
Anyone able to help me out? I'm lost as to what it is doing on line 21:
$mysql_date = $wpdb->get_var( $sql );
Any help would be greatly appreciated!
Thanks!
You are using the global variable $wpdb
which should be an instance of some class but when you use it, it's undefined. $wpdb
should be instantiated prior calling function lpd_post_date
. You will instantiate $wpdb
with something like this:
$wpdb = new myClass(); //myClass is the class name of your class
This error is indeed because $wpdb is not defined.
You are better off putting this code in the WordPress functions.php file that WP creates for your active theme (found in 'wp-content/themes/active_theme_name/functions.php' - the default theme is 'default' if I recall correctly). $wpdb already is defined in this file, and the code you have written should work there (take out the <?php
and ?>
and just put the function in the file somewhere with the others). You would then call the function you have created either by:
Putting
include_once('_path_to_active_theme/functions.php');
at the top of your script and then call the function in your new php file:$return_value = lpd_post_date($date_format, $echo, $modified_date);
//Do whatever we need to do with $return_value
Call the function in your theme UI code - if of course you are trying to put the value lpd_post_date return value in your UI somewhere
The following may help:
http://wordpress.org/support/topic/get_var-on-a-non-object-wpdb http://codex.wordpress.org/Theme_Development#Functions_File
It would definitely be a good idea to read that entire Theme_Development 2nd link if you haven't already.
精彩评论