Toolserver/Database/PHP

From Meta, a Wikimedia project coordination wiki

Jump to: navigation, search

This explains how to read your $HOME/.my.cnf from PHP, which does not support MYSQL_READ_DEFAULT_GROUP.

  1. Create a file named "database.php" with the following code. This code connects to the relevant database and provides meaningful errors on failure.
    <?php
    /***************
    ** Database connection
    ***************/
    function dbconnect($database) {
            // fix redundant error-reporting
            $errorlevel = ini_set('error_reporting','0');
     
            // connect
            $mycnf = parse_ini_file("/home/".get_current_user()."/.my.cnf");
            $username = $mycnf['user'];
            $password = $mycnf['password'];
            unset($mycnf);
            $db['connected'] = mysql_connect($database . '.db.toolserver.org',$username,$password) 
                    or print '<p class="fail"><strong>Database server login failed.</strong> '
                             . ' This is probably a temporary problem with the server and will be fixed soon. '
                             . ' The server returned: ' . mysql_error() . '</p>';
            unset($username);
            unset($password);
     
            // select database
            if($db['connected']) {
                    mysql_select_db(str_replace('-','_',$database)) 
                            or print '<p class="fail"><strong>Database connection failed: ' 
                                     . mysql_error() . '</strong></p>';
            }
     
            // restore error-reporting
            ini_set('error-reporting',$errorlevel);    
    }
    ?>
    
  2. At the top of a script that uses database access, include the following code. Replace "enwiki" with the appropriate wiki database name, and adjust the path depending on where you put the file.
    // connect to database
    include('database.php');
    dbconnect('enwiki');