'Opencart 2 pass a variable from model to controller

I created the following code in model

public function coupon_test() { 
        $charscode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $res = "";
        for ($i = 0; $i < 10; $i++) {
        $res .= $charscode[mt_rand(0, strlen($charscode)-1)];
        }
       $this->db->query("INSERT INTO `" . DB_PREFIX . "coupon` SET name = 'Newsletter coupon', code = '" .$res . "', type = 'P', 
       discount = '10', logged = '0', shipping = '0', total = '0', date_start = CURRENT_DATE(), 
       date_end = DATE_ADD(CURRENT_DATE(), INTERVAL 6 DAY), status = '1', date_added = NOW()");  
               
         
            }

and in controller

public function Ajaxcallacumba() {
        $this->load->model('total/coupon');
        $this->model_total_coupon->coupon_test();
        
        
    }

What i want is to pass in my controller either the variable $res from my model or call the code variable from the database. How can i do this.



Solution 1:[1]

// controller
public function Ajaxcallacumba() {   
  $this->load->model('total/coupon');
  $brand_new_coupon = $this->model_total_coupon->coupon_test();
}

// model
public function coupon_test() { 
  while (true) {
    $charscode = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $res = "";
    for ($i = 0; $i < 10; $i++) {
      $res .= $charscode[mt_rand(0, strlen($charscode)-1)];
    }
    
    // check coupon code is unique, if yes, then break the loop
  }
        
  $this->db->query("INSERT INTO `" . DB_PREFIX . "coupon` SET name = 'Newsletter coupon', code = '" .$res . "', type = 'P', 
  discount = '10', logged = '0', shipping = '0', total = '0', date_start = CURRENT_DATE(), 
  date_end = DATE_ADD(CURRENT_DATE(), INTERVAL 6 DAY), status = '1', date_added = NOW()");
  
  return $res; // give back the coupon code to controller
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Baracsi Róbert