1

I'm trying to make this code work but there is something is wrong whit it.

<?php
    $server = "localhost";
    $username = "root";
    $password = "";
    $database = "db";
    $connection = mysqli_connect($server, $username, $password, $database);
    if(mysqli_connect_errno())
    {
        echo("Failed-Connect");
        exit();
    }
    else
    {
        if(mysqli_ping($connection))
        {
            $query =
            "
            SET @a = 5;
            SET @b = 2;
            SELECT @c := col FROM whatever WHERE doesn't matter;
            IF @a > @b THEN
            UPDATE table2 SET col1 = col1 + 1, col2 = @c WHERE somthing = 'thething';
            END IF;
            ";
            $result = mysqli_multi_query($connection, $query);
            if($result)
            {
                echo("Done");
            }
        }
        else
        {
            echo("Failed-Ping");
        }
    }
    mysqli_close($enter code hereconnection);
    ?>

This code has no error but it does not update the row. When I remove the IF statement it works perfectly but I need that IF statement to validate something. Any idea whats wrong? If the code has major problem can you provide me whit an alternative?

1 Answer 1

2

A multi query is not equal to a stored routine and a code block like:

IF @a > @b THEN
  UPDATE table2 SET col1 = col1 + 1, col2 = @c WHERE somthing = 'thething';
END IF;

Is only valid in the context of a stored routine. So the given code has an error, and MySQL would have informed you about that if you would have added error checking.

You could write something like that:

UPDATE table2 SET col1 = col1 + 1, col2 = @c WHERE somthing = 'thething' AND (@a > @b);

So the update would only be done if @a > @b and if somthing = 'thething'.

Sign up to request clarification or add additional context in comments.

2 Comments

the IF block not only valid within a stored procedure but also in a function or trigger.
@RaymondNijland I changed it to stored routine if i'm not wrong this is the common name for all of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.