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'");
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
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
}