首页 > 解决方案 > 在 foreach PHP Codeigniter 中调用存储过程

问题描述

在 foreach 中调用存储过程时出现错误
它说“命令不同步,您现在无法运行此命令”。
我已经在寻找解决方案,但结果并不像我期望的那样。这是我的代码

$query = "CALL PROCEDURE_HEAD()";
$sql   = $this->db->query($query)->result_array();
foreach($sql as $key) {
   $name = $key['name'];
   $array['name'] = $name;
   $array['data'] = $key['data'];

   $query2 = "CALL PROCEDURE_CHILD('$name')";
   $sql2   = $this->db->query($query2)->result_array();

   foreach($sql2 as $value) {
     $array['child'] = array(
                        'child_name' => $value['child_name'],
                        'child_data' => $value['child_data']
                       );
   }
}

我试过运行codeigniter:命令不同步;你现在不能运行这个命令,因为我在过程之后使用过程,它没有运行。
任何形式的帮助都非常感谢

标签: phpcodeigniter

解决方案


使用 Model 与关联 this

在控制器中

$head = $this->Model_name->call_head();

foreach($head as $item) {
    $name = $item['name'];
    $array['name'] = $name;
    $array['data'] = $item['data'];

    $child = $this->Model_name->call_child($name);

    foreach($child as $value) {
        $array['child'] = array(
            'child_name' => $value['child_name'],
            'child_data' => $value['child_data']
           );
    }
}

在模型中

public function call_head()
{
    $query = "CALL PROCEDURE_HEAD()";
    $result = $this->db->query($query)->result_array();
    $query->next_result(); 
    $query->free_result();
    return $result;
}

public function call_child($name)
{
    $query = "CALL PROCEDURE_CHILD($name)";
    $result = $this->db->query($query)->result_array();
    $query->next_result(); 
    $query->free_result();
    return $result;
}

推荐阅读