PHP - MySQLi UPDATE +1确实增加了2

时间:2014-12-04 04:03:22

标签: php mysqli

我试图在页面加载时计算页面浏览量,但是无论何时我加载页面' UPDATE SET views = views + 1'实际上是在添加2.我已经在下面找到了我的代码,如果有人提出任何令人敬畏的建议。

// Create database connection
$db = new mysqli($db[host], $db[user], $db[pass], $db[data]);

// Display database connection error (if applicable)
if (mysqli_connect_errno()){
    printf("Connect failed: %s\n", mysqli_connect_errno());
    exit();
}

// Define Visitor Variables
$visitor[ip] = $_SERVER['REMOTE_ADDR']?:($_SERVER['HTTP_X_FORWARDED_FOR']?:$_SERVER['HTTP_CLIENT_IP']);

// Checks database to see if ip exists in logs
$check[ip] = $db->query("SELECT ip FROM admin_views WHERE ip = '$visitor[ip]'");

// If ip is found in database, update page views counter if it's not found, create a record for it
if ($check[ip]->num_rows == 1){
    $db->query("UPDATE admin_views SET views = views +1 WHERE ip = '$visitor[ip]'");
} else {
    $db->query("INSERT INTO admin_views VALUES('NULL', '$visitor[ip]')");
    echo "not found";
}

// Count the number of views
$count_views = "SELECT SUM(views) AS countViews FROM admin_views";

if ($result = $db->query($count_views)) {

    while ($row = $result->fetch_assoc()) {
       $views = $row['countViews'];
    }

    $result->free();
}

// Count unique page views
$count_unique_views = "SELECT id FROM admin_views ORDER BY id DESC LIMIT 1";

if ($result = $db->query($count_unique_views)) {

    while ($row = $result->fetch_assoc()) {
       $unique_views = $row['id'];
    }

    $result->free();
}

// Close database connection
$db->close();

0 个答案:

没有答案