I have a php script that changes a database when the page is requested. Here is the php:
That error occurs because $con
is not being correctly initialized (probably because, as many servers do, MySQL is restricted to local connections only). That's why you get the error after mysqli_connect()
.
If you can't connect to MySQL, you should kill the script or show an error message, without trying to query an empty object.
One alternative:
if (!$con) {
echo "Error connecting to MySQL: " . mysql_connect_error();
die; // You can kill the script here
}
Another one:
if (!$con) { // Error connecting
echo "Error connecting to Mysql: " . mysql_connect_error();
// Another message here if you want
}
else { // Connection ok
mysqli_query( /* bla bla bla */ );
// ...
}
Note that I'm verifying the $con
value (if null
or not) instead of mysqli_connection_errno()
, because it won't return a value if the connection variable is not well defined.
This kind of verification is taken directly from mysqli_connect() documentation examples.