• Hy I am trying to store some data in the database
    I have the PHP file ‘activity.php’ where I am getting the data

    Somehow I am able to store the data in the database using this statement
    INSERT INTOactivity(ip_address,activity) VALUES ('$i','activity);

    now what I want is that I want to look for the already existing ip address value in the database
    like if the value of the same IP address already exists then update the data else insert the data in a new row

    I am using this in the PHP file

    IF EXISTS (SELECT * FROMactivity` WHERE ip_address = $i)
    BEGIN
    UPDATE activity
    SET activity=’this is some random value’
    WHERE ip_address = $i;
    END
    ELSE
    BEGIN
    INSERT INTO activity (ip_address,activity) VALUES (‘$i’,’activity);
    END”;`

    but its giving me an error saying

    You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘IF EXISTS

    I pasted the same code in the console of PHPmyadmin and got an error there too

    ‘Unrecognised statement type neat If-Else’

    Why I am getting this error and how can I resolve it

    NOTE: I just want to check if a value exists then update the row else insert a new row

    Thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • Use INSERT … ON DUPLICATE KEY UPDATE statement see

    https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

    Thread Starter jasghar

    (@jasghar)

    Thanks for your response
    I used as mentioned in the example plus I searched on internet about it but I’m still getting an error message

    ‘You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ”3’

    I am using the below code

    if($conn) {
            echo 'connected to database';
            $sql = "INSERT INTO <code>activity</code> 
            set id = '2',
                ip_address = '$i',
                activity = '$inserelize'
            ON DUPLICATE KEY UPDATE
            id = values('3'),
            activity = values('$inserelize')";
    
            $result = mysqli_query($conn, $sql);
            if($result) {
                echo 'data inserted';
            }else{
                echo mysqli_error($conn);
            }
        }else {
            echo 'error in connecting to database';
        }
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to use if else statement for SQL in PHP’ is closed to new replies.