Heriberto Nol Heriberto Nol - 3 months ago 22
PHP Question

error when runing my code in remote server: User root has exceeded the 'max_user_connections'

[Im using hostinger as host]
I have a webpage where i show the results of a query, it works locally but when i uploaded it to the web i get an error message:


Ha habido un error en la linea: 6 Error: SQLSTATE[42000] [1226] User
'u749120824_root' has exceeded the 'max_user_connections' resource
(current value: 3) Fatal error: Call to a member function prepare() on
a non-object in /home/u749120824/public_html/pags/ver_usuarios.php on
line 18


Here are some screen shots
Localhosted
Localhost

Online Hosted
Online Host
My code:

class ComprobarUsuario extends Conexion{
public function ComprobarUsuario(){
parent::__construct();
}
public function Comprobar($nombre){
$sqlCU="SELECT * FROM admins WHERE NOMBRE=:nombre_usuario";
$resultCU=$this->con->prepare($sqlCU);
$resultCU->execute(array(":nombre_usuario"=>$nombre));
$NresultadosCU=$resultCU->fetch(PDO::FETCH_ASSOC);
if($NresultadosCU!=0){
return "admin";
}
}
}


Connection class:

class Conexion{
protected $con;
public function Conexion(){
try{
$this->con=new PDO("mysql:host=localhost;dbname=marisol","root","");
$this->con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$this->con->exec("SET CHARACTER SET utf8");
return $this->con;
}
catch(PDOException $e){
echo "Ha habido un error en la linea: " . $e->getLine() . " Error: " . $e->getMessage();
}
}
}

Answer

The problem is that your code creates a new connection for every new instance of ComprobarUsuario. If you use similar approach for other queries your application will exceed the limitation very quickly. The solution is to create one shared connection for all sub-classes.

class Conexion{
        protected static $con;
        public function Conexion(){
            try{
                if (!self::$con) {
                    self::$con=new PDO("mysql:host=localhost;dbname=marisol","root","");
                    self::$con->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
                    self::$con->exec("SET CHARACTER SET utf8");
                    return self::$con;
                }
            } catch(PDOException $e){
                echo "Ha habido un error en la linea: " . $e->getLine() . " Error: " . $e->getMessage();
            }
        }
    }
Comments