Fatal error mysql connection error

i got this error message Fatal error: mysql error: [0: Connection error to server 'localhost' with user 'use_online'] in CONNECT(localhost, '****', '****', use_home) in /home/usr/public_html/libr...

i got this error message

 Fatal error: mysql error: [0: Connection error to server 'localhost' with user 'use_online'] in CONNECT(localhost, '****', '****', use_home) in /home/usr/public_html/libraries/adodb/adodb-errorhandler.inc.php on line 81

im using adodb

my code

require_once($config['basedir'].'/libraries/adodb/adodb-errorhandler.inc.php');
require_once($config['basedir'].'/libraries/adodb/adodb.inc.php');

$conn = &ADONewConnection($DBTYPE);
$conn->NConnect($DBHOST, $DBUSER, $DBPASSWORD, $DBNAME);
@mysql_query("SET NAMES 'UTF8'");
$sql = "SELECT * from config";

$rsc = $conn->Execute($sql);

it was working fine but win i move to new server it gave me the errors above

update

adodb.inc.php code
……………………………………………….

/**************************************************************************************************
| Edited By : Onlinewp
| http://onlinewp.com
|**************************************************************************************************/


/**
 * @version V3.40 7 April 2003  (c) 2000-2003 John Lim (jlim@natsoft.com.my). All rights reserved.
 * Released under both BSD license and Lesser GPL library license.
  Whenever there is any discrepancy between the two licenses,
  the BSD license will take precedence.
 *
 * Set tabs to 4 for best viewing.
 *
 * Latest version is available at http://php.weblogs.com
 *
*/

// added Claudio Bustos  clbustos#entelchile.net
if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); 

define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');

  /**
* Default Error Handler. This will be called with the following params
*
* @param $dbms      the RDBMS you are connecting to
* @param $fn        the name of the calling function (in uppercase)
* @param $errno     the native error number from the database
* @param $errmsg    the native error msg from the database
* @param $p1        $fn specific parameter - see below
* @param $P2        $fn specific parameter - see below
    */
function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
{
    if (error_reporting() == 0) return; // obey @ protocol
    switch($fn) {
    case 'EXECUTE':
        $sql = $p1;
        $inputparams = $p2;

        $s = "$dbms error: [$errno: $errmsg] in $fn("$sql")n";
        break;

    case 'PCONNECT':
    case 'CONNECT':
        $host = $p1;
        $database = $p2;

        $s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)n";
        break;
    default:
        $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)n";
        break;
    }
    /*
    * Log connection error somewhere
    *   0 message is sent to PHP's system logger, using the Operating System's system
    *       logging mechanism or a file, depending on what the error_log configuration
    *       directive is set to.
    *   1 message is sent by email to the address in the destination parameter.
    *       This is the only message type where the fourth parameter, extra_headers is used.
    *       This message type uses the same internal function as mail() does.
    *   2 message is sent through the PHP debugging connection.
    *       This option is only available if remote debugging has been enabled.
    *       In this case, the destination parameter specifies the host name or IP address
    *       and optionally, port number, of the socket receiving the debug information.
    *   3 message is appended to the file destination
    */
    if (defined('ADODB_ERROR_LOG_TYPE')) {
        $t = date('Y-m-d H:i:s');
        if (defined('ADODB_ERROR_LOG_DEST'))
            error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST);
        else
            error_log("($t) $s", ADODB_ERROR_LOG_TYPE);
    }


    //print "<p>$s</p>";
    trigger_error($s,ADODB_ERROR_HANDLER_TYPE); 
}

  John Mwaniki /   29 Nov 2021

I have seen it severally where PHP mysqli_connect() database connection worked perfectly well for months or years, then all of a sudden it stops working. On enabling PHP error reporting, or on checking for errors in the error_log file in the cPanel, you find the error below:

PHP Fatal error: Uncaught Error: Call to undefined function mysqli_connect() in /home/username/public_html/…

This can create a great inconvenience and affect your database-driven website negatively especially if you don’t visit it regularly.

As you can see from the error above, PHP doesn’t recognize the mysqli_connect() function. This usually happens when some changes are made on the server that affects the mysqli extension.

There are 2 ways of connecting PHP to MySQL database:

  • MySQLi extension
  • PDO (PHP Data Objects) extension

Earlier versions of PHP(before version 5) used the MySQL extension which became deprecated in 2012 and was replaced with the MySQLi extension. The «i» in MySQLi stands for improved.

MySQLi extension supports both object-oriented and procedural ways of connecting to the database.

Procedural way

$conn = mysqli_connect("hostname", "username", "password", "database");

Object-Oriented way

$conn = new mysqli("hostname", "username", "password", "database");

All you have to do is to replace the values in quotes above with your real database credentials where the hostname in most cases will be «Localhost», though it may differ in some instances. The «username» is the username of the user assigned to the database, «password» is the password of that user, and «database» is the name of the database you are connecting to.

Either of the above methods will enable communication between PHP and the MySQL database server to take place.

When the error above occurs, the first thing you should do is to check if the PHP MySQL extension module is being loaded.

To do so, simply echo the phpinfo() function. It will show you all the information about your installed PHP version.

<?php
echo phpinfo();
?>

On the PHP information page, scroll down to the section titled «mysqli». You should be able to see the enabled MySQLi library in the Client API library version row as shown below:

phpinfo() mysqli information

There are two libraries for connecting PHP to MySQL database:

  • MySQL native driver for PHP (mysqlnd)
  • MySQL Client Library (libmysql)

The extensions(mysqli or PDO_MySQL) can either use the mysqlnd or libmysql library to connect from PHP to MySQL.

The MySQL Client Library is a general-purpose client library, meaning it can be used across different languages. On the other hand, mysqlnd library is highly optimized for and tightly integrated into PHP. The mysqlnd library is the default library for PHP 5.4 and later versions. MySQL recommends using the MySQL native driver for PHP (mysqlnd) together with ext/mysqli or PDO_MySQL.

In our case from the above screenshot, you can see that mysqlnd is the enabled driver.

We can now scroll more down to the section titled «mysqlnd» for more information as in the screenshot below:

mysqlnd information in phpinfo()

From the last row(API Extensions) of the above table, you can see that both mysqli and pdo_mysql extensions are enabled. This way the database connection works perfectly with no error.

In the case where the database connection results in the undefined function mysqli_connect() error, then you will find that the phpinfo() page doesn’t have the «mysqli» and the «mysqlnd» sections.

The solutions to undefined function mysqli_connect() error

1. Upgrading to a later PHP version

In most of the cases that this has happened, I have found that changing PHP to a later version has always worked and fixed the issue. Let’s say for example your current PHP version is 7.0, you can change to a later PHP version such as PHP 7.4 or 8.0.

This personally fixed the issue for me the last time it happened to one of the websites I manage.

Here is a brief guide on how to check your website PHP version -> 3 Simple ways of checking your website PHP version

And here is a simple guide for upgrading the PHP version -> How to change the PHP version in cPanel

2. Changing mysqli_connect to new mysqli

Try changing your database connection from procedural to OOP, ie. change replace mysqli_connect to new mysqli. Though it is the OOP way, it doesn’t mean that you will have to change anything else in your PHP code. I have seen it severally where making this change fixed the error.

3. Installing the PHP MySQL extension

If you host the website by yourself, you can simply install the php-mysqli extension on Ubuntu by use of the command below:

sudo apt install php-mysqli

You will then be required to restart the apache server with the command below for it to take effect.

sudo service apache2 restart

4. Adding or uncommenting the line «extension=php_mysql.dll» in the php.ini file

If you host the server yourself, open the php.ini file and remove the semicolon in front of the line below:


;extension=php_mysqli.dll

So that it will be like below:


extension=php_mysqli.dll

If this line doesn’t exist, simply add it. After making the changes, save and restart your Apache server.

If your website is hosted by a hosting provider/company, and upgrading to a later PHP version or changing mysqli_connect to new mysqli doesn’t seem to work for you, simply contact the host with the error message and they will fix it for you.

That’s all for this article. It’s my hope that it was helpful for you.

Uncaught error: Call to undefined function mysql_connect()

In this article, we will learn about the uncaught error “Uncaught error: Call to undefined function mysql_connect()”.

This error is encountered when we try to use mysql_connect() functions of php5 in php7.

PHP Fatal error: Uncaught Error: Call to undefined function mysql_connect() error is raised because mysql_* functions are completely removed from PHP 7, it previously got deprecated in PHP 5.5, but now it is completely removed.

The older MySQL function are removed due to the following reasons:

  1. Do not work on Object-Oriented concept
  2. Won’t support transactions and prepared statements
  3. Insecure

How to fix Undefined Function Mysql_connect() error

There are four methods to fix undefined function Mysql_connect() error:

  • Use MySQLi or PDO
  • Connecting to Mysql with the Pdo Object Is Pretty Straight Forward
  • Connecting to MySQL with MySqli Connection Object
  • Rollback to Older PHP 5, update your code to mysqli or PDO and then upgrade to PHP7

1. Use MySQLi or PDO

mysqli_connect()

Instead of usingmysql_connect()” we should use “mysqli_connect()” in php7 to avoid this error.

Example: $mysql = new mysqli(«localhost»,»root»,»password»,»DB_name»);

PDO(php database objects):

Example:$pdo = new PDO(‘mysql:host=localhost;dbname=database_name ‘, ‘username’, ‘password’);

//pdo requires a valid database to establish connection. If the database is not specified then it throws an exception.

2. Connecting to Mysql with the Pdo Object Is Pretty Straight Forward

$user = 'root'; // Mysql
User$password = ''; // Mysql Password
$server = 'localhost'; // Mysql Host
$database = 'my_database'; // Mysql Databse
// PDO Connection string
$pdo = new PDO("mysql:host=$server;dbname=$database", $user, $password);

3. Connecting to MySQL with MySqli Connection Object

$con = mysqli_connect('localhost', 'username', 'password', 'database');

4. Rollback to Older PHP 5, update your code to mysqli or PDO and then upgrade to PHP7

Best Practice

Use MySQLi wrapper and object mapper with prepared statements.

Example: User PHP-MySQLi-Database-Class https://github.com/ThingEngineer/PHP-MySQLi-Database-Class

By using MySQLi with prepare statement will secure your database connection  & in future, if need to upgrade your Database to some other version, you won’t have to update all you mysql connection string in all pages.

This package is free and customizable; you can upgrade by creating your Class & functions.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Fatal error microsoft basic render driver detected as primary device crossout
  • Fatal error maxretry is not a valid variable name for this driver
  • Fatal error maximum function nesting level of 100 reached aborting in
  • Fatal error math h no such file or directory
  • Fatal error mapping iso please check if file is present and defragmented

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии