I am trying to pass a mysqli connection to a class for it to use prepared statements. However, I am missing something and it is not working. What a i doing wrong?
The following code outputs “no”
index.php
$db_host = 'localhost';
$db_name = 'my_database';
$db_user = 'my_user';
$db_password = 'my_password';
$con = new mysqli($db_host,$db_user,$db_password,$db_name);
if (mysqli_connect_errno())
{
die(mysqli_connect_error());
}
$obj = new Obj( $con );
obj.php
Class Obj
{
public function __construct( mysqli $con )
{
$sql = "SELECT * FOM myTable";
if($con->prepare( $sql ))
{
echo "yes";
}
else
{
echo "no";
}
}
}
If you had failed to pass a mysqli connection to your class, you’d be getting a fatal error on this line:
But not only the constructor starts running fine, you can even access a class method:
To sum up, all that happens is that
mysqli::prepare()returnsfalsebecause there was an error while preparing the SQL statement. I’m not familiar with mysql but you can probably get the exact error message with mysqli::$error_list or mysqli::$error:If
SELECT * FOM myTableis the actual query, I suppose it’s a simple syntax error since you’ve misspeltFROM.