【问题标题】:OOP php error in database connection数据库连接中的 OOP php 错误
【发布时间】:2012-08-18 02:35:03
【问题描述】:

我是 OOP 的新手,所以我正在学习教程。所以它使用以下代码连接到数据库,但在我的情况下它没有连接

数据库.php

<?php
require_once("config.php");

class MySQLDatabase {

    private $connection;

  function __construct() {
    $this->open_connection();
  }

    public function open_connection() {
        $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
        if (!$this->connection) {
            die("Database connection failed: " . mysql_error());
        } else {
            $db_select = mysql_select_db(DB_NAME, $this->connection);
            if (!$db_select) {
                die("Database selection failed: " . mysql_error());
            }
        }
    }

    public function close_connection() {
        if(isset($this->connection)) {
            mysql_close($this->connection);
            unset($this->connection);
        }
    }

    public function query($sql) {
        $result = mysql_query($sql, $this->connection);
        $this->confirm_query($result);
        return $result;
    }

    public function mysql_prep( $value ) {
        $magic_quotes_active = get_magic_quotes_gpc();
        $new_enough_php = function_exists( "mysql_real_escape_string" ); // i.e. PHP >= v4.3.0
        if( $new_enough_php ) { // PHP v4.3.0 or higher
            // undo any magic quote effects so mysql_real_escape_string can do the work
            if( $magic_quotes_active ) { $value = stripslashes( $value ); }
            $value = mysql_real_escape_string( $value );
        } else { // before PHP v4.3.0
            // if magic quotes aren't already on then add slashes manually
            if( !$magic_quotes_active ) { $value = addslashes( $value ); }
            // if magic quotes are active, then the slashes already exist
        }
        return $value;
    }

    private function confirm_query($result) {
        if (!$result) {
            die("Database query failed: " . mysql_error());
        }
    }

}

$database =& new MySQLDatabase();
$db =& $database;

?>

config.php

<?php

// Database Constants                             
defined('DB_SERVER') ? null : define("DB_SERVER", "localhost");
defined('DB_USER')   ? null : define("DB_USER", "oop_project");
defined('DB_PASS')   ? null : define("DB_PASS", "");
defined('DB_NAME')   ? null : define("DB_NAME", "oop_project");

?>

函数.php

<?php

function strip_zeros_from_date( $marked_string="" ) {
  // first remove the marked zeros
  $no_zeros = str_replace('*0', '', $marked_string);
  // then remove any remaining marks
  $cleaned_string = str_replace('*', '', $no_zeros);
  return $cleaned_string;
}

function redirect_to( $location = NULL ) {
  if ($location != NULL) {
    header("Location: {$location}");
    exit;
  }
}

function output_message($message="") {
  if (!empty($message)) { 
    return "<p class=\"message\">{$message}</p>";
  } else {
    return "";
  }
}

?>

当我要测试连接时 我收到了这些错误。

Deprecated: Assigning the return value of new by reference is deprecated in J:\xampp\htdocs\oop_project\includes\database.php on line 60

Deprecated: Assigning the return value of new by reference is deprecated in J:\xampp\php\PEAR\Config.php on line 80

Deprecated: Assigning the return value of new by reference is deprecated in J:\xampp\php\PEAR\Config.php on line 166

Notice: Use of undefined constant DB_SERVER - assumed 'DB_SERVER' in J:\xampp\htdocs\oop_project\includes\database.php on line 13

Notice: Use of undefined constant DB_USER - assumed 'DB_USER' in J:\xampp\htdocs\oop_project\includes\database.php on line 13

Notice: Use of undefined constant DB_PASS - assumed 'DB_PASS' in J:\xampp\htdocs\oop_project\includes\database.php on line 13

Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in J:\xampp\htdocs\oop_project\includes\database.php on line 13

Warning: mysql_connect() [function.mysql-connect]: [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. (trying to connect via tcp://DB_SERVER:3306) in J:\xampp\htdocs\oop_project\includes\database.php on line 13

Warning: mysql_connect() [function.mysql-connect]: php_network_getaddresses: getaddrinfo failed: No such host is known. in J:\xampp\htdocs\oop_project\includes\database.php on line 13
Database connection failed: php_network_getaddresses: getaddrinfo failed: No such host is known.

我该如何纠正这个...?谢谢。

【问题讨论】:

  • 最好的解决方案是不使用古代类。写一个新的不会比修复你拥有的要多得多 - 但它可能会更好/更干净!
  • 忘掉这句话,学习 PDO
  • 大声笑/\你把我都搞砸了:)
  • 感谢您的想法。但是你能解释一下吗,我对这些东西很陌生,对此一无所知。
  • 这是一个可怕的例子,它只会给你带来麻烦。在它成为应用程序的一些核心组件之前,趁你还有机会把它扔掉。 @LawrenceCherone 有一个很棒的基于 PDO 的答案,您应该使用它。您不应在任何新应用程序中使用mysql_query。这是 1990 年代已弃用的界面,很难正确使用,并可能导致各种可怕的SQL injection bugs

标签: php mysql database oop


【解决方案1】:

“已弃用”警告是因为您正在使用

$database =& new MySQLDatabase();

替换为

$database = new MySQLDatabase();

这些通知是因为在您尝试实例化类(新的 MySQLDatabase)之前似乎没有定义常量(DB_SERVER,...)。确保 config.php 之前已加载。 其他警告与这些相同的问题有关。 config.php 的包含实际上是包含 J:\xampp\php\PEAR\Config.php 不是你的本地配置文件。

【讨论】:

  • 是的,支持我击败它。
  • 是的!我知道我刚刚将名称 config.php 更改为 config2.php,现在它运行良好。但这是怎么发生的?
  • 发生这种情况是因为对于 include('file.php') 之类的东西,PHP 会搜索 php.ini 中定义的包含路径
【解决方案2】:

您的 DB_SERVER、DB_USER、DB_PASS 变量似乎有问题,或者您的服务器有问题?您绝对应该花时间尝试不使用已弃用的 oop 类的示例。

但是,首先尝试更改您的 $database =& new MySQLDatabase(); 到更干净的 $database = new MySQLDatabase();

【讨论】:

    【解决方案3】:

    如果您想转而使用 PDO,那么这里有一个简单的示例,说明我认为您正在努力实现的目标。 CreateReadUpdateDelete (CRUD) 类。

    <?php 
    class MySQLDatabase{
        public $db;
        function __construct($dsn, $user=null, $pass=null){
            $this->dsn = $dsn;
            $this->user = $user;
            $this->pass = $pass;
            //Connect
            $this->connect();
        }
    
        function connect(){
            try{
                $this->db = new PDO($this->dsn, $this->user, $this->pass);
                $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
                $this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
            }catch (Exception $e){
                die('Cannot connect to databse. Details:'.$e->getMessage());
            }
        }
    
        function Select($table, $fieldname=null, $fieldvalue=null){
            $sql = "SELECT * FROM $table"; 
            $sql .=($fieldname != null && $fieldvalue != null)?" WHERE $fieldname=:id":null;
            $statement = $this->db->prepare($sql);
            if($fieldname != null && $fieldvalue != null){$statement->bindParam(':id', $fieldvalue);}
            $statement->execute();
            return $statement->fetchAll(PDO::FETCH_ASSOC);
        }
    
        function Insert($table, $values){
            $fieldnames = array_keys($values[0]);
    
            $sql = "INSERT INTO $table";
            $fields = '( ' . implode(' ,', $fieldnames) . ' )';
            $bound = '(:' . implode(', :', $fieldnames) . ' )';
            $sql .= $fields.' VALUES '.$bound;
    
            $statement = $this->db->prepare($sql);
            foreach($values as $vals){
                $statement->execute($vals);
            }
        }
    
        function Update($table, $fieldname, $value, $where_key, $id){
            $sql = "UPDATE `$table` SET `$fieldname`= :value WHERE `$where_key` = :id";
            $statement = $this->db->prepare($sql);
            $statement->bindParam(':id', $id);
            $statement->bindParam(':value', $value);
            $statement->execute();
        }
    
        function Delete($table, $fieldname=null, $id=null){
            $sql = "DELETE FROM `$table`";
            $sql .=($fieldname != null && $id != null)?" WHERE $fieldname=:id":null;
            $statement = $this->db->prepare($sql);
            if($fieldname != null && $id != null){$statement->bindParam(':id', $id);}
            $statement->execute();
        }
    
    }
    
    
    //Sample Usage
    $db = new MySQLDatabase('mysql:host=localhost;dbname=test','root','password');
    
    
    //Multi insert:
    $insert = array(array('some_col'=>'This was inserted by the $db->Insert() method'),
                    array('some_col'=>'Test insert 2'),
                    array('some_col'=>'Test insert 3'),
                    );
    $db->Insert('pdo_test', $insert);
    
    //Select All
    $result = $db->Select('pdo_test');
    /*
    Array
    (
        [0] => Array
            (
                [id] => 2
                [some_col] => This was inserted by the $db->Insert() method
            )
    
        [1] => Array
            (
                [id] => 3
                [some_col] => Test insert 2
            )
    
        [2] => Array
            (
                [id] => 4
                [some_col] => Test insert 3
            )
    )
    */
    
    //Single select
    $result = $db->Select('pdo_test','id','2');
    /*
    Array
    (
        [0] => Array
            (
                [id] => 2
                [some_col] => This was inserted by the $db->Insert() method
            )
    
    )
    */
    
    /* Delete Single record*/
    $db->Delete('pdo_test', 'id', '2');
    
    /*Delete All*/
    $db->Delete('pdo_test');
    
    //Array ( ) 
    $result = $db->Select('pdo_test');
    ?>
    

    【讨论】:

      【解决方案4】:

      最好的解决方案是转到 php.ini allow_url_include = 开启 并保存

      使用

      inlcude 'J:\xampp\htdocs\oop_project\includes\database.php';
      require_once 'J:\xampp\htdocs\oop_project\includes\database.php';
      

      根据需要,这将解决

      php_network_getaddresses: getaddrinfo failed: No such host is known.
      

      【讨论】:

        猜你喜欢
        • 2014-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-23
        • 2016-08-10
        • 1970-01-01
        • 1970-01-01
        • 2014-02-14
        相关资源
        最近更新 更多