借助数据库在PHP中创建一个命中计数器?

时间:2015-02-02 12:22:30

标签: php mysql database

我有网址http://siteurl/directory/onemore/ $ fileID.php的网页 我试图只提取$ fileID,然后使用

$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
$hits = $hits + 1;
$query = $mysqli->query("UPDATE tablename SET HITS = $hits WHERE ID = $fileID");
echo 'Total hits on page'.$hits.'';

我无法弄清楚如何获得$ fileID部分,并想问我的其余程序是否正确?

修改

使用上面的代码命中时会遇到问题。我想在每次刷新页面后,他们会更新为+1。

4 个答案:

答案 0 :(得分:2)

您可以像这样确定$ fileId:

/* $_SERVER['PHP_SELF'] results to e.g. '/directory/onemore/5.php' */
/* basename(...) results to e.g. '5.php' */
$fileName = basename($_SERVER['PHP_SELF']);
/* take the text before the last occurrence of '.' */
$fileID = substr($fileName, 0, strrpos($fileName, '.'));


$query = $mysqli->query("UPDATE tablename SET HITS = HITS + 1 WHERE ID = $fileID");

$query = $mysqli->query("SELECT * FROM tablename WHERE ID = $fileID");
$rows = mysqli_fetch_array($query);
$hits = $rows['HITS'];
echo 'Total hits on page'.$hits.'';

答案 1 :(得分:1)

试试这个:

<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';

print_r(parse_url($url));

echo parse_url($url, PHP_URL_PATH);
?>
  

输出

Array
(
    [scheme] => http
    [host] => hostname
    [user] => username
    [pass] => password
    [path] => /path
    [query] => arg=value
    [fragment] => anchor
)

看,如果有帮助。

答案 2 :(得分:1)

如果您不需要每次都打印匹配,可以在单个查询中递增它,这样更清晰,更有效。

UPDATE tablename SET hits = hits + 1 WHERE id = $fileID

答案 3 :(得分:0)

获取URL的$ fileID: 看看pathinfo() - 此功能提取不同部分的网址

在你的情况下,它将是:

$path_parts = pathinfo($_SERVER["SCRIPT_FILENAME"]);
$fileID = $path_parts['filename']; 

您的更新查询将起作用,如果您只想计算而不显示新值,您可以使其更简单 - 只需在更新表格行时增加HITS:

$query = mysqli->query("UPDATE tablename SET HITS = HITS+1 WHERE ID = $fileID");