PHP动态计数功能

时间:2014-12-15 08:55:04

标签: php mysql

我正在尝试为mysql中的count计算一个动态函数:

的functions.php:

  function countEntries($table, $where = '', $what = '')
  {
      if (!empty($where) && isset($what)) {
          $q = "SELECT COUNT(*) FROM " . $table . "  WHERE " . $where . " = '" . $what . "' LIMIT 1";
      } else{
          $q = "SELECT COUNT(*) FROM " . $table . " LIMIT 1";
      }
      $record = query($q);
      $total = fetchrow($record);
      return $total[0];
  }

HTML代码:

<?php echo countEntries("news", "category", "1"); ?>
<?php echo countEntries("post", "type", "Sports"); ?>

但仍然有空白页面没有任何错误!

3 个答案:

答案 0 :(得分:0)

你可以尝试一下。

function countEntries($table, $where = '', $what = '')
      {
          if (!empty($where) && isset($what)) {
              $q = "SELECT COUNT(*) AS count FROM " . $table . "  WHERE " . $where . " = '" . $what . "' LIMIT 1";
          } else{
              $q = "SELECT COUNT(*) AS count FROM " . $table . " LIMIT 1";
          }
          $record = query($q);
          $total = fetchrow($record);
          return $total['count'];
      }

这里给出count(*)的别名,并使用它来访问返回的结果$ total ['count']。 希望它有所帮助。

答案 1 :(得分:0)

  

您忘记关闭其他事项的第一件事,第二件事只需添加此行&#34; ini_set(&#34; display_errors&#34;,1); &#34;在你的php.this的顶部将显示你的PHP中的错误。

您的代码:

function countEntries($table, $where = '', $what = '')
{
  if (!empty($where) && isset($what)) {
      $q = "SELECT COUNT(*) FROM " . $table . "  WHERE " . $where . " = '" . $what . "' LIMIT 1";
  } else
      $q = "SELECT COUNT(*) FROM " . $table . " LIMIT 1";
  }
  $record = query($q);
  $total = fetchrow($record);
  return $total[0];
}

我的代码:

   function countEntries($table, $where = '', $what = '')
      {
      if (!empty($where) && isset($what)) {
          $q = "SELECT COUNT(*) AS count FROM " . $table . "  WHERE " . $where . " = '" . $what . "' LIMIT 1";
      } else{
          $q = "SELECT COUNT(*) AS count FROM " . $table . " LIMIT 1";
      }
      $record = query($q);
      $total = fetchrow($record);
      return $total['count'];
  }

答案 2 :(得分:0)

谢谢你们,它现在运作良好:

function countEntries($table, $where, $what)
{
  if (!empty($where) && isset($what)) {
      $q = "SELECT COUNT(*) FROM " . $table . "  WHERE " . $where . " = '" . $what . "' LIMIT 1";
  } else
    $q = "SELECT COUNT(*) FROM " . $table . " LIMIT 1";
    $record = mysql_query($q);
    $total = mysql_fetch_array($record);
    return $total[0];
}


echo countEntries('news', "type", "sport");