执行$ stmt-> num_rows时返回0

时间:2017-09-16 12:00:19

标签: php mysqli

我是mysqli的新手。我正在连接到mysql数据库,并获取一些数据。

$user_id = "CCD_00005";

    /* create a prepared statement */
    if ($stmt = mysqli_prepare($GLOBALS['conn'], "SELECT user_name FROM user_master WHERE user_id=?")) {

        /* bind parameters for markers */
        mysqli_stmt_bind_param($stmt, "s", $user_id);

        /* execute query */
        mysqli_stmt_execute($stmt);

        /* bind result variables */
        mysqli_stmt_bind_result($stmt, $user_name);

        /* fetch value */
        mysqli_stmt_fetch($stmt);

        echo("Total Results:".$stmt->num_rows."<br />");

        printf("%s is having name %s\n", $user_id, $user_name);

        /* close statement */
        mysqli_stmt_close($stmt);
 }

我收到了结果Total Results:0 CCD_00005 is having name sdafasdf

为什么我没有将行数计为1。

请帮忙。

1 个答案:

答案 0 :(得分:1)

按如下所示更改执行顺序:

$user_id = "CCD_00005";

    /* create a prepared statement */
    if ($stmt = mysqli_prepare($GLOBALS['conn'], "SELECT user_name FROM user_master WHERE user_id=?")) {

        /* bind parameters for markers */
        mysqli_stmt_bind_param($stmt, "s", $user_id);

        /* execute query */
        mysqli_stmt_execute($stmt);

        mysqli_stmt_store_result($stmt);        
        echo("Total Results:".mysqli_stmt_num_rows($stmt)."<br />");

        /* bind result variables */
        mysqli_stmt_bind_result($stmt, $user_name);

        /* fetch value */
        mysqli_stmt_fetch($stmt);


        printf("%s is having name %s\n", $user_id, $user_name);

        /* close statement */
        mysqli_stmt_close($stmt);