views:

68

answers:

2

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

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.

+2  A: 

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

e.g

$this->db->query();
Mario Cesar
I just mean that I do not want to use the built in drivers that come with CI. I don't know how to do it.
johnny
Even though the built-in drivers use the functional libraries provided for each DB? ie. the MySQL drivers for CI use mysql_connect, mysql_query, mysql_fetch_assoc, etc. That, and the drivers handle formalities that you don't have to worry about.
Chris Hutchinson
+2  A: 

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

kevtrout
thank you for your help.
johnny
In this code `mysql_close($link);` will never get executed... :-)
captaintokyo
Because it is after the return statement?
kevtrout
yes, anything after the `return` statement won't be executed
captaintokyo
Well, you live and learn. Thanks captaintokyo
kevtrout
I used it for Sqlite anyway. Thanks.
johnny