skip to Main Content

I have a table for formula grade where the user can create their own formula using the operator, column, dan number, which I have provided on app UI

formulaid tipe formula gradecatid
1 operator ( NULL
1 column PAS 5
1 operator + NULL
1 column PTS 4
1 operator ) NULL
1 operator / NULL
1 number 2 NULL

the math string is from formula column, column type is another value from another grade type

( PAS + PTS ) / 2

last process will become string

( Number + Number ) / 2

Note:
This formula only the sample, the formula can be in any form for other example ( 5+1+2+3) / 4, or 1 + 1, it’s not fix to this form ( Number + Number ) / 2, the user can create any formula with the given functionality as mention above, operator, number, and column.

Is it possible to evaluate this string in mysql to determine is valid math operation or not?

2

Answers


  1. Chosen as BEST ANSWER

    Finally I create this SP based on @Serg suggestion I try to create below SP for handling the error

    CREATE PROCEDURE SP_TEST()
    BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN 
    SHOW ERRORS; 
    END;      
    SET @sql = 'SELECT ( 100 + 100  / 2';
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    END;
    CALL SP_TEST();
    

    it will show error if there's any bad math operation

    Thanks All


  2. You use this code via regex [mysql]

    SELECT '(5+9)/2' REGEXP '\(([0-9]+)\+([0-9]+)\)\/2';
    

    can change ‘(5+9)/2’ to input value

    code example in w3schools mysql compiler

    operator regex code
    + \+
    * \/
    / \*
    \-
    ( \(
    ) \)
    int number ([0-9]+)
    float number ([0-9]+|[.|][0-9]+)

    it’s so hard )

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search