[英]PHP OOP: mysql_connect not returning false when wrong information passed
所以我正在尝试PHP OOP,我正在尝试创建一个简单的mysql数据库连接类。 这是我的代码,然后我会解释发生了什么。
的index.php
<?php
// Connect to Database Class
require_once('../libs/DB.class');
$connection = new DatabaseConnect('localhost', '', '');
DB.class
<?php
class DatabaseConnect {
// When class is called, make sure to grab the host, username, and password to connect to the MySQL Database
public function __construct($db_host, $db_username, $db_password) {
echo 'Attempting Connection . . . <br>';
// If the method Connect() doesn't return true then kill the script and say you done messed up... or tell the user that connection has been successful
if(!$this->Connect($db_host, $db_username, $db_password)) {
die("Connection to $db_host failed");
} else {
echo "Connected to $db_host";
}
}
// When the Connect method is called from the construct, grab the passed variables, try to connect, and return true or false
public function Connect($db_host, $db_username, $db_password) {
if(!mysql_connect($db_host, $db_username, $db_password)) {
return false;
} else {
return true;
}
}
}
由于我在index.php文件中创建对象时没有提供用户名和密码,因此该构造应该杀死脚本并说我无法连接到mysql。 但是,无论我向$ db_username或$ db_password变量提供什么,无论登录信息是否正确,Connect()方法总是返回true。 它永远不会返回虚假。 我不知道为什么。 任何帮助,将不胜感激。
谢谢!
mysql_connect()
在PHP 5.5.0中已弃用,并且已在PHP 7.0.0中删除。 您可以使用
PDO :: __结构()
try {
$dbh = new PDO($db_host, $db_username, $db_password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
mysqli_connect()
if(!mysqli_connect($db_host, $db_username, $db_password)) {
return false;
} else {
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.