How To Make Connection To WordPress Data Base In A Plugin?

I am learning Plugins and I am trying to connect WordPress database wp-config.php in my Plugin PHP code. Currently for checking my code, I used the below connection and it is working fine. Now I converted it into a WordPress plugin so anyone can use this but now its time to make WordPress database connection.

//Connection To DataBase
$host = "XXXXXXXXXXXXXX";
$username = "XXXXXXXXXX";
$password = "XXXXXXXXXX";
$dbname = "XXXXXXXXXXXX";
$connection = mysql_connect($host, $username, $password);
mysql_select_db($dbname);

So How to insert wp-config.php like something require_once(wp-config.php'); in plugin instead of above code to make WordPress SQL database connection in my plugin file?

1 Answer
1

I found the answer my self. First open your wp-config.php and check the bottom of file that Is that contain the below code?…

if ( !defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . "https://wordpress.stackexchange.com/");

If yes then add the below code to make the connection in your plugin PHP files to connect with wp-config.php file that contain Database Name, Database UserName, Database Password, Database Host… …

require_once(ABSPATH . 'wp-config.php');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($connection, DB_NAME);

And you will get connection to WordPress database…

Leave a Comment