本文介绍了PHP切换到mysqli:num_rows问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始将一些代码更新为MySQL改进的扩展,并且到现在为止一直很成功:

I recently started updating some code to MySQL improved extension, and have been successful up until this point:

// 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表中肯定有数据.

As shown I am trying to use the object oriented style.I get no mysqli error, and vardump says no data... but there definitely is data in the db table.

推荐答案

尝试一下:

<?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() ;

?>

这篇关于PHP切换到mysqli:num_rows问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 18:58