开发者

How can I connect to a database manually in CodeIgniter?

开发者 https://www.devze.com 2023-01-18 11:30 出处:网络
Is it possible to connect to a database manually, using any set of drivers for php, in CodeIgniter?Would I just open a connection in the model?I have a need that CodeIgniter won\'t cover but I\'d like

Is it possible to connect to a database manually, using any set of drivers for php, in CodeIgniter? Would I just open a connection in the model? I have a need that CodeIgniter won't cover but I'd like to use it for it's MVC architecture. I just can't use it's ActiveRecord like in the demos with MySQL, et开发者_如何学JAVAc.

If I can just do a "regular" non-CodeIgniter database connection, how do I get the information into my controller?

Also, am I wrong for wanting to use CodeIgniter in this way (no active record) but for all its other "stuff"?

Thank you.


This is a very simple example of using functional php to connect to a mysql db. It comes form the php manual. Put this in your model. Call it by calling a model function the normal CI way. It will return the result array, so assign the model call to a variable in your controller.

<?php
function my_model_query(){
    //replace the function arguments with your information
    $link = mysql_connect('host_name', 'mysql_user', 'mysql_password');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    //your code here
    $query = "SELECT * FROM mytable";
    $result = mysql_query($query);
    while($row = mysql_fetch_assoc($result)){

        $result_array[]['your_field_1'] = $row['your_field_1'];
        $result_array[]['your_field_2'] = $row['your_field_2']; 
        //and so on

       }

    //close the connection when you are done
    mysql_close($link);

    //send results back to controller
    return $result_array;


}//endfunction
?>

You can use this in your model method. Let's assume you return the results

EDIT: moved mysql_close above return statement


I don't really know what your problem is, but you can execute a query without the active record.

e.g

$this->db->query();


for manual connection to database , just the normal code

$link = mysqli_connect('localhost','root','','db_iris');
0

精彩评论

暂无评论...
验证码 换一张
取 消