如何将PHP文件转换为CodeIgniter中的模型?

时间:2013-09-09 07:56:07

标签: php codeigniter

如何将此PHP文件翻译为模型文件?我是CodeIgniter的新手。

这是我的代码:

<?php
    $q=$_GET['q'];
    $my_data=mysql_real_escape_string($q);
    $mysqli=mysqli_connect('192.168.128.30','root','root','root') or die("Database Error");
    $sql="SELECT * FROM items WHERE itemcode LIKE '%$my_data%' ORDER BY itemcode";
    $result = mysqli_query($mysqli,$sql) or die(mysqli_error());

    if($result)
    {
        while($row=mysqli_fetch_array($result))
        {
            echo $row['itemcode']."\n";

        }
    }
?>

3 个答案:

答案 0 :(得分:1)

如果你的表名是项目,那么你可以创建一个名为mitems.php的php文件。 有一个模型文件的例子......

<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MItems extends CI_Model
{
    public $table;
    public function __construct()
    {
        parent::__construct();
        $this->table = "items";
        $this->load->database();
    }

    function select($conditions=NULL, $tablename="", $limit=500, $offset=0)
    {
        if($tablename=="")
        {
            $tablename = $this->table;
        }
        if($conditions != NULL)
            $this->db->where($conditions);

        $query = $this->db->get($tablename, $limit, $offset=0);
        return $query->result();
    }
}

您可以点击此链接http://thephpcode.com/blog/codeigniter/a-smart-codeigniter-model

答案 1 :(得分:0)

CI模式?这是你的:

public function select_data($my_data){
   $this->db->like('itemcode', $my_data);
   $this->db->order_by('itemcode');

   return $this->db->get('items');
}

答案 2 :(得分:0)

一些基本想法:

  • 您可以创建一个模型类“ItemCode”或类似的东西(不知道主题)并添加方法Search;
  • 您可以使用内置的“DB”对象来执行查询,请参阅http://ellislab.com/codeigniter/user-guide/database/active_record.html#select;
  • 访问“GET”参数应该移动到控制器,你应该使用更好地了解SQL注入的东西(在ActiveRecord中,例如,这将自动转义);
  • 只能在配置文件中找到SQL连接参数。