我创建了一个自定义管理菜单:
function new_menu() {
add_menu_page(
'New Menu',
'New Menu',
'administrator',
'new_menu',
'new_menu_content'
);
}
add_action('admin_menu','new_menu');
在该新菜单中,我从数据库中获取了一些数据:
function fishing_data_content($conn){
require_once(get_template_directory() . '/connect.php');
require_once(get_stylesheet_directory() . '/data.php');
}
connect.php
连接到数据库:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "data";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
然后data.php
从该数据库中获取一些数据:
$stmt = $conn->prepare('SELECT * FROM posts');
$stmt->execute();
$values = $stmt->fetchAll();
foreach($values as $val){
echo $val . '<br>';
}
}
我还试图在data.php中要求连接文件:
require_once(dirname(__FILE__) . '/connect.php');
但仍然存在相同的错误:
Fatal error: Call to a member function prepare() on string in /home/public_html/wordpress/wp-content/themes/theme/data.php on line 10