所以我尝试使用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。它永远不会返回虚假。我不知道为什么。任何帮助将不胜感激。
谢谢!
答案 0 :(得分:0)
mysql_connect()
在PHP 5.5.0中已弃用,在PHP 7.0.0中已被删除。
你可以用
PDO :: __ construct()
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;
}