簡體   English   中英

PHP OOP:mysql_connect在傳遞錯誤信息時不返回false

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

所以我正在嘗試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。 它永遠不會返回虛假。 我不知道為什么。 任何幫助,將不勝感激。

謝謝!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM