PHP和SQL计数记录

时间:2015-03-08 14:42:52

标签: php sql

我想在mytable的列中显示一个数字。

SELECT COUNT(0) FROM `db`.`tbl`;

以及代码的结果:

  

资源ID#5

这需要打印“2”。

这是我的代码:

        $icon = mysql_query("SELECT * FROM `**`.`**`;");
        // Here the problem!!
$count = mysql_query("SELECT COUNT(*) FROM `**`.`**`;");
        echo $count;

    if ($icon == 0) {
        $per = "URL";
        $title = "TITLE";
    }
    else if($icon =! 0)  {
        $per = "*****";
// Here the problem!!
        $title = "(".$count.") COUNT";
    }
    else {
        $per = "****";
        $title = "TITLE";
    }
        echo "
        <link rel='icon' type='image/x-icon' href='$per' />
        <link rel='icon' type='image/png' href='$per' />
        <title>$title</title>
        ";

3 个答案:

答案 0 :(得分:2)

如果要显示表格中的列数,则可以使用:

select count(*)
from information_schema.columns
where table_name = 'tbl' and table_schema = 'db';

答案 1 :(得分:1)

您需要在将来更好地撰写问题。它似乎也在计算列,而不是行。

$icon = mysql_query("SELECT * FROM `**`.`**`;");
$row = mysql_fetch_assoc($icon);
$icon_result = $row['COLUMNAME'];
$count = mysql_query("SELECT COUNT(*) as counter FROM `**`.`**`;");
$row = mysql_fetch_assoc($count);
$count_result = $row['counter'];
echo $count_result;
if ($icon == 0) {
    $per = "URL";
    $title = "TITLE";
} else if($icon != 0)  {
    $per = "*****";
    $title = "($count) COUNT";
} else {
    $per = "****";
    $title = "TITLE";
}
echo "<link rel='icon' type='image/x-icon' href='$per' />
<link rel='icon' type='image/png' href='$per' />
<title>$title</title>";

这是函数doc。 http://php.net/manual/en/function.mysql-fetch-assoc.php

答案 2 :(得分:0)

sql应该是

SELECT COUNT(*) FROM `db`.`tbl`;

我认为你在php中获得记录集的结果。你需要使用函数fetch_assoc()来获取记录。