php切换到mysqli:num_rows问题

时间:2013-02-17 02:40:13

标签: php mysqli

我最近开始更新一些代码到MySQL改进的扩展,并且直到这一点已经成功:

// old code - works
$result = mysql_query($sql);
    if(mysql_num_rows($result) == 1){
    $row = mysql_fetch_array($result);
    echo $row['data'];
    }


// new code - doesn't work
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); 
    if($result->num_rows == 1) {
    $row = $result->fetch_array();
    echo $row['data'];
    }

如图所示,我正在尝试使用面向对象的样式。 我没有得到mysqli错误,vardump说没有数据......但db表中肯定有数据。

3 个答案:

答案 0 :(得分:6)

试试这个:

<?php

// procedural style

$host = "host";
$user = "user";
$password = "password";
$database = "db";

$link = mysqli_connect($host, $user, $password, $database);

IF(!$link){
    echo ('unable to connect to database');
}

ELSE {
$sql = "SELECT * FROM data_table LIMIT 1";
$result = mysqli_query($link,$sql);
    if(mysqli_num_rows($result) == 1){
    $row = mysqli_fetch_array($result, MYSQLI_BOTH);
    echo $row['data'];
    }
}
mysqli_close($link);


// OOP style 

$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table LIMIT 1";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
    if($result->num_rows == 1) {
    $row = $result->fetch_array();
    echo $row['data'];
    }

    $mysqli->close() ;

// In the OOP style if you want more than one row. Or if you query contains more rows.    

$mysqli = new mysqli($host,$user, $password, $database);
$sql = "SELECT * FROM data_table";
$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]"); /* I have added the suggestion from Your Common Sence */
    while($row = $result->fetch_array()) {
     echo $row['data']."<br>";
    }

    $mysqli->close() ;    

?>

答案 1 :(得分:1)

在PHP v 5.2中,在从查询结果中提取数据行之前未设置mysqli :: num_rows:

$mysqli = new mysqli($host,$user, $password, $database);

if ($mysqli->connect_errno) {
    trigger_error(sprintf(
        'Cannot connect to database. Error %s (%s)',
        $mysqli->connect_error,
        $mysqli->connect_errno
    ));
}

$sql = "SELECT * FROM data_table";

$result = $mysqli->query($sql);

// a SELECT query will generate a mysqli_result
if ($result instanceof mysqli_result) {
    $rows = array();
    while($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }

    $num_rows = $result->num_rows; // or just count($rows);

    $result->close();

    // do something with $rows and $num_rows
} else {
    //$result will be a boolean
}

$mysqli->close() ;    

答案 2 :(得分:0)

正如所说,你没有检查错误 以这种方式运行所有查询

$result = $mysqli->query($sql) or trigger_error($mysqli->error." [$sql]");

如果没有显示错误且var转储没有数据 - 那么答案很简单:您的查询没有返回任何数据。检查表中的查询和数据。