How to fix Deprecated mysql_connect in an install file?

0

I could help someone with this error (Deprecated mysql_connect), I explain: I have an old script, this contains a typical installation interface. Everything is fine until the final installation step where I get these two errors:

  

Deprecated: mysql_connect (): The mysql extension is deprecated and   will be removed in the future: use mysqli or PDO instead in   /home/site/public_html/test/install/database.php on line 14

     

Warning: Can not modify header information - headers already sent by   (output started at   /home/site/public_html/test/install/database.php:14) in   /home/site/public_html/test/install/install.php on line 105

The batabase.php file contains:

<?php
include 'include/db.php';

class MYSQL_DB {
    var $connection;
    function MYSQL_DB(){
        $this->connection = mysql_connect(HOST, USER, PASS) or die(mysql_error());
        mysql_select_db(NAME, $this->connection) or die(mysql_error());
    }
    function mysql_exec_batch ($p_query, $p_transaction_safe = true){
        if($p_transaction_safe){
            $p_query = 'START TRANSACTION;'.$p_query.'; COMMIT;';
        };
        $query_split = preg_split ("/[;]+/", $p_query);
        foreach($query_split as $command_line){
            $command_line = trim($command_line);
            if($command_line != ''){
                $query_result = mysql_query($command_line);
                if($query_result == 0){
                    break;
                };
            };
        };
        return $query_result;
    }
    function query($query){
        return mysql_query($query, $this->connection);
    }
};
$database = new MYSQL_DB;
?>

The install.php file contains from line 99 to 109 (of the error):

function ImportDB(){
        global $database;
        $str = file_get_contents('include/database.sql');
        $str = preg_replace("'%PREFIX%'", 'alpha', $str);
        $result = $database->mysql_exec_batch($str);
        if($result){
            header('Location: index.php?step=5');
        }else{
            header('Location: index.php?step=3&error=1');
        }
    }
    
asked by Carla 08.12.2017 в 14:54
source

2 answers

0

The message tells you clearly. The mysql_connect() function used on line 14 of your database.php is disapproved for security reasons. You should update a large part of your code, since it is currently very vulnerable to attacks. For example, you must replace all the functions you use for the connection, and instead of using mysql you must use mysqli .

For the case of mysql_connect() you must do it in the following way:

$this->connection = mysqli_connect( 'host', 'username', 'password');

You must also replace mysql_select_db() in the following way:

$database = mysqli_select_db($link, 'database');

And so with all the other functions disapproved. I suggest you look for information about it. You can read how to do it here or here .

You can see the use of mysqli_connect() here

You can see the use of mysqli_select_db() here

    
answered by 08.12.2017 в 15:13
0

You have multiple options,

You can turn off error messages

// al principio de cada archivo pon lo siguiente
error_reporting(0);

You can, through the command line, adapt the function ImportDB :

<?php
$comando = 'mysql -u usuario -p contraseña base_a_cargar < archivo.sql';

$ultima_linea = system($comando, $retornoCompleto);

print_r( $ultima_linea );
print_r( $retornoCompleto );

You can migrate the code to PDO or MYSQL, example MySQLi, simply adapt it to your needs:

// Establecemos la conexiin
$mysqli = new mysqli('localhost', 'mi_usuario', 'mi_contraseña', 'mi_bd');

// verificamos que sea correcta 
if ($mysqli->connect_error) {
    die('Error de Conexión (' . $mysqli->connect_errno . ') '
        . $mysqli->connect_error);
}

// Se asume conexión en $mysqli

// Recuperamos el fichero como un string
$fileSQL = file_get_contents('ruta_fichero.sql');


/* Ejecutar consulta multiquery */
if ($mysqli->multi_query($fileSQL)) {
    do {
        /* Almacenar y mostrat juego de resultados */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_assoc()) {
                print_r($row);
                echo "<br/>";
            }
            $result->free();
        }
        /* mostrar divisor */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }
      // Avanzar al siguiente resultado
    } while ($mysqli->next_result());
}

/* cerrar conexión */
$mysqli->close();

Since PHP version 5.5.0, the functions of original mysql are declared obsolete and issue a E_DEPRECATED error, in PHP 7.0.0 have been deleted.

  • The first option is not recommended, even if you are only going to use the script once and in a controlled way to be feasible.

  • The second option can be dangerous and must be used with great care since it is a command line, we must guarantee that only what we want will be executed and that there will be no option for a malicious user can run anything.

  • The third option is the most recommended, migrate to MySQLi or PDO is what you should do, in this case I would bet on MySQLi since PDO does not support 100% multiple sentences and could give you problems.

  • An example with your connection class trying sideways as little as possible.

    <?php
    ini_set('display_errors', '1');
    error_reporting(E_ALL);
    
    class MYSQL_DB {
        protected $connection;
        public $log = array();
    
        // adaptamos el constructor
        function __construct()
        {
            // cambiamos la conexión a mysqli
            $this->connection = new mysqli('localhost', 'mi_usuario', 'mi_contraseña', 'mi_bd');
    
            if ($this->connection->connect_error) {
                // si falla la conexion finalizamos el script
                die('Error de Conexión (' . $this->connection->connect_errno . ') '. $this->connection->connect_error);
            }
            $this->log[] = 'Conexion ok';
        }
    
        // adaptamos el método mysql_exec_batch
        function mysql_exec_batch ($p_query, $p_transaction_safe = true)
        {
            $this->log[] =  $p_query;
            // declaramos variable para los resultados 
            $query_result = Array();
    
            if($p_transaction_safe){
                    // comprobamos si se pide transacciones
                if($this->connection->begin_transaction(MYSQLI_TRANS_START_READ_WRITE)) {
                    $this->log[] = 'Transeccion iniciada';
                } else {
                    $this->log[] = 'Error en transeccion (' . $this->connection->errno . ') '. $this->connection->error;                
                }
            }
    
            /* Comprobamos consulta multiquery  correctamente */
            if ($this->connection->multi_query($p_query)) {
                $this->log[] =  'mutiquery ok';            
                // recorremos los resultados de la consulta
                $i = 0; // contador
                do {
                    /* Almacenar y mostrat juego de resultados */
                    if ($result = $this->connection->store_result()) {
                        while ($row = $result->fetch_assoc()) {
                             // almacenamos los resultados
                            $query_result[$i][] =  $row;
                        }
                        // Liberamos el resultado
                        $result->free();
                    }
    
                    if ($this->connection->more_results()) {
                        ++$i; // incrementamos contador
                    } else {
                        $this->log[] = 'Se recorrieron todos los resultados';            
                        break;
                    }
    
                // Avanzar al siguiente conjunto de resultados
                } while ($this->connection->next_result());
            } else {
                $this->log[] = 'Error en multiquery (' . $this->connection->errno . ') '. $this->connection->error;
            }
    
            if($p_transaction_safe){
                // hacemos commit
                if($this->connection->commit()) {
                    $this->log[] = 'Commit ok';
                } else {
                    $this->log[] = 'Error en commit (' . $this->connection->errno . ') '. $this->connection->error;
                }
            }
    
            // retornamos el Array de resultados
            $this->log[] = 'Return result';
            $this->log['resultados'] = $query_result;
            return $query_result;
        }
    
    }
    
    $database = new MYSQL_DB;
    
    
    $sql = '
    DROP TABLE IF EXISTS tabla;
    
    CREATE TABLE tabla(TABLA_ID INT UNSIGNED NOT NULL);
    
    INSERT INTO tabla VALUES(123456789);
    INSERT INTO tabla VALUES(284561);
    
    SELECT * FROM tabla;
    SELECT * FROM tabla;
    ';
    
    
    //$str = file_get_contents('include/database.sql');
    $str = preg_replace("'%PREFIX%'", 'alpha', $sql);
    $result = $database->mysql_exec_batch($str);
    if($result){
        print_r($result);
    }else{
        print_r($result);
    }
    
    echo '<pre>';
        print_r($database->log);
    echo '</pre>';
    
        
    answered by 08.12.2017 в 15:58