MySQL to MySQLi connection problems

2020-01-19 23:57发布

问题:

I recently upgraded my server and now I'm trying to convert everything from MySQL to MySQLi and I'm having some difficulty.

I keep getting this error:

PHP Warning:  mysqli_select_db() expects exactly 2 parameters

Can someone guide me in the right direction please and thanks!!!

Here is my old code that is in a PHP class:

class Db {
    function __construct($app = ''){
        // Get the main settings from the array we just loaded
        $host = 'localhost';
        $user = 'username';
        $pass = 'password';
        $db = 'db_name';
        // Connect to the database
        $this->link = mysqli_connect($host, $user, $pass);
        mysqli_select_db($db);
        register_shutdown_function(array(&$this, 'close'));
    }
    function query($query){
        if($query) return @mysqli_query($query, $this->link);
        else return false;
    }
    function fetchArray($result){
        if($result) return mysqli_fetch_array($result, mysqli_ASSOC);
        else return false;
    }
    function queryFetch($query){
        if($query) $result = mysqli_query($query, $this->link);
        if($result)
            return mysqli_fetch_array($result, mysqli_ASSOC);
        else
            return false;
    }
    function close(){
        mysqli_close($this->link);
    }
}

回答1:

@mysqli_query($query, $this->link) the connection comes first here and not second; the order is different in using the mysqli_ API as opposed to the mysql_ API. Plus, remove @ during testing/development, it's an error suppressor.

mysqli_select_db($db); requires a db connection and as the first argument.

It's all in the manuals:

  • http://php.net/manual/en/mysqli.query.php
  • http://php.net/manual/en/mysqli.select-db.php

Note: You may potentially have a variable scope issue, so if that is the case, you will need to pass the connection inside the methods.

Use error handling:

  • http://php.net/manual/en/mysqli.error.php
  • http://php.net/manual/en/function.error-reporting.php


标签: php mysql mysqli