【问题标题】:php num_rows greater than 0php num_rows 大于 0
【发布时间】:2015-01-30 02:37:45
【问题描述】:

为了更新旧代码并同时学习,我迷路了。我不确定我是否做对了,我希望有人能指出我正确的方向,而不是抨击我的新手。我知道要远离 mysql 语句,这就是为什么我要尝试进入 oop 并随时学习它的原因。不知道我是否应该使用

if($rs->num_rows > 0)

或者如果它应该是

if($rows_returned > 0)

以下是我希望是一个不错的开始,原文在底部。

<?
// functions.php is required to connect to the database as usual
require("db.inc.php");

//our sql statement
$sql1 = 'select * from flights where flightnumber='" . $_REQUEST['DATA2'] . "'');
$rs=$conn->query($sql1);
if($rs == false) {
trigger_error('Wrong SQL:' . $sql1 . ' Error:' . $conn->error, E_USER_ERROR);
}else {
$rows_returned = $rs->num_rows;
if ($rs->num_rows > 0 ){
    for ($i=0$i<$num_result;$i++)
    {

$rs->data_seek(0);
while($row = $rs->fetch_assoc()){
    echo '1|flightplan\n';
    echo $row['departure'] .'\n';
    echo $row['destination'].'\n';
     ....more echo's removed to save reading.....
}
}
else{
echo '0|Flightnumber not found';
}

/* original kept as guide for updating
 *
 * $query = mysql_query("SELECT * FROM `flights` where flightnumber="".$_REQUEST['DATA2']."'");
 * $num_result = mysql_num_rows($query);
 * if ($num_result > 0)
 * {
 *  for ($i=0;$i<$num_result;$i++)
 *  {
 *      $result = mysql_fetch_array($query);
 *      echo "1|flightplan\n";
 *      echo $result['departure']."\n";
 *      echo $result['destination']."\n";
 *    ....more echo's removed to save reading.....
 *  }
 * }
 * else
 * {
 *  echo "0|Flightnumber not found";
 * }
 */
 ?>

【问题讨论】:

  • 首先,你应该清理你的$sql1变量,它是无效的。此外,两者都是正确的,但您可以通过使用第一个选项来保持代码简洁明了 - if($rs-&gt;num_rows &gt; 0)
  • 在浏览了一些代码之后,我发现我需要保留 $rows_returned。因为紧接着,我没有意识到 ($i=0;$i

标签: php oop mysqli


【解决方案1】:

你的第二个答案是正确的。如果您要从查询对象中获取数据以供以后使用,强烈建议将数据存储在新变量中。这样,当您释放查询对象时,您不会丢失数据。

祝你编码好运!

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    相关资源
    最近更新 更多