Skip to content

Instantly share code, notes, and snippets.

@chrisdavidmiles
Last active May 29, 2016 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisdavidmiles/965d9190581bc1b99ad3f48447f59370 to your computer and use it in GitHub Desktop.
Save chrisdavidmiles/965d9190581bc1b99ad3f48447f59370 to your computer and use it in GitHub Desktop.
This is a database connectivity script for WordPress. It's designed to help troubleshoot the dreaded "Error Establishing Database Connection" error. To use this tool, create a file in the same folder as wp-config.php, place this code in it, and access the file in a browser.
<?php
/**
* This is a database connectivity script for WordPress.
* It's designed to help troubleshot the dreaded "Error Establishing Database Connection" error.
*
* How does it work? It uses regular expressions to match the database settings in the wp-config.php
* and then tests those settings. If there is an error thrown, the script interprets the error and
* prints actionable information that can be used to fix the site, if at all possible. If the database
* connection works, the script will run a REPAIR on all tables in the database, and print the results.
*/
// File will delete itself when accessed
unlink(__FILE__);
$conditionaldirectory = dirname($_SERVER['PHP_SELF']);
if ($conditionaldirectory == "/"){
$conditionaldirectory = "";
}
echo "
<link rel=\"stylesheet\" href=\"https://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\"/>
<link rel=\"stylesheet\" href=\"https://netdna.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css\"/>
<script data-cfasync=\"false\" src=\"//ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js\"></script>
<script data-cfasync=\"false\" src=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>
<div class=\"container\"><h3>";
echo ' '.$_SERVER['HTTP_HOST'];
echo "$conditionaldirectory database connection test</h3>";
// This will be overridden if WP_ALLOW_REPAIR is defined as true in wp-config.php
$allow_repair = false;
$wpconfig = dirname( __FILE__ ) . '/wp-config.php';
if ( ! file_exists( $wpconfig ) )
die( "Results: <span style=\"color: rgb(255, 0, 0);\">wp-config.php file cannot be found.</span> Please place this script in the same directory as wp-config.php.</h4>" );
if ( file_exists( dirname( dirname( __FILE__ ) ) . '/wp-config.php' ) && ! file_exists( dirname( dirname( __FILE__ ) ) . '/wp-settings.php' ) )
printf( "<h4>Results: There appears to be a wp-config.php file at %s which is\nnot part of a WordPress installation, but can be read by WordPress. Perhaps\nthe wp-config.php file at %s isn't needed?</h4>", dirname( dirname( __FILE__ ) ) . '/wp-config.php', $wpconfig );
$contents = file_get_contents( $wpconfig );
foreach ( array( 'DB_NAME', 'DB_USER', 'DB_PASSWORD', 'DB_HOST' ) as $config )
preg_match( "/define[ ]*?\([^'\"]*?(['\"])$config\\1[^,]*?,[^'\"]*?(['\"])(.+)\\2[ ]*?\);/iU", $contents, $$config );
preg_match( '/\$table_prefix[ ]*?=[ ]*?([\'"]+)(.+)\\1[ ]*?;/iU', $contents, $table_prefix );
if ( ! $allow_repair && preg_match( "/define[ ]*?\([^'\"]*?(['\"])WP_ALLOW_REPAIR\\1[^,]*?,[^'\"]*?true[ ]*?\);/iU", $contents ) )
$allow_repair = true;
@$link = mysql_connect( $DB_HOST[3], $DB_USER[3], $DB_PASSWORD[3] );
if ( ! $link ) {
die( sprintf( "<h4>Results: <span style=\"color: rgb(255, 0, 0);\">Database connection failed with this error:</span></h4><pre> %s\n</pre> <h4>Possible Errors Explained:</h4><ul><li><span style=\"font-family: monospace;\">Access denied for user 'example_user'@'localhost' (using password: YES)</span> - <br>This means the user listed in wp-config.php was not allowed to access the database listed in wp-config.php when it tried. Typically this error comes up when an sql username or password is wrong. </li><li><span style=\"font-family: monospace;\">User 'user_example' already has more than 'max_user_connections' active connections</span> - <br>This error means that the user specified in wp-config.php is hitting it's max sql connection limit. SQL is a language that databases use, and site builders like WordPress and Joomla use them. If the site is optimized correctly, when it checks the database the \"query\" or information lookup should be open and closed very very quickly. There can only be 15 simultaneous look-ups but on a well optimized site this isn't a problem since they are opened and closed so fast, there can be lots of traffic and the site won't slow down. But if the site code isn't optimized well, there are what are called \"slow queries\" or requests that take a long time. If the site is doing this frequently, then at times the site will appear to be down since it's waiting for the slow queries to complete before more people can access the site. </ul>", mysql_error() ) );
}
echo "<h4>Results: <span style=\"color: rgb(57, 123, 33);\">Successful database connection! </span>\n";
@$db_selected = mysql_select_db( $DB_NAME[3], $link );
if ( ! $db_selected ) {
die ( sprintf( "<span style=\"color: rgb(255, 0, 0);\">Database selection failed with this error:</span></h4><pre> '%s': %s\n</pre><h5><hr>This error means that the sql username and password in wp-config.php work with each other, but when that sql user tries to access the specified database, <i>then</i> an error gets thrown. <br><br>This could mean:<ul><li>The database name could be wrong in the wp-config.php file. (Check if a database named \"$DB_NAME[3]\" even exists). </li><li>The database user, might not be assigned to the database with full privileges.</li></ul>", $DB_NAME[3], mysql_error() ) );
}
echo "<span style=\"color: rgb(57, 123, 33);\">Database selected successfully!</h4>\n<h5>The database user/password works, and the sql user specified in wp-config.php was able to access the database without problems just now. If this site is only showing database errors sometimes, perhaps the issue is slow queries or the sql user hitting the maximum simultaneous connection limit. Try looking in the slow query logs and see how many slow queries there has been for $DB_NAME[3] today.<br><br>If the database connection error is constant, and we know the user/password/privileges are ok, let's see if running a repair on the database helps. You can see the results of the database check and repair below. If all the tables in the database come back as OK, and the site is still throwing a database related error, you can at least know that the sql settings in wp-config.php seem to be correct. Keep in mind that sometimes plugins and themes can cause sql related errors too sometimes.<br><br></span>";
echo "\n<button type=\"button\" class=\"btn btn-default\" data-toggle=\"collapse\" data-target=\"#sql-repair-log\">Database Check and Repair</button><div id=\"sql-repair-log\" class=\"collapse\"> <br><pre><strong>Checking tables for errors:</strong>\n";
$tables = mysql_query( "SHOW TABLES LIKE '{$table_prefix[2]}%'" );
while ( $table = mysql_fetch_array( $tables, MYSQL_NUM ) ) {
$status = mysql_fetch_row( mysql_query( "CHECK TABLE `{$table[0]}`" ) );
$message = sprintf( 'The table %s is', $status[0] );
if ( $status[3] != 'OK' ) {
printf( "\n%s NOT OK. Error: %s\n", $message, $status[3] );
if ( $allow_repair ) {
printf( "Attempting to repair %s\n", $status[0] );
$status = mysql_fetch_row( mysql_query( "REPAIR TABLE `{$table[0]}`") );
$message = sprintf( 'The table %s', $status[0] );
if ( $status[3] != 'OK' )
printf( "%s could NOT be repaired. Error: %s\n\n", $message, $status[3] );
else
printf( "%s was successfully repaired\n\n", $message );;
} else {
printf( "Not repairing table %s due to configuration.\nChange \$allow_repair to true or define WP_ALLOW_REPAIR in wp-config.php\n\n", $status[0] );
}
} else {
printf( "%s OK\n", $message );
}
}
// Close sql connection
mysql_close( $link );
?>
</div></pre></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment