简体   繁体   English

带OOP的OOPS,PHP数据库连接

[英]OOPS with OOP, PHP database connection

Hey guys I am developing a database connection with OOP PHP and I am stuck on this error; 大家好,我正在用OOP PHP开发数据库连接,但我一直坚持这个错误;

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\\Users...\\function.php on line 26. 警告:mysqli_query()期望参数1为mysqli,在第26行的C:\\ Users ... \\ function.php中给出null。

I am new to OOP so any help greatly appreciated 我是OOP的新手,因此非常感谢您的帮助

<?php
    class MyClass{
        var $HOST = "localhost";
        var $USER = "user";
        var $PASS = "pass";
        var $DB = "image_blog";
        public $con;

        function _construct(){
            $this->host = $HOST;
            $this->user = $USER;
            $this->pass = $PASS;
            $this->db = $DB;

            $this->con = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
        }

        public function query($sql)
        {
            $query = mysqli_query($this->con,$sql);
            return $query;
        }
   }

   $obj = new Myclass;
   echo $obj->query("SELECT * FROM posts");

The name of your constructor function must be __construct with two underscores, not one. 构造函数的名称必须是带有两个下划线而不是一个下划线的__construct

You can debug this sort of problem yourself. 您可以自己调试此类问题。 Working backwards from the error, you would first do a var_dump() on $this->con (the first parameter for mysqli_query() ). 从错误开始,首先要对$this->conmysqli_query()的第一个参数var_dump()执行var_dump() )。 This would show you that $this->con is not defined. 这将显示$this->con未定义。 Next, you would go back to where you define and add a die() statement or similar to see if that code is even running. 接下来,您将返回到定义并添加die()语句或类似语句的位置,以查看该代码是否还在运行。 You will find that it isn't. 您会发现事实并非如此。

From there, you could try copying/pasting in a known working function from the PHP documentation and then you would find that the constructor function would work. 从那里,您可以尝试从PHP文档中复制/粘贴到一个已知的工作函数中,然后您会发现构造函数可以工作。 All you have to do then is compare your two constructor functions, and it is likely you would immediately spot your error. 然后,您要做的就是比较两个构造函数,很可能您会立即发现错误。

var $HOST = "localhost";
var $USER = "user";
var $PASS = "pass";
var $DB = "image_blog";

Reading this answer , you are using an outdated syntax for declaring class properties here (they are not, in fact, variables in and of themselves). 阅读此答案 ,您将在这里使用过时的语法来声明类属性(实际上,它们本身不是变量)。 In your constructor (which others are right, is missing the first underscore), you are simply referencing undefined local variables, rather than the properties themselves. 在构造函数中(其他人是对的,缺少第一个下划线),您只是在引用未定义的局部变量,而不是属性本身。 The solution here is to: 解决方案是:

  1. Add a second underscore prior to the _construct method to make it __construct , and _construct方法之前添加第二个下划线,使其成为__construct ,然后
  2. Change your constructor in regards to these properties. 更改关于这些属性的构造函数。

I would suggest passing variables in as parameters to the constructor and set them that way (so that you would do new MyClass( $host, $user, $pass, $db) ). 我建议将变量作为参数传递给构造函数,并以这种方式设置它们(这样您就可以执行new MyClass( $host, $user, $pass, $db) )。 I would also change, instead of using the var keyword, to declare these properties like this: 我还将更改,而不是使用var关键字来声明这些属性,如下所示:

protected $host = 'host';
// etc.

Another option could be to define them as constants, since, as you are using them currently, they can never really change anyway: 另一种选择是将它们定义为常量,因为当您当前使用它们时,它们永远不会真正改变:

const HOST = 'host';

And you can reference them later as: 您以后可以引用它们为:

self::HOST

Here's a relevant quote from the documentation : 这是文档中的相关报价:

In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private. 为了保持与PHP 4的向后兼容性,PHP 5仍将接受在属性声明中使用关键字var,而不是(或除之之外)public,protected或private。 However, var is no longer required. 但是,不再需要var。 In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning. 在PHP从5.0到5.1.3的版本中,不建议使用var,并且会发出E_STRICT警告,但是自PHP 5.1.3起,它不再被弃用,因此不会发出警告。

构造function __construct()以2个下划线function __construct()开头

like others said, constructor start with 2 underscores, i am using following class and its work for me, 就像其他人说的那样,构造函数以2个下划线开头,我正在为我使用以下类及其工作,

class maindb_con
{
    private $hostname;
    private $username;
    private $password;
    private $dbname;
    private $con;

    function __construct()
    {
        $this->hostname = "**********";
        $this->username = "**********";
        $this->password = "**********";
        $this->dbname   = "**********";
        if(!mysql_connect($this->hostname, $this->username, $this->password,$this->dbname))
        {
            echo'Error:: 1001 Couldnot connect to database. Please update hostname, username and password';
        }
        else
            $this->con=mysql_connect($this->hostname, $this->username, $this->password);

    }
    /*function maindb_con($hname, $uname, $pwd, $dbname)
    {
        $this->hostname = $hname;
        $this->username = $uname;
        $this->password = $pwd;
        $this->dbname = $dbname;
    }*/
    function get_con()
    {
        mysql_select_db($this->dbname,$this->con);
        return $this->con;
    }
    function get_dbname()
    {
        return $this->dbname;
    }
    public function __destruct()
    {
        mysql_close($this->con);
    }
} 

and you can add following method to run query and get result or false if query couldnt run as you require 并且您可以添加以下方法来运行查询并获取结果,如果查询无法按要求运行则返回false

public function runQuery($query)
    {
        //echo "query on runQuery(): ".$query;
        if($result=mysql_query($query,$this->con)) //or die("couldnt run mysql_query on runQuery for ".$query)
            return $result;
        return false;
    }

or this class could be used in following way 或者可以按以下方式使用此类

$dbcon=new maindb_con();
        $con=$dbcon->get_con();
        //echo "query on runQuery(): ".$query;
        if($result=mysql_query($query,$con))
......

Please visit here which will give you advance oop programming in PHP and give feedback please .... 请访问这里 ,它将为您提供使用PHP进行高级oop编程并提供反馈的意见.....

security levels Changes 1 安全级别更改1

 define("DB_HOST", 'yourhostaname');  
    define("DB_USER", 'dbusername');  
    define("DB_PASSWORD", 'dbpassword');  
    define("DB_DATABSE", 'databasename');

security levels Changes 2 安全级别更改2

public to protected member variable. 对受保护的成员变量公开。

1) your data base connection code is Procedural Style not for OOP 1)您的数据库连接代码是非OOP的过程样式

OOP Style : $this->con =new mysqli( $this->host, $this->user, $this->pass, $this->db) OOP风格:$ this-> con = new mysqli($ this-> host,$ this-> user,$ this-> pass,$ this-> db)

2) You should change construct function __construct() 2)您应该更改构造函数__construct()

3) Check condition if ($this->con->connect_error) die('Database error -> ' . $this->con->connect_error); 3)检查条件($ this-> con-> connect_error)是否死了('Database error->'。$ this-> con-> connect_error);

4) Change echo $obj->query("SELECT * FROM posts"); 4)更改echo $ obj-> query(“ SELECT * FROM posts”); to print_r($obj->query("SELECT * FROM posts")); 到print_r($ obj-> query(“ SELECT * FROM posts”)); OR var_dumb 5) 或var_dumb 5)

public function query()
    {

        return $this->con;

    }

6) obj->query("SELECT * FROM posts") or die(obj->error); 6) obj->query("SELECT * FROM posts") or die(obj->error);

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

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