How to use MySQLi Driver in Codeigniter

2020-02-11 03:13发布

Hi I'm kinda new to this and I would like to ask someone here that are experts in codeigniter framework and PHP.

How can I use mysqli drivers in php native query? For example.

My code:

Model

class Home_model extends CI_Model{

public function getusers(){
$q = "SELECT * FROM `users`";
return $r = mysqli_query($q);
}

}

Controller:

class Home extends CI_Controller{
public function iterateuser(){
while($row = mysqli_fetch_object($this->Home_model->getusers())){
echo $row->username;
}

}

My code above is an error, report saying "mysqli_query expects at least 2 parameters". Is there a way in codeigniter to pass the link on the mysqli_query() first parameter as described on the php.net documentation http://php.net/manual/en/mysqli.query.php

4条回答
我欲成王,谁敢阻挡
2楼-- · 2020-02-11 03:53

go to:

yourproject/application/config/database.php

change:

$db['default']['dbdriver'] = 'mysql';   

with:

$db['default']['dbdriver'] = 'mysqli';
查看更多
虎瘦雄心在
3楼-- · 2020-02-11 03:56

You should change the content of the file DB_driver.php in you codeigniter system directory. Go to:

system/database/DB_driver.php

And change the following line:

var $dbdriver = 'mysql'; 

to :

var $dbdriver = 'mysqli'; 

here is a extraction of the DB_driver.php

 * MySQLi Database Adapter Class - MySQLi only works with PHP 5
 *
 * Note: _DB is an extender class that the app controller
 * creates dynamically based on whether the active record
 * class is being used or not.
 *
 * @package        CodeIgniter
 * @subpackage    Drivers
 * @category    Database
 * @author        ExpressionEngine Dev Team
 * @link        http://ellislab.com/codeigniter/user-guide/database/
 */
class CI_DB_mysqli_driver extends CI_DB {

    var $dbdriver = 'mysqli'; 
查看更多
贪生不怕死
4楼-- · 2020-02-11 03:59

Once you have specified 'mysqli', you can use the following function to get mysqli. For example, mysqli_real_escape_str, etc.:

function get_mysqli() { 
    $db = (array)get_instance()->db;
    return mysqli_connect('localhost', $db['username'], $db['password'], $db['database']);
}
查看更多
欢心
5楼-- · 2020-02-11 04:02

Open the file 'database.php' under the folder '/application/config/'

Move to the line

$db['default'] = array('dbdriver' => '')

Modify it as below

$db['default'] = array('dbdriver' => 'mysqli')
查看更多
登录 后发表回答