I have a simple php file that is connect to the wordpress DB and any thing that want works fine. But I want to use the value from wp_config.php
file from wordpress to connect my php file to DB. I tried this but it's not working
<?php
require_once('wp-config.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD , DB_NAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
And this is my default PHP file that works. This file is in a directory inside the WordPress project that I use inside the other template for a custom search.
// Create connection
$conn = new mysqli($servername, $username, $password , $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Note: I change the important Data! Do you have a solution for this?
You really should be using PDO to connect, but other than that, perhaps try using constant("variable")
instead of trying to use the variables directly:
<?php
require_once('wp-config.php');
$conn = new mysqli(constant("DB_HOST"), constant("DB_USER"), constant("DB_PASSWORD"), constant("DB_NAME"));
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
The same code works fine for me.
Check the wp-config.php path and try to echo the constants and check you have included the correct file before passing to
mysqli
echo DB_HOST;
echo DB_USER;
echo DB_PASSWORD;
echo DB_NAME;
or you can use wp-load.php include('/path/wp-load.php');
include_once ('/path/wp-load.php');
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD , DB_NAME);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
Using the defines the user sets in wp-config:
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
Since your script is outside the Wordpress environment, try this:
require_once(path/to/wp-config.php');
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
Since you want to connect WP DB in other external application or in a template to get data from WP DB you can include wordpress file directly in your file. using wp-blog-header.php
will load complete wordpress into your current template and then you can use make use of it.
include_once $_SERVER['DOCUMENT_ROOT'].'/YOUR_WP_DIR/wp-blog-header.php';
global $wpdb; // wordpress database object
print_r($wpdb);
Content of wp-blog-header.php :
/**
* Loads the WordPress environment and template.
*
* @package WordPress
*/
if ( !isset($wp_did_header) ) {
$wp_did_header = true;
// Load the WordPress library.
require_once( dirname(__FILE__) . '/wp-load.php' );
// Set up the WordPress query.
wp();
// Load the theme template.
require_once( ABSPATH . WPINC . '/template-loader.php' );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.