【问题标题】:Error trying to fetch data from 2 tables codeigniter尝试从 2 个表 codeigniter 获取数据时出错
【发布时间】:2017-04-05 14:00:04
【问题描述】:

我要从 2 个表中获取数据。我的表是“Study”、“Users”和“Subjects”

“学习”包括:(id,user_id[是表“用户”的“id”列的外键],subject_id[是表“id”列的外键”科目”]、年级、日期)

“用户”包括:(id、用户名、姓名、姓氏、密码、类型、状态、日期)

“主题”包括:(id、career_id、姓名、描述、小时数)

最后我想得到这样的东西:

我收到了这个错误:

这是我的代码: 我的视图文件(“home”):

    <html>

    <head>
        


    </head>

<body>

    <div class="container"> 
    <div class="row">
    <div class="col-md-12">

        <h2 align="center">TABLE:Study</h2>
        
        <input id="busqueda_tabla" type="text">
            <table class="table table-hover" align="center" border="1" cellspacing="0" cellpadding="0" width="700" id="tabla_busqueda">
                <thead>
                    <th>id</th>
                    <th>User</th>
                    <th>Subject</th>
                    <th>Grade</th>
                    <th>Date</th>
                    <th>Action</th>
                </thead>

<tbody>
    <?php

    if (count($records) > 0 && $records != false) {
        foreach($records as $record) {
            
            echo "<tr>
                      <td>".$record['id']."</td>
                      <td>".$record['user']."</td>
                      <td>".$record['subject']."</td>
                      <td>".$record['grade']."</td>
                      <td>".$record['date']."</td>
                      <td align='center'>
                         
                         <button type='button' class='btn btn-primary'>EDITAR</button></a> |
                    
                         <button type='button' class='btn btn-danger'>BORRAR</button></a>

                  </tr>";
        }

       }
    ?>

</tbody>

    </table>

        </div>
        </div>
        </div>

</body>
</html>

这是我的控制器文件(“主页”):

    <?php

    class Home extends CI_Controller{

         public function __construct(){
             parent::__construct();

             $this->load->model("Crudmodel");

        }


        public function index(){

    # get all data in Study table
    $selectStudys = $this->Crudmodel->selectStudys();

    foreach ($selectStudys as $key => $study) 
    {
        # get UserNames
        $user = $this->Crudmodel->getName($study['user_id']);

        #get Subject Names
        $subject = $this->Crudmodel->getSubName($study['subject_id']);


        #append both NEW VALUES to same array


        $data[$key]['user_id'] = $user[0]['username'];
        $data[$key]['subject_id'] = $subject[0]['name'];

    }


    $data['records'] = $selectStudys;
    $this->load->view('home', $data);

}



   }
    
?>

还有我的模型文件(“Crudmodel”):

  <?php

    class Crudmodel extends CI_Model{

        public function __construct(){
         parent::__construct();

         $this->load->database();

        }


        function selectStudys()
{
    $query= $this->db->query("SELECT * FROM Study");
    $result = $query->result_array();
    return $result;
}

function getName($name)
{
    $query= $this->db->query("SELECT username FROM Users WHERE id = $name ");
    $result = $query->result_array();
    return $result;
}

function getSubName($subject)
{
    $query= $this->db->query("SELECT name FROM Subjects WHERE id = $subject ");
    $result = $query->result_array();
    return $result;
}








}
?>

希望你能帮助我:/

【问题讨论】:

    标签: php mysql codeigniter fetch


    【解决方案1】:

    我将您的查询更改为加入查询,只需将您的代码更改为以下

    public function index(){
    
        # get all data in Study table
    
        $query = $this->db->query("SELECT sd.user_id as id,sd.grade as grade,sd.date as date,sd.subject_id as subject,ur.username as user FROM Study as sd,Users as ur,Subjects as sb WHERE ur.id=sd.user_id and sb.id=sd.subject_id");
    
        $result = $query->result_array();
    
        $data['records'] = $result;
    
        $this->load->view('home', $data);
    
    }
    

    现在运行代码

    【解决方案2】:

    未定义的索引和尝试获取属性非对象或多或少意味着相同的事情,即您没有获取正确的数据,或者您尝试获取的变量或索引未初始化或未定义,其原因可能是错误在查询或您正在运行的查询返回的空白数据中。

    我想请求您像这样提取您的查询数据

    $check = $this->db->query("SELECT * FROM SOMETHING AND YOUR CONDITION AND STUFF HERE"); 
    
    if($check->num_rows()>0){
     $result = $check->result(); 
     return $result;
    }else{
     return false; // or anything you want. 
    }
    

    假设这个查询函数存储在模型中,你正在这样调用你的模型

    $someVariable = $this->model_name->function();
    if($someVariable!==FALSE){
    // handle
    }else 
    {
    // handle
    }
    

    最后,不知道为什么,但我有时也会反驳双引号的问题,是的,我知道.. 双引号内的变量有效,我只是说有时......至少它发生在我身上,所以我想请求最后一件事。尝试像这样调试你的查询,目前你有

    "SELECT * FROM TABLE WHERE THIS = $THAT" 
    

    把这个改成

    "SELECT * FROM TABLE WHERE THIS = '".$THAT."'"
    

    希望对你有用!

    已编辑: (抱歉,我未能展示您自己代码中的示例) 你的模型文件

      <?php
    
        class Crudmodel extends CI_Model{
    
            public function __construct(){
             parent::__construct();
    
             $this->load->database();
    
            }
    
    
            function selectStudys()
    {
        $query= $this->db->query("SELECT * FROM Study");
        if($query->num_rows()>0){
           $result = $query->result_array();
         }else{
          $result = "";
              // or anything you can use as error handler
          return $result;
        }
    }
    
    function getName($name)
    {
        $query= $this->db->query("SELECT username FROM Users WHERE id = $name ");
        if($query->num_rows()>0){
        $result = $query->result_array();
        }else{
        $result = "";
              // or anything you can use as error handler
        return $result;
      }
    }
    
    function getSubName($subject)
    {
        $query= $this->db->query("SELECT name FROM Subjects WHERE id = $subject ");
      if($query->num_rows()>0){
         $result = $query->result_array();
      }else{
          $result = "";
              // or anything you can use as error handler
          return $result;
    }
        }
    
     function CombineResults($subject, $name){
      // you can also use this
       $query = $this->db->query("SELECT sub.name, user.username FROM Subjects sub, Users user WHERE sub.id=$subject AND user.id = $name");
       if($query->num_rows()>0){
            return $query->result();
             }else{
               return "";
                  // or anything you can use as error handler
            }
        }       
      }
        ?>
    

    你的控制器文件

      public function index(){
    
        # get all data in Study table
        $selectStudys = $this->Crudmodel->selectStudys();
        // we have condition on this model method/function we can validate
        // response comming from this method and add handler just like we did
        // for queries. your main problem can be this
    
        foreach ($selectStudys as $key => $study) 
        {
            # get UserNames
            $user = $this->Crudmodel->getName($study['user_id']);
    
            #get Subject Names
            $subject = $this->Crudmodel->getSubName($study['subject_id']);
    
    
            #append both NEW VALUES to same array
    
            if(!empty($user[0]['username'])){
            $data[$key]['user_id'] = $user[0]['username'];
            // your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
            }else{
             $data[$key]['user_id'] = ''; // or anything as your else condition you can use as error handler 
            }
            if(!empty($subject[0]['name'])){
            $data[$key]['subject_id'] = $subject[0]['name'];
            // your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
            }else{
               $data[$key]["subject_id"] = "";
              // or anything you can use as error handler
            }
    
        }
    
    
        $data['records'] = $selectStudys;
        $this->load->view('home', $data);
    
    }
    

    【讨论】:

    • 老兄,你能帮我处理一下我的代码吗?我对这一切有点头晕:S
    • 很抱歉,如果我的回答使情况恶化,请问有什么可以帮忙的,兄弟你试过我的解决方案了吗?只需尝试在空白或错误​​查询上添加处理程序,以使您的索引不为空。它将解决您的问题,例如您正在尝试初始化$var['index'] = ''$var['index'] = $something 假设$something 是当您的代码在使用num_rows()null 检查查询响应后具有值时您的查询不起作用并在检查num_rows()==0 后返回空白值,它将修复。
    • 我的意思是,我不明白你的回答:S。如果你可以加入我的代码,你会帮助我很多伙伴:)
    • if(!empty($user[0]['username']){ 我错过了“)”关闭小括号,请把它放在上面,它会像这样if(!empty($user[0]['username'])){ - 更新答案并在那里添加小括号。
    猜你喜欢
    • 2020-07-25
    • 2021-01-03
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多