MySQL行数用PHP计算并显示结果

时间:2015-02-05 23:25:11

标签: php mysql database count rows

我想创建一个API,当您访问它时,它将以文本格式显示我的数据库中有多少行的结果。

数据库信息:

Username: predator_db

DB Name: predator_db

Table Name: database

我尝试了几个代码而无法让它工作。

代码尝试了:

<?php
$con = mysql_connect("localhost","predator_db","PASS");
if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("predator_db", $con);

$result = mysql_query("select count(1) FROM database");
$row = mysql_fetch_array($result);

$total = $row[0];
echo "Total rows: " . $total;

mysql_close($con);
?>

代码响应:“总行数:”&lt;不显示有多少行。错误日志:

[05-Feb-2015 23:44:58 UTC] PHP Deprecated:  mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/predator/public_html/api/resolver/number.php on line 2
[05-Feb-2015 23:44:58 UTC] PHP Warning:  mysql_fetch_array() expects parameter 1 to be resource, boolean given in /home/predator/public_html/api/resolver/number.php on line 10

3 个答案:

答案 0 :(得分:1)

您尝试从database获取结果...而不是从predator_db的实际数据库中获取结果。

我会用基础知识来做,但请查看MySQLi准备好的语句和/或PDO。

$link = mysqli_connect("localhost", "predator_db", "PASS", "predator_db");
$result = mysqli_query($link, "select COUNT(id) AS count FROM `database`");
// make sure it worked
if(!$result) {
    die('Error: ' . mysqli_error($link));
} else {
    $num_rows = mysqli_fetch_assoc($result);
    // echo it
    echo "Rows: " . $num_rows['count'];
}

答案 1 :(得分:1)

首先,在保留关键字database之后命名表格不是一个好主意。但是,如果你打算走这条路,你总是要把名字放在反引号``中。所以,你的查询应该是

$result = mysql_query("select count(1) FROM `database`");

另外,请查看MYSQLi,因为旧的MySQL驱动程序已被弃用。

答案 2 :(得分:0)

<?php
$link = mysqli_connect("localhost", "DB_USER", "DB_PASS", "DB_NAME");
$result = mysqli_query($link, "select COUNT(*) AS count FROM DB_NAME.DB_TABLE");
if(!$result) {
    die('Error: ' . mysqli_error($link));
} else {
    $num_rows = mysqli_fetch_assoc($result);
    echo "Rows: " . $num_rows['count'];
}
?>