[英]Check if database credentials are valid?
I'm building a small self-hosted app which requires database usage. 我正在构建一个需要数据库使用的小型自托管应用程序。 I'd like to validate that the user inputted database credentials are valid, before they're actually saved. 我想验证用户输入的数据库凭据是否有效,然后再进行实际保存。 What could I do to check whether or not a connection is valid, would it be as simple as? 我该怎么做才能检查连接是否有效,是否会如此简单?
$conn = mysql_connect($db_name, $db_user, $db_pass); mysql_select_db($db_name);
if($conn) {
mysql_close($conn);
// Do stuff if connection is valid
} else {
mysql_close($conn);
// Do stuff if connection is invalid
}
Would I even need to close the connection if it's invalid? 如果连接无效,我什至需要关闭连接吗? (Within the else{}
statement. I took a look at mysql_ping()
but it doesn't really seem to be what I need. (在else{}
语句中。我看了mysql_ping()
但这似乎并不是我真正需要的。
如果凭据无效,则无需关闭连接,因为它不会首先打开。
also frequently used is 'die' which allows you to print a message before stopping execution of the script: 还经常使用的是“ die”,它允许您在停止执行脚本之前打印一条消息:
$conn = mysql_connect($db_name, $db_user, $db_pass) or die('the error message');
or for debugging purposes the following is frequently used: 或出于调试目的,经常使用以下内容:
$conn = mysql_connect($db_name, $db_user, $db_pass) or die(mysql_error());
which will print the mysql error such as a warning about wrong credentials 这将打印mysql错误,例如关于错误凭证的警告
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.