1
所以我试图在PHP OOP中使用我的手,并且我试图做一个简单的mysql数据库连接类。这是我的代码,然后我会解释发生了什么。PHP OOP:当错误信息通过时,mysql_connect不会返回false
的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。它永远不会返回错误。我不知道为什么。任何帮助,将不胜感激。
谢谢!
停止使用**过时并且PHP7的去除**'mysql_ * '功能。迁移到PDO并开始使用准备好的语句。 –
感谢您的建议,但我想弄清楚为什么我的代码不工作。 –
您应该使用PDO而不是创建您自己的DatabaseConnect类... –