Welcome Guest, Not a member yet? Register   Sign In
UPDATE when exists otherwise INSERT (with active Record) Best practice?
#11

[eluser]Peter O'Sullivan[/eluser]
Correct me if I'm wrong xwero, but your code

Code:
// Check if a record exists for this SKU
$this->db->where('sku',$sku);
if ($this->db->count_all_results() == 0) {

Needs to have the a 'from' part.

The code needs to be

Code:
// Check if a record exists for this SKU
$this->db->from('products')->where('sku',$sku);
if ($this->db->count_all_results() == 0) {

Correct?
#12

[eluser]TheFuzzy0ne[/eluser]
Or the table name can be passed into the count_all_results() method as a parameter.
#13

[eluser]xwero[/eluser]
I never wrote the method worked Smile
Code:
function save($sku = NULL, $label = NULL, $price = NULL) {
  $this->db->start_cache();
  $this->db->from('products');
  $this->db->stop_cache()
  // The SKU is our unique ID, if it doesn't exist - we're screwed
  if ($sku !== NULL) {
    // In this example, label and price are optional and can be inserted as NULL
    $record = array('sku'=>$sku, 'label'=>$label, 'price'=>$price);
    // Check if a record exists for this SKU
    $this->db->where('sku',$sku);
    if ($this->db->count_all_results() == 0) {
      // the check can be chained for less typing
      // $this->db->where('sku',$sku)->count_all_results()
      // A record does not exist, insert one.
      $query = $this->db->insert('', $record);
    } else {
      // A record does exist, update it.
      $query = $this->db->update('', $record, array('sku'=>$sku));
    }
    $this->db->flush_cache();
    // Check to see if the query actually performed correctly
    if ($this->db->affected_rows() > 0) {
      return TRUE;
    }
    return FALSE;
  }
  return FALSE;
}




Theme © iAndrew 2016 - Forum software by © MyBB