duanpanyang1962 2012-01-18 15:25
浏览 15
已采纳

mysql中的计数器不起作用

I'am trying to implement a "most popular searches" function on a web site using a simple counter. The idea is that the first time a search is made, the query is stored in a special table. After that the count number increments by one every time that same search is made. I think I do exactly as I should but the code doesn't seem to work. The count value stays on NULL in the table. Here's my code. "Searchny" is the table where I store the searches. Any pointers much appreciated!

$search_result = mysql_query("SELECT * FROM searchny WHERE sok='$sokt'");

if(mysql_num_rows($search_result) == 0 ) { 
    $sql = "INSERT INTO searchny (sok, dt) VALUES ('" . $sokt . "', NOW());"; 
    mysql_query($sql);
}
else {
    mysql_query("UPDATE searchny SET count = count+1 WHERE sok='$sokt'");
} 
  • 写回答

3条回答 默认 最新

  • dousi6701 2012-01-18 15:48
    关注

    Your problem is most likely that count is NULL. Anything added to NULL is NULL.

    Try this query:

    SELECT NULL + 1
    

    The result will be:

    NULL
    

    You could set your default value for the count field to 0 instead.

    However, here's a simpler way to implement this. Note that I've excluded the date field because I don't know what the requirements for the date are:

    Table searchny:
    ---------
    sok
    count
    ---------
    primary_key (sok)
    

    Then do it all in one statement:

    INSERT INTO searchny (sok, count) VALUES ($sokt, 1)
      ON DUPLICATE KEY UPDATE count = count + 1
    

    If it's a new sok value, then a new row is inserted and the count is set to 1. If the sok value already exists, then the record's count is incremented by 1.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错