A migration from Oracle to MySQL was recently done at my work, so when I change the connection to the DB in one of my projects it throws me errors when trying to log in.
The connection code is as follows:
class Target
{
public static function Conectar()
{
try
{
$conexion = new PDO('mysql:host=10.2.3.5;port=3306;dbname=BI_TGT;charset=UTF8','bi_tgt','password');
}
catch(Exception $e)
{
$e->getMessage();
}
return $conexion;
}
}
The login code is as follows:
require_once("conexion.php");
class Model
{
public static function ingresoUsuarioModel($datosModel, $tabla)
{
$stmt = Target::Conectar()->prepare("select ba, password, nombre from $tabla where ba = :usuario");
$stmt->bindParam(":usuario", $datosModel['usuario'], PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}
}
It throws me the following errors:
Notice : Undefined variable: connection Fatal error Uncaught Error:Call to a member function prepare() on null
The problem arises when trying to connect to the server where mysql is hosted because if I use the same code but with the connection to oracle it works perfect, the connection data to mysql is correct I don't know what is happening, I can't find the way to solve the problem, if anyone can help me it would be great.
According to the PHP Manual (bold is mine):
What is happening now is that this is failing, raising an Exception:
Therefore,
$conexion
is not defined and you have aUndefined variable
. If the connection creation did not fail, no Exception would be raised, the variable$conexion
would be created and in that case the return set outside wouldtry
work. But this should work in both cases, not just when the connection happens.The correct way to write your code (regardless of whether the connection works or not) would be the following:
Here the code will return either the valid connection or
null
and in the call you can (must) check the state of the connection before using it, thus writing code that avoids the naivety problem when programming:Why it is not connected is another matter. You should check the way you are passing the connection DSN, which varies depending on the type of database. You must also verify that the credentials (username, password) are correct. Example 1 of the PHP Manual shows you how to connect to a MySQL database (although some of that data might vary, depending on your context).
Cedano's excellent answer, helped me to remove the problem with the undefined variable, indeed it was returning the wrong response in my
try
, but I still couldn't connect to the database.So printing the error that captured $e, it threw the following:
Doing some research I found this post: Solution Which effectively helped me to solve my connection problem.
I just ran that command:
And the connection to the database was made without problems.