为什么尝试从此代码中获取数据会出错?

时间:2018-06-25 17:37:28

标签: php mysql

它说它的行有一个错误,例如mysqli_num_rows()期望参数1为mysqli_result,它指向这一行$resultCheck = mysqli_num_rows($result);

我的代码是:

<?php

$sql = "SELECT FROM videos ORDER BY video_id ASC LIMIT 2,1;";
$result = mysqli_query($con, $sql);
$resultCheck = mysqli_num_rows($result);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) { ?>
<li class="jp-playlist-current"><div><a href="javascript:;" class="jp- 
playlist-item-remove" style="display: none;">×</a><a href="javascript:;" 
class="jp-playlist-item jp-playlist-current" tabindex="0">1. <?php echo 
$row['video_name']; ?> <span class="jp-artist">by <?php echo 
$row['video_artist']; ?></span></a></div></li>

<?php   }

} else {
    echo "there are no songs!";
}

?>

2 个答案:

答案 0 :(得分:2)

mysqli_num_rows()函数需要一个mysqli_result对象作为其参数。

如果查询中有任何错误并且没有返回mysqli_result对象,则失败。 如果出现语法错误或查询中使用了错误的表名-字段名,查询可能会失败,并且重要的一点是数据库连接处于活动状态。

您需要全部检查。

如果数据库连接正常,已完成并经过先前检查,则不需要以下代码:

<?php
$con = mysqli_connect("{DB_HOST}", "{db_user}","{db_password}","{db_name}");
if (mysqli_connect_errno()) die("DB Connect Error: " . mysqli_connect_error());
?>

然后请尝试查询是否也成功,然后再尝试从中获取结果(如果查询失败,mysqli_query()函数将返回false)。

<?php
$result = mysqli_query($con, "SELECT * FROM videos ORDER BY video_id ASC LIMIT 2,1");
if (!$result) die('Error on the query...');
$resultCheck = mysqli_num_rows($result);

if ($resultCheck) {
    while ($row = mysqli_fetch_assoc($result)) { ?>
...<?php echo $row['video_name']; ?>...
...<?php echo $row['video_artist']; ?>...
<?php   }

} else {
    echo "there are no songs!";
}
?>

答案 1 :(得分:0)

替换:

Dana

具有:

$sql = "SELECT FROM videos ORDER BY video_id ASC LIMIT 2,1;"; // ';' in the end is wrong