PHP脚本不再写入数据库

时间:2016-09-15 07:48:26

标签: php mysql session

我有一个PHP脚本来记录页面上的点击并将计数存储在表格中。每个会话每页记录一次点击。

如果在更新点击次数之前访问过某个页面。

如果某个页面没有点击,因此表格中已经没有点击,则会生成一个条目,其计数从1开始。

它工作正常,但现在它已经破了 - 它更新了已经在数据库中有条目的页面的点击次数,但是没有为新页面添加条目。

谁能看到我出错的地方以及如何解决?

代码;

//start a PHP session
//this prevents spamming the click count by refreshing the page
session_start();


//create current page constant
$curPage = mysql_real_escape_string(htmlspecialchars($_SERVER['REQUEST_URI']));
$title =  '0';

//set number of clicks variable to 0
$clicks = 0;

//do not recount if page currently loaded
if($_SESSION['page'] != $curPage) {
   //set current page as session variable
   $_SESSION['page'] = $curPage;

   //try to connect to MySQL server
   if(!$link = mysql_connect($host, $user, $pass)) {
      echo "Could not connect to MySQL server. Check your login information; the MySQL server may also be offline or temporarily overloaded.";
   }
   //try to select database
   elseif(!mysql_select_db($dbname)) {
      echo "Cannot select database.";
   }
   else {
      //get current click count for page from database;
      //output error message on failure
      if(!$rs = mysql_query("SELECT * FROM click_count WHERE page_url = '$curPage'")) {
         echo "Could not parse click counting query.";
      }
      //if no record for this page found,
      elseif(mysql_num_rows($rs) == 0) {
         //try to create new record and set count for new page to 1;
         //output error message if problem encountered
         if(!$rs = mysql_query("INSERT INTO click_count (page_url, page_count) VALUES ('$curPage', 1)")) {
            echo "Could not create new click counter for this page.";
         }
         else {
            $clicks = 1;
         }
      }
      else {
         //get number of clicks for page and add 1
         $row = mysql_fetch_array($rs);
         $clicks = $row['page_count'] + 1;
         //update click count in database;
         //report error if not updated
         if(!$rs = mysql_query("UPDATE click_count SET page_count = $clicks WHERE page_url = '$curPage'")) {
            echo "Could not save new click count for this page.";
         }
      }
   }
}

更新:似乎问题可能与我的htaccess重写有关,但我不确定原因。

1 个答案:

答案 0 :(得分:0)

您应该调试代码以找出问题所在。如果它没有向数据库添加新页面,可能代码永远不会满足这个条件:

elseif(mysql_num_rows($rs) == 0)...

首先要做的是在代码中添加一行来检查是否真的满足条件,如下所示:

$rs = mysql_query("SELECT * FROM click_count WHERE page_url = '$curPage'");
echo "\n<hr>DEBUGGING: rs=$rs";
if(!$rs) {
  echo "Could not parse click counting query.";
}...
添加新页面时, $ rs应为零。否则,继续调试以了解为什么它与零不同。