0

When someone visits my site, i want to log the users ip, but when you arrive to the site the table might not exist, so the UPDATE query gives me an error. And I also need to check against existing tables. I've tried: reading, but none seems to cover this problem, if the table dont exist. It's probably a typo.

$db->query("INSERT INTO track (tm, user_agent, host, ip, port, lang) VALUES ('$tm','$user_agent','$host','$ip','$port','$lang') WHERE NOT EXISTS (
    SELECT ip FROM track WHERE ip='$ip'");

2 Answers2

5

You probably want to look at the INSERT ... ON DUPLICATE KEY UPDATE Syntax which allows you to specify an action if the key is already present

Rowland Shaw
  • 36,411
  • 12
  • 91
  • 161
0

I found your typo.

Your (bad) code with better formatting:

$db->query("
    INSERT INTO track (
        tm, 
        user_agent, 
        host, 
        ip, 
        port, 
        lang
    ) 
    VALUES (
        '$tm',
        '$user_agent',
        '$host',
        '$ip',
        '$port',
        '$lang'
    ) 
    WHERE NOT EXISTS 
    (
        SELECT ip FROM track WHERE ip='$ip'
");

after fix:

$db->query("
    INSERT INTO track (
        tm, 
        user_agent, 
        host, 
        ip, 
        port, 
        lang
    ) 
    VALUES (
        '$tm',
        '$user_agent',
        '$host',
        '$ip',
        '$port',
        '$lang'
    ) 
    WHERE NOT EXISTS 
    (
        SELECT ip FROM track WHERE ip='$ip'
    ) -- that was missing
");

Anyway, you may need something like this:

    // check if ip exists
    $query = $db->$query("
        SELECT count(ip) FROM track WHERE ip='$ip'
    ");

    $result = $query->fetchFirstRowSomehow(); // i dont know methods you have in $db object

    $rows = $result['0']; // getting first (only) column that should contain count()

    if ($rows == 0)
    {
        // your insert code here
    }
    else
    {
        // your update code here
    }
Kamil
  • 11,919
  • 23
  • 72
  • 160