2016-07-30 65 views
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。它永远不会返回错误。我不知道为什么。任何帮助,将不胜感激。

谢谢!

+5

停止使用**过时并且PHP7的去除**'mysql_ * '功能。迁移到PDO并开始使用准备好的语句。 –

+0

感谢您的建议,但我想弄清楚为什么我的代码不工作。 –

+0

您应该使用PDO而不是创建您自己的DatabaseConnect类... –

回答

0

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; 
    }