【问题标题】:Codeigniter transferring data from one table to another using for loopCodeigniter 使用 for 循环将数据从一个表传输到另一个表
【发布时间】:2020-05-04 01:45:00
【问题描述】:

我试图在我的模型中将数据从一个表移动到另一个表。在前两行中,我得到了“购物车”表中与用户名匹配的所有行。我现在正在尝试遍历所有这些并将产品 ID 与我的“产品”表中的产品 ID 匹配。然后我尝试格式化数据以适合我的名为“已售”的新表。但是我收到一个错误。我认为 $q->id、$q->product_name 等的语法是错误的。我知道您通常可以在视图中使用它,但它在模型中不起作用。你知道这样做的正确语法是什么吗?

 function checkout($username){
    $this->db->where('username', $username);
    $query = $this->db->get('cart');
    //$data = array();

    foreach ($query as $q){
        $product = $this->db->get_where('product', array('id' => $q->id));
        $arr['product_id'] = $product->id;
        $arr['product_brand'] = $product->item_brand;
        $arr['product_name'] = $product->item_name;
        $arr['product_image'] = $product->item_image_url;
        $arr['product_price'] = $product->item_price;
        $arr['product_size'] = $product->item_size;
        $arr['name_of_seller'] = $product->name_of_lister;
        $arr['name_of_buyer'] = $this->session->userdata('username');

        $this->db->insert('sold', $arr);
    }
    //Deletes the items out of the cart
   // $this->db->delete('cart');
}

这是我收到的错误消息

【问题讨论】:

  • 您好,欢迎您,当您想显示一些非常重要的信息(例如收到的错误消息)时,最好避免在问题中使用图片。图片不能被搜索引擎索引。

标签: php sql codeigniter


【解决方案1】:

您必须使用result() 来获取$query 变量中的数据。

$query = $this->db->get('cart')->result();

同样的方法,也改变第二个查询。

$product = $this->db->get_where('product', array('id' => $q->id))->result();

看看这对你有没有帮助。

【讨论】:

    【解决方案2】:
    function checkout($username){
    $this->db->where('username', $username);
    $query = $this->db->get('cart');
    
    if ($query->num_rows()>0) {
        $qdata = $query->result_array();
    
        foreach ($qdata as $key => $qdvalue) {
            $this->db->where('id', $qdvalue['id']);
            $product = $this->db->get('product');
            $pdata = $product->row_array()
            $inarray = array(
                'product_id'        =>      $pdata['id'],
                'product_brand'     =>      $pdata['item_brand'],
                'product_name'      =>      $pdata['item_name'],
                'product_image'     =>      $pdata['item_image_url'],
                'product_price'     =>      $pdata['item_price'],
                'product_size'      =>      $pdata['item_size'],
                'name_of_seller'    =>      $pdata['name_of_lister'],
                'name_of_buyer'     =>      $this->session->userdata('username')
            );
    
            $this->db->insert('sold', $inarray);
        }//end of foreach
    }//end of if query
    }//end of checkout function
    

    如果所有列的值都正确,我会重写你的函数它会起作用。 我会建议你对这种类型的数据库事件使用事务。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多