0

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; ?>
1

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I edited my code but now he says: Object of class mysqli_result could not be converted to string
Yes, you need to get the actual data from the result object, but you shouldn't call mysqli_query again, because that is the procedural version of the method that gave you the object in the first place. I've updated my answer with some code, some more explanation and a useful link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.