简体   繁体   中英

OOPS with OOP, PHP database connection

Hey guys I am developing a database connection with OOP PHP and I am stuck on this error;

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\\Users...\\function.php on line 26.

I am new to OOP so any help greatly appreciated

<?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.

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 would show you that $this->con is not defined. Next, you would go back to where you define and add a die() statement or similar to see if that code is even running. 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. 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
  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) ). I would also change, instead of using the var keyword, to declare these properties like this:

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. However, var is no longer required. 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.

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

like others said, constructor start with 2 underscores, i am using following class and its work for me,

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

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 ....

security levels Changes 1

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

security levels Changes 2

public to protected member variable.

1) your data base connection code is Procedural Style not for OOP

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

2) You should change construct function __construct()

3) Check condition if ($this->con->connect_error) die('Database error -> ' . $this->con->connect_error);

4) Change echo $obj->query("SELECT * FROM posts"); to print_r($obj->query("SELECT * FROM posts")); OR var_dumb 5)

public function query()
    {

        return $this->con;

    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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