如何在CodeIgniter中手动连接到数据库? [英] How can I connect to a database manually in CodeIgniter?

查看:93
本文介绍了如何在CodeIgniter中手动连接到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CodeIgniter中,是否可以使用任何一组用于php的驱动程序手动连接到数据库?我只打开模型中的连接?我有一个需要CodeIgniter不会覆盖,但我想使用它的MVC架构。

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.

如果我只能做一个常规的非CodeIgniter数据库连接,我该如何使用它的ActiveRecord获取信息到我的控制器?

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

此外,我想以这种方式使用CodeIgniter(没有活动记录),但是对于所有其他东西,我错了吗?

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

谢谢。

推荐答案

这是一个非常简单的例子,使用函数php连接到mysql db。它来自php手册。把它放在你的模型中。通过调用模型函数调用它的正常CI方式。它将返回结果数组,因此将模型调用分配给控制器中的变量。

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:将mysql_close移到return语句之上

moved mysql_close above return statement

这篇关于如何在CodeIgniter中手动连接到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆