2016-07-30 2 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 내가 어떤 이름을 제공하지 않은, 그리고 index.php 파일에서 개체를 만드는 암호가, 구조물 살인해서는 안 때문에

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

} 

스크립트 및 내가 MySQL에 연결할 수 없었다고 말했습니다. 그러나 $ db_username 또는 $ db_password 변수에 무엇을 제공하더라도 로그인 정보가 올바른지 여부에 관계없이 Connect() 메서드는 항상 true를 반환합니다. 결코 거짓을 반환하지 않습니다. 왜 확실하지 않은 Im. 어떤 도움을 주시면 감사하겠습니다.

감사합니다.

+5

정지 **'mysql_로를 제거 ** 사용되지 않으며 PHP7의로 사용을 사용할 수 있습니다 * '함수. PDO로 마이그레이션하고 Prepared Statements를 사용하십시오. –

+0

조언을 주셔서 감사하지만, 내가 왜 코드가 작동하지 않는지 알고 싶습니다. –

+0

자신의 DatabaseConnect 클래스를 만드는 대신 PDO를 사용해야합니다 ... –

답변

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; 
    } 
관련 문제