Php OOP-通过_构造连接到数据库

Php OOP-通过_构造连接到数据库,php,Php,我是OOP新手,正在努力学习。所以请原谅我的无知。我正在尝试连接mysql并测试连接是否成功,我使用的是if-else条件 令人惊讶的是,mysql\u connect总是返回true,即使传递了错误的登录凭据。现在我想弄明白为什么会这样,花了大约20分钟后,我放弃了。因此,我来到这里寻求社区的帮助。这是我的密码: class test { private $host = 'localhost'; private $username = 'root2'; // using wro

我是OOP新手,正在努力学习。所以请原谅我的无知。我正在尝试连接mysql并测试连接是否成功,我使用的是
if-else
条件

令人惊讶的是,
mysql\u connect
总是返回true,即使传递了错误的登录凭据。现在我想弄明白为什么会这样,花了大约20分钟后,我放弃了。因此,我来到这里寻求社区的帮助。这是我的密码:

class test
{
    private $host = 'localhost';
    private $username = 'root2'; // using wrong username on purpose
    private $password = '';
    private $db = 'dummy';
    private $myConn;    

    public function __construct()
    {
       $conn = mysql_connect($this->host, $this->username, $this->password);
       if(!$conn)
       {
        die('Connection failed'); // this doesn't execute
       }
       else
       {
        $this->myConn = $conn;
        $dbhandle = mysql_select_db($this->db, $this->myConn);
        if(! $dbhandle)
        {
            die('Connection successful, but database not found'); // but this gets printed instead
        }
       }        
    }
}

$test = new test();

请不要使用
mysql.*
函数,原因有很多很多-。它们也已弃用,将被删除

你会过得更好

另外,我强烈建议将此数据库代码抽象为一个专用的数据库类,必要时可以将其注入

关于主题:

这段代码似乎对我有用,你试过
var\u dump
ing
$conn
?该用户是否具有正确的权限


我还希望您没有一个允许
root
无密码登录的生产服务器

忽略使用mysql_*函数而不是mysqli或pdo函数的事实,您应该在OOP代码中使用异常,而不是die()。除此之外,我无法复制您的问题-可能是您的mysql服务器设置为接受无密码登录

class test
{
    private $host = 'localhost';
    private $username = 'root2'; // using wrong username on purpose
    private $password = '';
    private $db = 'dummy';
    private $myConn;    

    public function __construct()
    {
       // returns false on failure
       $conn = mysql_connect($this->host, $this->username, $this->password);
       if(!$conn)
       {
        throw new RuntimeException('Connection failed'); // this doesn't execute
       }
       else
       {
        $this->myConn = $conn;
        $dbhandle = mysql_select_db($this->db, $this->myConn);
        if (!$dbhandle)
        {
            throw new RuntimeException('Connection successful, but database not found'); // but this gets printed instead
        }
       }        
    }
}

try {
$test = new test();
} catch (RuntimeException $ex) {
    die($ex->getMessage());
}

您的问题与OOP完全无关,请尝试使用this
$conn=mysql\u connect($this->host,$this->username,$this->password)或die(mysql\u error())die
(mysql\u select\u db)