How to make sure that stored data is unique

public function insert_all() {
        $get_data = $this->call_api->fetchData('GET', 'http://89.201.137.7:8082/datasnap/rest/grupeartikala/lista', false);
        $response = json_decode($get_data);
        $data = $response->result[0]->grupe_artikala;
        foreach ($data as $item) {
            $sku = ltrim($item->grupa_artikla);
            $product = array(
                'sku' => $sku,
                'title' => $item->naziv,
                'enabled' => $item->enabled
            );
            try {
                $this->db->insert('products', $product);
                $db_error = $this->db->error();
                if (!empty($db_error)) {
                    throw new Exception("Database error! Error Code [" . $db_error['code'] . "] Error: " . $db_error['message']);
                }
            } catch (Exception $e) {
                log_message('error:', $e->getMessage());
                return;
            }
        }
        return $data;
    }

I fetch some data and save it to the database. It's around 200 elements.

public function insert_all_products()
    {
            $this->luceed_model->insert_all();
            redirect(site_url('/luceed_products/products'));
    }

I call the model from the controller. This method is run when the form submits.

<?php echo form_open('/luceed_products/insert_all_products', 'class="ciForm"'); ?>
<input type="submit" name="submit" value="Save To Database">
</form>

And the form. How can I make it submit data only if the entry is unique? I tried to make a conditional out of $this->db->where('sku !=', $sku) then to insert to database if that condition is true with $this->db->insert. I don't think I can use set_validation() to check for uniqueness since I am not storing data from input fields.

Edit: I set my SKU in the database as UNIQUE and now I get a Database Error duplicate entry when I try to save data that's duplicate.

The database error with error handling set to TRUE:
A Database Error Occurred Error Number: 1062

Duplicate entry '1' for key 'sku'

INSERT INTO products (sku, title, enabled) VALUES ('0001', 'Pokrivala za glavu', 'D')

Filename: C:/laragon/www/luceed/system/database/DB_driver.php

Line Number: 692

Database Error without error handling by codeigniter:
A PHP Error was encountered Severity: Notice

Message: Undefined index: ERROR:

Filename: core/Log.php

Line Number: 181

Backtrace:

File: C:\laragon\www\luceed\application\models\Luceed_model.php Line: 40 Function: log_message

File: C:\laragon\www\luceed\application\controllers\Luceed_products.php Line: 26 Function: insert_all

File: C:\laragon\www\luceed\index.php Line: 315 Function: require_once



Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)