I am trying to insert the current time() and $_SERVER['REMOTE_ADDR']; into my database
I have this code

<?php
    require_once("../core/core.php");

    $user_time = time();
    $ip = $_SERVER['REMOTE_ADDR'];
    $sql = "SELECT * FROM userinfo WHERE ip = $ip";
    $result = $conn->query($sql);

    if(!$result) {
        trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR); <-- line 10
        echo "Database connection failed.";
    } else {
        if($result->num_rows == 0){
            trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);

            $sql = "INSERT INTO userinfo (ip, time) VALUES ('$ip', '$user_time')";
            $conn->query($sql);
            echo "IP ADDRESS SAVED successfully";
        } else if($result->num_rows >= 1) {
            $sql = "UPDATE userinfo SET time = '$user_time' WHERE `ip` = '$ip'";
            $conn->query($sql);
            echo "IP ADDRESS UPDATED successfully";
        }
    }
?>

But i get an error Fatal error: Wrong SQL: SELECT * FROM userinfo WHERE ip = my_real_ip Error: 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 '.103.25' at line 1 in /home/appunloc/domain/folder/index.php on line 10

It looks like there's a problem with the SQL query on line 10. The error message indicates that there's a syntax error near the IP address in the WHERE clause. This is probably because the IP address is not enclosed in single quotes, which are required for string values in SQL.

Try modifying the query on line 10 to enclose the IP address in single quotes, like this:

$sql = "SELECT * FROM userinfo WHERE ip = '$ip'";

Alternatively, you could use the filter_var() function to sanitize the IP address before inserting it into the SQL query. This can help prevent SQL injection attacks by removing potentially harmful characters from the input. Here's how you could use filter_var() to sanitize the IP address in this code:

$ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_SANITIZE_STRING);
$sql = "SELECT * FROM userinfo WHERE ip = '$ip'";

I hope this helps! Let me know if you have any other questions

Thank you so much <3

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.