简体   繁体   中英

Check if connected to MySQL and Database

I'm having a problem with a PHP-Script, where I want to check, if the MySQL-Logindata are valid. I found somewhere the mysql_ping() function, but it doesn't work as it should, because it returns in every case true , even if the inserted data are totally wrong. How do I solve it?

$verbindung = mysql_connect($_POST["mysql_host"], $_POST["mysql_user"],
$_POST["mysql_pwd"]);

if (!mysql_ping($verbindung)) {
    $break = true;
}
else {
    // Check here also via SQL, if database $_POST["mysql_db"] exists
}

This already is more complex than it needs to be and should do the correct thing. The reason why all usernames work quite likely is that MySQL by default has an anonymous user ''@'localhost' which accepts any username. Probably you want to remove that user. ( DROP USER ''@'localhost' , be sure you can login as other user before doing that, use SHOW GRANTS to see which user you are using)

For simplification mind that the connect cal will fail if there is something wrong, so you wont need that ping call. ping can be used if you have a longer living connection and you want to check whether the connection is still working.

A simple form for the check might look like this:

$verbindung = new mysqli($_POST["mysql_host"], $_POST["mysql_user"], $_POST["mysql_pwd"]);
if (!$verbindung) {
    echo "Wrong settings";
}

Mind that I changed to the mysqli insterface. the old mysql extension in PHP providing the mysql_* functions is deprecated and shouldn't be used anymore.

I actually found out a nicer solution with the mysqli_connect_errno() function and a requirement of inputs from the database name and the user name.

$verbindung = @mysqli_connect((!empty($_POST["mysql_host"]) ? $_POST["mysql_host"] : 'localhost'),
    $_POST["mysql_user"], $_POST["mysql_pwd"], $_POST["mysql_db"]);

if (mysqli_connect_errno() || empty($_POST["mysql_user"]) || empty($_POST["mysql_db"])) {
    $break = true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM