0

After getting a great response from @majick I was able to resolve an issue I was having with trying to access wp-config.php from a plugin. I've set up the connection file I'm using in the plugin in as so:

function find_require($file,$folder=null) {

    if ($folder === null) {$folder = dirname(__FILE__);}

    $path = $folder.'/'.$file;

    if (file_exists($path)) {require($path); return $folder;}
    else {
        $upfolder = find_require($file,dirname($folder));
        if ($upfolder != '') {return $upfolder;}
   }
}

$configpath = find_require('wp-config.php');

require_once($configpath.'\wp-config.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($conn, DB_NAME);

With that in place I can load my table content, but when it comes to modifying the table content I've run into an issue. The table is updated, but I get the following errors:

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in ...\wp-content\plugins\editdb\editdatabase.php on line 145

Warning: mysqli_error() expects parameter 1 to be mysqli, null given in ...\wp-content\plugins\editdb\editdatabase.php on line 150

Error getting tables:

Warning: mysqli_close() expects parameter 1 to be mysqli, null given in ...\wp-content\plugins\editdb\editdatabase.php on line 175

As well when the page reloads with the dropdown selection list the list is now empty and does not contain any Employee names from the Database.

I know its related to having this executed in a plugin rather then the theme, but I don't know enough to determine exactly why the null values are occurring.

To put some perspective before using this I had hard coded the wp-config information in the plugin's connect.php file and everything worked, but for obvious reasons that is not best practice.

3

You should never have to read wp-config to get database credentials. WordPress has built-in functions which are generally more secure for this sort of operation.

In your plugin, simply call global $wpdb;

and you will be connected to the WP database. You can then perform whatever queries you need - select, update, add, etc. For example:

$results = $wpdb->get_results( 'SELECT * FROM wp_options WHERE option_id = 1', OBJECT );

Please see https://codex.wordpress.org/Class_Reference/wpdb for details. This should be both safer and much easier than reading in credentials and manually connecting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.