简体   繁体   中英

counting rows in php with sql

For an application I'm trying to count the total of friends. I want to do this with a function but it isn't returning anything. It tells me this:

Warning: mysqli_query() expects at least 2 parameters, 1 given

But I only need one parameter. I think I'm totally wrong.

This is the function:

public function GetTotalOfFriends($user_id){
    $db = new Db();
    $select = "SELECT COUNT FROM friendship WHERE (friendship_recipient_id ='" . $user_id ."' OR friendship_applicant_id = '" . $user_id . "') AND friendship_status = 'accepted'";
    $result = $db->conn->query($select);
    $row = mysqli_query($result);
    $total = $row[0];
    echo $total;

I'm trying to print it out in this way:

$friend = new Friendship;
$numberoffriends = $friend->GetTotalOfFriends($user_id);

<?php echo $numberoffriends; ?>

You are mixing up a couple of things. The line $result = $db->conn->query($select); already seems to execute a query, but then you try to bypass your database wrapper by passing that query result again to mysqli_query .

Apart from that, I think your query itself is also wrong. COUNT needs a parameter, indicating a field or value to count. Quite often COUNT(*) is used, but COUNT('x') might be more efficient in some cases. You can also use a specific field name, and COUNT will count the non-null values for you.

The result you got is a mysql_result object, which you need to use to get to the actual data of the query result. The documentation of this object is here and I suggest that you read it thoroughly.

One possible way to do this is using this:

$resultArray = $result->fetch_row();

This will result in the first (and only) row of your query. It is represented as an array, with one value (since your query returns only one column). You can fetch that value like this:

return $resultArray[0];

You could also use any of the other fetch methods if you want your data in a different fashion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM