【问题标题】:Php - mysql - Return number of rowsphp - mysql - 返回行数
【发布时间】:2015-01-12 12:47:37
【问题描述】:

我正在尝试获取用户拥有的朋友数量,但我似乎无法让它发挥作用,所以我真的希望你能帮助我。 这是php

$findFriendssql = "select u.firstName, u.id from friends f, user u 
where (f.u_ID1 = '$loggedId' and u.id = f.u_id2) 
or (f.u_id2 = '$loggedId' and u.id = f.u_id1)";


$all_friends_sql = $db->getRows($findFriendssql);

//$number_of_friends = mysql_num_rows($all_friends_sql);
if ($all_friends_sql) {
$number_of_friends = mysql_num_rows($all_friends_sql);
$friends = "";
foreach ($all_friends_sql as $one_post) {
//doing stuff here.

这里是获取行函数

public function getRows($sql) {
    $result = array();
    $table = mysql_query($sql, $this->db_link);
    if (!$table) {
        die("\"$sql\" seems to be an invalid query: " . mysql_error());
    }
    while ($row = mysql_fetch_assoc($table)) {
        array_push($result, $row);
    }

    return $result;
}

无论我尝试什么 - 我都会收到错误,即 num rows 期望参数 1 是资源。 提前谢谢你

【问题讨论】:

  • 它是否抛出任何错误?
  • yah - 它会引发预期参数错误,但我可以在这里为您发布。警告:mysql_num_rows() 期望参数 1 是资源,数组在第 22 行的 /Applications/XAMPP/xamppfiles/htdocs/gamershubFinalLocal/findFriends.php 中给出
  • 好吧,用 count($all_friends_sql) 代替 mysql_num_rows($all_friends_sql) ,虽然我听不懂你的查询。
  • 哈哈 - 效果很好 - 感谢 anwejunaid!我的查询是选择用户的名字,哪些是登录的人的朋友,或者是朋友的朋友。如果你愿意 - 把它写成答案,我会接受的。
  • 您应该使用 Left joingroup by 指令(用户 id 组),以便在同一查询中拥有她朋友的号码,以提高响应性能

标签: php mysql return logic rows


【解决方案1】:
  $findFriendssql = "select u.firstName, u.id from friends f, user u where (f.u_ID1 = '$loggedId' and u.id = f.u_id2) 
or (f.u_id2 = '$loggedId' and u.id = f.u_id1)";


 $all_friends_sql = $db->getRows($findFriendssql);

 //$number_of_friends = mysql_num_rows($all_friends_sql);
 if (count($all_friends_sql)>0) {
 $number_of_friends = mysqli_num_rows($all_friends_sql);
 $friends = "";
 foreach ($all_friends_sql as $one_post) {

【讨论】:

    【解决方案2】:

    第 num 行应该在此之后立即发生:

    $table = mysql_query($sql, $this->db_link);
    $totalFirends = mysql_num_rows($table);
    

    使用$table 作为输入参数。 $table 应该是一种资源。能够使用mysql_num_rows。 您的函数中的以下内容将 $table 更改为不再是资源。此外,您不需要此代码即可知道用户有多少朋友:

        while ($row = mysql_fetch_assoc($table)) {
        array_push($result, $row);
        }
    
        return $result;
    }
    

    此外,如果您只需要数字,则查询应更改为 SELECT COUNT(some-field)

    我不知道$loggedId 的内容是什么希望您测试查询返回的内容应该返回。是否使用示例数据正确查询输出,让我们在 phpmyadmin 中说?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-10
      • 2013-09-06
      • 1970-01-01
      • 2014-04-23
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 2012-03-25
      相关资源
      最近更新 更多