Welcome Guest, Not a member yet? Register   Sign In
form validation is_unique using array
#1

I have a for that inputs a batch of data into the database. The form has one field where the barcodes for a product are inserter, seperated by comma's. Using explode I make an array out of it. 

What I want is to validate if each of the items in the array is unique in the database. Normally I would use the is_unique validator to check just one barcode. Is there a way to use is_unique for the full array?
Reply
#2

I don't think it can be used with an array, but maybe you can use a for loop with the check() function (https://codeigniter.com/user_guide/libra...te-1-value)

Something like this:
PHP Code:
foreach ($barcodes as $barcode)
{
    if ( ! 
$validation->check($barcode'is_unique[...todo add your table and field name...]'))
    {
        // Not unique
    
}

CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#3

That was exactly what I needed! Thanks!
Reply
#4

@includebeer Looks ugly.

PHP Code:
//with model 
$model = new Model();
// array or null
$notUniqueValues $model->whereIn('field'$arrayOfValues)->groupBy('field')->findColumn('field');

//without model 
$result db_connect()->table('table')->select('field')->whereIn('field'$arrayOfValues)->groupBy('field')->get()->getResultArray();
$notUniqueValues $result array_column($result'field') : null
Reply
#5

@iRedds How is your solution better than calling a simple check() function? Why would you build a SQL request yourself when the framework can do it for you?
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply
#6

@includebeer Answer the question. Which is better than 1 SQL query or N-SQL queries?

Each tool must be used correctly.
When you hold a hammer in your hands, everything around becomes nails.
Reply
#7

(04-20-2021, 01:08 AM)iRedds Wrote: @includebeer Answer the question. Which is better than 1 SQL query or N-SQL queries?

Each tool must be used correctly.
When you hold a hammer in your hands, everything around becomes nails.

Haha! That is some dense BS! Micro-optimization is not the solution either. It's not like he have 5000 record to check or if the table contains millions of record. If you have a simple form with something like 10 values to check in the database, you won't gain anything with your solution. You are better off optimizing the database with indexes than trying to cram everything in a single request. Building a custom request for each use case is worst that reusing a simple select. Don't forget that database engines also have built-in optimization and cache.
CodeIgniter 4 tutorials (EN/FR) - https://includebeer.com
/*** NO support in private message - Use the forum! ***/
Reply




Theme © iAndrew 2016 - Forum software by © MyBB