【问题标题】:parser error: syntax error, unexpected $data (T_VARIABLE) in codeIgniter解析器错误:语法错误,codeIgniter 中出现意外的 $data (T_VARIABLE)
【发布时间】:2015-11-30 03:40:00
【问题描述】:

我是 CodeIgniter 的新手。当我尝试通过控制器、视图和模型传递数据时,我得到了这个:

语法错误: c:\xampp\htdocs\ci\application\controllers\users.php 中 行中出现意外的 '$data'(T_VARIABLE) 10

这是我的控制器users.php 代码:

<?php
class Users extends CI_Controller
    {
        public function show()
            {
                $data['results']=$this->user_model->get_users();
                $this->load->view('user_view',$data);
             }
    }
?>

在views文件夹user_view.php代码:

<body>
<?php
foreach($results as $object){
    echo $object->username;
}
?>
</body>

在模型文件夹user_model.php代码

<?php
class User_model extends CI_Model
    {
        public function get_users()
            {
                $query=$this->db->get('users');
                return $query->result();
            }
    }
?>

我该如何解决这个错误?

【问题讨论】:

    标签: php codeigniter variables


    【解决方案1】:

    为什么你的错误提示 c:\xampp\htdocs\ci\application\users.php 不应该是 c:\xampp\htdocs\ci\application\controller\users.php`

    【讨论】:

    • 感谢您的回复。我纠正了它。仍然出现同样的错误。
    【解决方案2】:

    在你的控制器中

    public function show()
    {
        $data['results']=$this->user_model->get_users();
        $this->load->view('user_view',$data);
    }
    

    在你的模型中

    public function get_users(){
        $query=$this->db->get('users');
        $result = $query->result_array(); //added
        return $result; //added
    }
    

    在视图中

    <body>
    <?php
        foreach($results as $new_results) //changed
        {
            echo $new_results['username']; //changed
        }
    ?>
    </body>
    

    【讨论】:

    • 感谢您的评论。我检查了它。但得到了同样的错误。
    • 错误是:严重性:解析错误;消息:语法错误,意外的“$data”(T_VARIABLE);文件名:controllers/users.php
    • 抱歉又打扰你了。更正行后,我收到两条消息:第一个是 Severity:notice;消息:使用未定义的常量结果-'结果';文件名:models/user_model.php,第二个是严重性:警告;消息:为 foreach() 提供的参数无效;文件名:views/user_view.php
    • 在视图中result 应该来results
    【解决方案3】:

    您正在尝试访问错误的ARRAY。 在您的控制器阵列中是$data['results'] 而不是$data['result']。所以你需要在foreach循环中访问$results。

    在你的view改自

    foreach($result as $object){
    

    到

    foreach($results as $object){
    

    【讨论】:

    • 感谢您的 cmets。我改变了它,但仍然有同样的错误。
    【解决方案4】:

    在 foreach 循环中使用$results 并检查

    【讨论】:

    • 感谢您的评论。我更改了它并尝试了,但仍然出现同样的错误。
    【解决方案5】:

    首先,您必须将模型加载为:

    $this->load->model('User_model','user_model');
    

    然后您可以将该模型中定义的函数用作:

    $this->user_model->get_users();
    

    【讨论】:

      【解决方案6】:

      您的代码中还有一个错误,即您没有在函数中加载模型

      更新您的代码以在 show() 函数的第一行添加以下行

      $this->load->model('user_model');
      

      【讨论】:

        猜你喜欢
        • 2015-05-11
        • 2019-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多