Why running queries one by one yields correct results, but running lots of them in one chunk doesn't? Let's say I create a simple table and a stored function to populate it:

CREATE TABLE t
(
    id INT PRIMARY KEY,
    val VARCHAR(255)
)//

CREATE FUNCTION populateIfNotAlreadyIn (idArg INT, valArg VARCHAR(255))
RETURNS BOOLEAN NOT DETERMINISTIC
BEGIN
    DECLARE alreadyIn INT;
    SELECT COUNT(id) INTO alreadyIn FROM t WHERE id = idArg;
    IF alreadyIn &lt;&gt; 0 THEN
        RETURN FALSE;
    ELSE
        INSERT INTO t (id, val) VALUES (idArg, valArg);
        RETURN TRUE;
    END IF;
END//


Of course, the intended behaviour is that the function returns 0 if a row with the given ID already exists in the table, and 1 if it doesn't (in the latter case, the function also inserts such a row).

So now testing comes.

If I run testing queries in phpmyadmin one by one like that:

SELECT populateIfNotAlreadyIn(1, 'val1');


//Go//

SELECT populateIfNotAlreadyIn(2, 'val2');


//Go//

… etc


Then apparently, the results are correct: the function returns 1 and inserts a row if and only if there is no row with such an id in the table, otherwise it returns 0.

So far, so good. But instead of running queries one by one, let's feed phpmyadmin with all of them at once. To be more specific, let's insert into phpmyadmin sth like this:

SELECT populateIfNotAlreadyIn(1, 'val1');
SELECT populateIfNotAlreadyIn(2, 'val2');
SELECT populateIfNotAlreadyIn(3, 'val3');
SELECT populateIfNotAlreadyIn(4, 'val4');
SELECT populateIfNotAlreadyIn(5, 'val5');


And then click Go, to run all of them.

Result? The rows are inserted correctly into table t. But the stored function returns incorrect values. Each call except the last one returns a 0.

Why does this happen?
SELECT populateIfNotAlreadyIn(1, 'val1'),
       populateIfNotAlreadyIn(2, 'val2'),
       populateIfNotAlreadyIn(3, 'val3'),
       populateIfNotAlreadyIn(4, 'val4'),
       populateIfNotAlreadyIn(5, 'val5') ;


Meanwhile, you could shorten the function to just

RETURN EXISTS(SELECT * FROM t WHERE id = idArg);