如何使用PHP获取MySQL表中的行数?

时间:2013-10-11 09:44:43

标签: php mysql mysqli

为什么我的代码在行$result = mysql_query("SELECT * FROM institutions");上返回500内部服务器错误我是否做了一些可怕的错误?我想要做的就是在我刚刚向该表添加一行之后,计算MySQL表中的行数(称为' institutions')。

    $institution_sql = "
    INSERT INTO `institutions`
    (`InstitutionName`, `HeaderPictureID`, `Description`, `DevicesInfo`, `DoingInfo`, `FacebookPage`, `Location`, `TwitterHandle`, `Website`, `CreatedAt`)
    VALUES
    (" . nz($_POST['TempInstitutionName']) . ", 74, 'N/A', 'N/A', 'N/A', 'N/A', 'On the Internet', 'N/A', 'N/A', NOW())
    ";

    $mysqli->query($institution_sql);
    if ($mysqli->errno) {
        $dbreturn['status'] = "PASSWORD_FAILURE";
    } else {
        $dbreturn['status'] = "EXEC_SUCCESS";

        $result = mysql_query("SELECT * FROM institutions");
        $rows = mysql_num_rows($result);
        echo "There are " . $rows . " rows in my table.";

        $insert_sql = "
        INSERT INTO `users`
        (`Handle`, `Email`, `FirstName`, `LastName`, `InstitutionID`, `TempInstitutionName`, `TwitterHandle`, `ProfilePictureID`, `HeaderPictureID`, `AccountType`, `CreatedAt`)
        VALUES
        (" . nz($_POST['Handle']) . ", " . nz($_POST['Email']) . ", " . nz($_POST['FirstName']) . ", " . nz($_POST['LastName']) . ", $num_rows, " . nz($_POST['TempInstitutionName']) . ", " . nz($_POST['TwitterHandle']) . ", " . nz('75') . ", " . nz('74') . ", " . nz($_POST['AccountType']) . ",NOW())
        ";

        $mysqli->query($insert_sql);
        if ($mysqli->errno) {
            $dbreturn['status'] = "EXEC_FAILURE";
        } else {
        $dbreturn['status'] = "EXEC_SUCCESS";

        $insertid = $mysqli->insert_id;

        $password_sql = "
        INSERT INTO `passwords`
        (`UserID`)
        VALUES
        ('$insertid')
        ";

        $mysqli->query($password_sql);
        if ($mysqli->errno) {
            $dbreturn['status'] = "PASSWORD_FAILURE";
        } else {
            $dbreturn['status'] = "EXEC_SUCCESS";
        }

        } //todo: use a transaction here

    }

5 个答案:

答案 0 :(得分:3)

$ result = mysql_query(“SELECT count(*)FROM institutions”);

这将直接返回行数。

此链接可以向您详细说明

http://dev.mysql.com/doc/refman/5.1/en/counting-rows.html

答案 1 :(得分:1)

您的问题是您将MYSQLIMYSQL混合

使用mysqli

重写代码
    $result = $mysqli->query("SELECT * FROM institutions");
    $rows = $result->num_rows ;
  //  and so on ...

您通过mysqli连接,然后在代码中使用mysql。

答案 2 :(得分:1)

使用

$result = $mysqli->query($institution_sql);
$result->num_rows;

或者对于普通的旧mysql

$result = mysql_query($institution_sql);
mysql_num_rows($result);

答案 3 :(得分:1)

试试这个:

$result = mysql_query("SELECT count(*) FROM institutions");

MySQL文档:http://dev.mysql.com/doc/refman/5.0/en/select.html

此外:http://www.w3schools.com/sql/sql_func_count.asp

SQL COUNT(*) Syntax

COUNT(*)函数返回表中的记录数:

答案 4 :(得分:0)

...也应该是:

VALUES     ('“。nz($ _ POST ['TempInstitutionName'])。”',74

注意单引号[除非'nz'函数负责处理]。