0

当有人访问我的站点时,我想记录用户 ip,但是当您到达站点时,该表可能不存在,因此 UPDATE 查询给了我一个错误。而且我还需要检查现有表。我试过:阅读,但如果表不存在,似乎没有一个能解决这个问题。这可能是一个错字。

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

2 回答 2

5

您可能想查看INSERT ... ON DUPLICATE KEY UPDATE 语法,它允许您在密钥已存在时指定操作

于 2013-02-21T16:44:10.687 回答
0

我发现你的错字了。

您的(坏)代码具有更好的格式:

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

修复后:

$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
");

无论如何,您可能需要这样的东西:

    // 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
    }
于 2013-02-21T16:45:41.297 回答