简体   繁体   English

PHP OOP:mysql_connect在传递错误信息时不返回false

[英]PHP OOP: mysql_connect not returning false when wrong information passed

So i'm trying my hand in PHP OOP, and i'm trying to make a simple mysql database connect class. 所以我正在尝试PHP OOP,我正在尝试创建一个简单的mysql数据库连接类。 Here is my code and then i'll explain what's going on. 这是我的代码,然后我会解释发生了什么。

index.php 的index.php

<?php

// Connect to Database Class
require_once('../libs/DB.class');
$connection = new DatabaseConnect('localhost', '', '');

DB.class 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;
    }
  }

}

Since i have supplied no username, and no password when making the object in the index.php file, the construct should be killing the script and saying that i have not been able to connect to mysql. 由于我在index.php文件中创建对象时没有提供用户名和密码,因此该构造应该杀死脚本并说我无法连接到mysql。 However, no matter what i supply to the $db_username or $db_password variables, whether the login information is correct or not, the Connect() method is ALWAYS returning true. 但是,无论我向$ db_username或$ db_password变量提供什么,无论登录信息是否正确,Connect()方法总是返回true。 it never returns false, ever. 它永远不会返回虚假。 Im not sure why. 我不知道为什么。 Any help would be appreciated. 任何帮助,将不胜感激。

Thanks! 谢谢!

mysql_connect() was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. mysql_connect()在PHP 5.5.0中已弃用,并且已在PHP 7.0.0中删除。 you can use 您可以使用

PDO::__construct() PDO :: __结构()

try {
     $dbh = new PDO($db_host, $db_username, $db_password);
    } catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage();
    }

mysqli_connect() mysqli_connect()

if(!mysqli_connect($db_host, $db_username, $db_password)) {
      return false;
    } else {
      return true;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM