Archive

Archive for March, 2012

Verify EAN 13 in MySql

23 March 2012 6 comments

To verify the correct structure of an EAN13  with MySql we can create a function as the follow.

DROP FUNCTION IF EXISTS FNC_IS_VALID_EAN13;

DELIMITER $$
CREATE FUNCTION FNC_IS_VALID_EAN13(_ean VARCHAR(13)) RETURNS tinyint(4)
READS SQL DATA
BEGIN
DECLARE _correct_ean TINYINT;
DECLARE _even_sum SMALLINT;
DECLARE _odd_sum SMALLINT;
DECLARE _check_digit SMALLINT;
DECLARE _check_number SMALLINT;
IF LENGTH(_ean) 13 THEN RETURN 0; END IF;
IF NOT _ean REGEXP ‘^[0-9]+$’ THEN RETURN 0; END IF;
SELECT SUBSTR(_ean, 0, 1)+SUBSTR(_ean, 2, 1)+SUBSTR(_ean, 4, 1)+SUBSTR(_ean, 6, 1)+SUBSTR(_ean, 8, 1)+SUBSTR(_ean, 10, 1) INTO _even_sum;
SELECT SUBSTR(_ean, 1, 1)+SUBSTR(_ean, 3, 1)+SUBSTR(_ean, 5, 1)+SUBSTR(_ean, 7, 1)+SUBSTR(_ean, 9, 1)+SUBSTR(_ean, 11, 1) INTO _odd_sum;
SELECT ( (10-(3*_even_sum + _odd_sum)%10)%10 ) INTO _check_digit;
SELECT SUBSTR(_ean, 13, 1) INTO _check_number;
SELECT IF(_check_number=_check_digit,1,0) INTO _correct_ean;
RETURN _correct_ean;
END$$
DELIMITER ;

 

To use it simply just type into your queries something like this:

SELECT ean, FNC_IS_VALID_EAN13 (ean) as isValid FROM MY_TABLE;

That’s it

Verify EAN 13 with PHP

23 March 2012 4 comments

Here the function to verify a correct EAN13 structure.

function validate_EAN13Barcode($barcode)
{
    // check to see if barcode is 13 digits long
    if (!preg_match("/^[0-9]{13}$/", $barcode)) {
        return false;
    }

    $digits = $barcode;

    // 1. Add the values of the digits in the 
    // even-numbered positions: 2, 4, 6, etc.
    $even_sum = $digits[1] + $digits[3] + $digits[5] +
                $digits[7] + $digits[9] + $digits[11];

    // 2. Multiply this result by 3.
    $even_sum_three = $even_sum * 3;

    // 3. Add the values of the digits in the 
    // odd-numbered positions: 1, 3, 5, etc.
    $odd_sum = $digits[0] + $digits[2] + $digits[4] +
               $digits[6] + $digits[8] + $digits[10];

    // 4. Sum the results of steps 2 and 3.
    $total_sum = $even_sum_three + $odd_sum;

    // 5. The check character is the smallest number which,
    // when added to the result in step 4, produces a multiple of 10.
    $next_ten = (ceil($total_sum / 10)) * 10;
    $check_digit = $next_ten - $total_sum;

    // if the check digit and the last digit of the 
    // barcode are OK return true;
    if ($check_digit == $digits[12]) {
        return true;
    }

    return false;
}
Categories: Functions, PHP
%d bloggers like this: