如何从本机php转换为codeigniter [英] How to convert from native php to codeigniter

查看:115
本文介绍了如何从本机php转换为codeigniter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下db和php。我试图做一个无序的类别菜单列表。
原始的php本身工作。
我试图把这转换为MVC在codeigniter和以下是我到目前为止,不工作。
如果有人可以指出我做错了什么,我会很感激。



数据库

  CREATE TABLE IF NOT EXISTS`categories`(
`id` int(11)NOT NULL auto_increment,
`name` varchar(255)NOT NULL,
`shortdesc` varchar(255)NOT NULL,
`longdesc` text NOT NULL,
`status`枚举('active','inactive')NOT NULL,
`parentid` int(11)NOT NULL,
PRIMARY KEY(`id`)
)ENGINE = MyISAM AUTO_INCREMENT = 10 DEFAULT CHARSET = latin1 AUTO_INCREMENT = 10;

-
- 转储表类别的数据
-

INSERT INTO`categories`(`id`,`name` ,`shortdesc`,`longdesc`,`status`,`parentid`)VALUES(1,'shoes','男孩和女孩的鞋子','','活动',7)
INSERT INTO`categories`(`id`,`name`,`shortdesc`,`longdesc` ,`````````` parentid`)VALUES(2,'shirts' ','active',7);
...
...

menu.php工作)

 <!DOCTYPE html PUBLIC -  // W3C // DTD XHTML 1.0 Transitional // EN
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
< html xmlns =http://www.w3.org/1999/xhtmlxml:lang =enlang =en>
< head>
< meta http-equiv =content-typecontent =text / html; charset = iso-8859-1/>
< title>查看任务< / title>
< / head>
< body>
< h3>菜单< / h3>
<?php
function make_list($ parent){

全局$ data;
echo'< ul>';

foreach($ parent as $ task_id => $ todo){

echo< li> $ todo;

if(isset($ data [$ task_id])){

make_list($ data [$ task_id])
}

echo'< / li>';

}
echo'< / ul>';

}

$ dbc = @mysqli_connect('localhost','root1','root','ci_day6')或die('< p>无法连接到数据库!< / p>< / body>< / html>');

$ q ='SELECT id,parentid,name FROM categories ORDER BY parentid ASC';
$ r = mysqli_query($ dbc,$ q);

$ data = array();

while(list($ id,$ parentid,$ name)= mysqli_fetch_array($ r,MYSQLI_NUM)){

$ data [$ parentid] [$ id] = $ name;

}

make_list($ data [0]);

?>

< / body>
< / html>

此php输出以下html

 菜单

*衣服
o鞋子
o衬衫
o裤子
o连衣裙
* fun
o玩具
o游戏

我的MVC迄今为止没有工作。



cat_menu_model.php(model)

 <?php 

class Cat_menu_model extends Model
{
function Cat_menu_model()
{
parent :: Model();

}

function get_categories_nav()
{

$ data = array();
$ this-> db-> select('id,name,parentid');
$ this-> db-> where('status','active');
$ this-> db-> orderby('parentid','asc');
$ this-> db-> orderby('name','asc');

$ Q = $ this-> db-> get('categories');
if($ Q - > num_rows()> 0){
foreach($ Q - > result_array()as $ row){
$ data [$ row ['parentid ']] [$ row ['id']] = $ row ['name'];
}
}

$ Q-> free_result();
return $ data;

}
}

cat_menu.php / p>

 <?php 

class Cat_menu extends Controller
{

function Cat_menu()
{
parent :: Controller();
}
function make_menu($ parent)
{
$ this-> load-> model('cat_menu_model');

$ data ['navlist'] = $ this-> cat_menu_model-> get_categories_nav();
$ this - > load> view('menu');
}
}

menu.php(检视)

 <?php 
if(count($ navlist))
{
$ this-> make_menu ($ data [0]);
echo'< ol>';
foreach($ parent as $ id => $ catname){

echo< li> $ catname;

if(isset($ data [$ id])){

make_menu($ data [$ id]);

}

echo'< / li>';

}
echo'< / ol>';
}
?>

它显示错误消息。

 遇到PHP错误

严重性:警告

消息:缺少cat_menu :: make_menu()的参数1

文件名:controllers / cat_menu.php

行号:10
pre>

解决方案

由于上面的PHP错误消息,它说你已经告诉Cat_menu :: make_menu参数。在这种情况下, Cat_menu 控制器中的 make_menu($ parent)功能。



如果此功能不需要任何输入 - 看起来不像$ parent被使用 - 然后只是删除$ parent参数从make_menu。



或者,设置一个默认值,如果你想该函数接受无参数。如下:



cat_menu.php(控制器)



 <?php 

class Cat_menu extends Controller
{

function Cat_menu()
{
parent ::控制器();
}

function make_menu($ parent = FALSE)//这个$ parent参数是否需要?
{
$ this-> load-> model('cat_menu_model');

$ data ['navlist'] = $ this-> cat_menu_model-> get_categories_nav();

//如果你想要解析数据到视图,你需要声明它
$ this-> load-> view('menu',$ data);
}
}

假设你的代码其余部分是正确的,现在工作。请参见 CodeIgniter用户指南,以供您参考。特别是在解析值时查看文档






OP *已在下面的评论中回应,这是我的回应。



** OP =原始海报*



在视图中运行print_r($ navlist)时。 OP获得以下输出:

 数组(
[0] =& 7] => clothes
[8] => fun

[7] =& 2] => shirts
[1] => shoes

[8] =& 5] => toys


注意OP的CI模型ActiveRecord查询与原始非MVC查询显着不同:

  SELECT 
id,
parentid,
name
FROM
类别
ORDER BY
parentid ASC

vs

  $ this-> db-> select('id,name,parentid'); 
$ this-> db-> where('status','active');
$ this-> db-> orderby('parentid','asc');
$ this-> db-> orderby('name','asc');
$ Q = $ this-> db-> get('categories');

CI模型查询与原始SQL不同。当转换为SQL时,将产生以下结果:

  SELECT 
id,
name,
parentid
FROM
类别
WHERE
status ='active'
ORDER BY
parentid ASC,
name ASC

但是,这是正确的数据被带回来,所以我会继续。



OP希望数组的格式类似于层次结构。有关以后的参考,请参阅: PHP / MySQL - 构建导航菜单层次结构。最简单的方法是遵循OP的原始(非MVC)函数,并将其添加为模型函数。这个模型函数将创建一个嵌套数组,而不是直接的html输出 - 这是为了分离应用程序逻辑和输出。



您可以添加以下内容你的模型作为一个函数。最初取自嵌套集,php数组和转换,但自重写以来OP出现的错误:

 函数to_hierarchy($ collection = NULL)
{
if ($ collection))return false;

$ tree = array();

foreach($ collection [0] as $ key => $ value)
{
$ tree [$ value] = array

foreach($ collection [$ key] as $ item)
{
array_push($ tree [$ value],$ item);
}
}

return $ tree;
}



现在我们可以更新我们的控制器为:



cat_menu.php(Controller)

 < ;? php 

class Cat_menu extends Controller
{

function Cat_menu()
{
parent :: Controller();
}

function make_menu($ parent = FALSE)//这个$ parent参数是否需要?
{
$ this-> load-> model('cat_menu_model');

$ get_nav_list = $ this-> cat_menu_model-> get_categories_nav();

$ format_nav_list = $ this-> cat_menu_model-> to_hierarchy($ get_nav_list);

//加载ul / ol转换的HTML帮助器
$ this-> load-> helper('html');

$ data ['navlist'] = $ format_nav_list;

//如果你想解析数据到视图,你需要声明它
$ this-> load-> view('menu',$ data);
}
}

现在我们可以将视图更新为:



menu.php(查看)

 <?php 
echo ul($ navlist);
?>

免责声明:因为我目前没有从这台计算机访问解释器。请务必检查任何语法。


I have the following db and php. I am trying to make a unordered list of category menu. The original php is working by itself. I am trying to convert this to MVC in codeigniter and the following is what I got so far and not working. If someone can point out what I am doing wrong, I will appreciate it.

Database

CREATE TABLE IF NOT EXISTS `categories` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `shortdesc` varchar(255) NOT NULL,
  `longdesc` text NOT NULL,
  `status` enum('active','inactive') NOT NULL,
  `parentid` int(11) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

-- 
-- Dumping data for table `categories`
-- 

INSERT INTO `categories` (`id`, `name`, `shortdesc`, `longdesc`, `status`, `parentid`) VALUES (1, 'shoes', 'Shoes for boys and girls.', '', 'active', 7);
INSERT INTO `categories` (`id`, `name`, `shortdesc`, `longdesc`, `status`, `parentid`) VALUES (2, 'shirts', 'Shirts and blouses!', '', 'active', 7);
...
...

menu.php (original php and working)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
    <title>View Tasks</title>
</head>
<body>
<h3>Menu</h3>
<?php 
function make_list ($parent) {

    global $data;
    echo '<ul>';

    foreach ($parent as $task_id => $todo) {

        echo "<li>$todo";

        if (isset($data[$task_id])) { 

            make_list($data[$task_id]);
        }

        echo '</li>';

    }
    echo '</ul>';

} 

$dbc = @mysqli_connect ('localhost', 'root1', 'root', 'ci_day6') OR die ('<p>Could not connect to the database!</p></body></html>');

$q = 'SELECT id, parentid, name FROM categories ORDER BY parentid ASC'; 
$r = mysqli_query($dbc, $q);

$data = array();

while (list($id, $parentid, $name) = mysqli_fetch_array($r, MYSQLI_NUM)) {

    $data[$parentid][$id] =  $name;

}

make_list($data[0]);

?>

</body>
</html>

This php output the following html

Menu

    * clothes
          o shoes
          o shirts
          o pants
          o dresses
    * fun
          o toys
          o games

My MVC so far and not working.

cat_menu_model.php(model)

<?php

class Cat_menu_model extends Model
{
         function Cat_menu_model()
        {
            parent::Model();

        }

        function get_categories_nav()
        {

            $data = array();
            $this->db->select('id,name,parentid');
            $this->db->where('status', 'active');
            $this->db->orderby('parentid','asc');
            $this->db->orderby('name','asc');

            $Q = $this->db->get('categories');
        if ($Q -> num_rows() > 0){
          foreach ($Q -> result_array() as $row){
          $data[$row['parentid']][$row['id']] = $row['name'];
          }
          }

           $Q->free_result(); 
           return $data; 

        }
}

cat_menu.php (controller)

<?php

class Cat_menu extends Controller
{

    function Cat_menu()
    {
        parent::Controller();
    }
    function make_menu($parent)
    {
        $this->load->model('cat_menu_model');

        $data['navlist'] = $this->cat_menu_model->get_categories_nav();
            $this -> load ->view('menu');
    }
}

menu.php(view)

<?php
if (count($navlist))
{
  $this->make_menu($data[0]);
  echo '<ol>';
    foreach ($parent as $id => $catname) {

        echo "<li>$catname";

        if (isset($data[$id])) { 

        make_menu($data[$id]);

        }

        echo '</li>';

    } 
 echo '</ol>';
}
?>

It shows an error messages.

A PHP Error was encountered

Severity: Warning

Message: Missing argument 1 for Cat_menu::make_menu()

Filename: controllers/cat_menu.php

Line Number: 10

解决方案

Given the PHP error message above, it's saying that you've told the method Cat_menu::make_menu() to accept an argument. In this case the function make_menu($parent) in the Cat_menu controller.

If this function does not require any input -- doesn't look like $parent is used -- then just remove the $parent argument from make_menu.

Alternatively, set a default value if you would like the function to accept no arguments. See below:

cat_menu.php (Controller)

<?php

class Cat_menu extends Controller
{

    function Cat_menu()
    {
        parent::Controller();
    }

    function make_menu($parent = FALSE) //Is this $parent argument needed?
    {
        $this->load->model('cat_menu_model');

        $data['navlist'] = $this->cat_menu_model->get_categories_nav();

        //If you want to parse data to a view you need to state it
        $this->load->view('menu', $data);
    }
}

Assuming the rest of your code is correct, this should now work. Please see the CodeIgniter User Guide for reference from now on. Specifically the views documentation on parsing values across.


OP* has since responded in the comments below, this is my response.

**OP = Original Poster*

When running print_r($navlist) in the view. The OP gets the following output:

Array ( 
    [0] => Array ( 
        [7] => clothes 
        [8] => fun 
    ) 
    [7] => Array ( 
        [3] => pants 
        [2] => shirts 
        [1] => shoes 
    ) 
    [8] => Array ( 
        [6] => games 
        [5] => toys 
    )
)

However, it is worth noting that the OP's CI model ActiveRecord query is significantly different than the original -- non MVC -- query:

SELECT 
    id, 
    parentid, 
    name 
FROM 
    categories 
ORDER BY 
    parentid ASC

vs.

$this->db->select('id,name,parentid');
$this->db->where('status', 'active');
$this->db->orderby('parentid','asc');
$this->db->orderby('name','asc');
$Q = $this->db->get('categories');

The CI model query is different than the original SQL to begin with. When converted into SQL it would produce the following:

SELECT
    id, 
    name,
    parentid
FROM
    categories
WHERE
    status = 'active'
ORDER BY
    parentid ASC,
    name ASC

However, it seems that this is the correct data being brought back so I'll continue on.

The OP would like the array formatted like a heirarchy. For future reference, please see: PHP/MySQL - building a nav menu hierarchy. The easiest way to do this, would be to follow the OP's original (non MVC) function and add it as a model function. This model function would create a nested array, rather than the direct html output -- the reason for this is to separate application logic from output.

You can add the following to your model as a function. Originally taken from Nested sets, php array and transformation but since re-written due to errors appearing for OP:

function to_hierarchy($collection = NULL)
{
    if (is_null($collection)) return false;

    $tree = array();

    foreach($collection[0] as $key => $value)
    {
        $tree[$value] = array();

        foreach($collection[$key] as $item)
        {
            array_push($tree[$value], $item);
        }
    }

    return $tree;
}

Now we can update our controller to be the following:

cat_menu.php (Controller)

<?php

class Cat_menu extends Controller
{

    function Cat_menu()
    {
        parent::Controller();
    }

    function make_menu($parent = FALSE) //Is this $parent argument needed?
    {
        $this->load->model('cat_menu_model');

        $get_nav_list = $this->cat_menu_model->get_categories_nav();

        $format_nav_list = $this->cat_menu_model->to_hierarchy($get_nav_list);

        //Load the HTML helper for ul/ol conversion
        $this->load->helper('html');

        $data['navlist'] = $format_nav_list;

        //If you want to parse data to a view you need to state it
        $this->load->view('menu', $data);
    }
}

Now we can update our view to be the following:

menu.php (View)

<?php
    echo ul($navlist);
?>

Disclaimer: None of the above has been tested using PHP as I currently don't have access to the interpreter from this computer. Please make sure you check over any syntax.

这篇关于如何从本机php转换为codeigniter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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