Kathy
Kathy

Reputation: 1

Echo number of rows where id=$id

I've tried to echo number of rows where a certain id=$id. This is essentially to count the number of "votes" a person has been receiving on the website. It works like a charm in mysqlworkbench, however the number of rows where this person's id has been inserted into database (through the voting button) won't show up on the webpage. The table name is forslag_stemmer, and it has its primary key= id, and foreign keys brukerid (the user that votes for a certain person) and foreign key forslagid (this is the people who receives votes from the users).

This query works in workbench, but not on the page:

echo "<u><b>Number of votes</u></b>:";

$sql= "SELECT COUNT( * ) FROM 
       bb.forslag_stemmer WHERE forslagid=$forslagid";

$resultat = $kobling->query($sql);

while($rad=$resultat->fetch_assoc())
{
    $forslagid = $rad["forslagid"];

    echo $sql;
    echo "$resultat->num_rows";
}

I really don't know what to do?

Upvotes: 0

Views: 305

Answers (2)

Ajith
Ajith

Reputation: 258

mysqli_result::num_rows Gets the number of rows in a result

In your Example since you're querying as "select count(*) from table" it always returns Number of rows as "1"

You can get Number of rows in two ways

Method 1:

$sql= "SELECT * from FROM bb.forslag_stemmer WHERE forslagid=$forslagid";
$result = $con->query($sql);
echo $result->num_rows; // prints number of rows found

Method 2:

$sql= "SELECT count(*) as resultcount from FROM bb.forslag_stemmer WHERE 
       forslagid=$forslagid";
$result = $con->query($sql);
while($row = $result->fetch_assoc()){
    echo $row['resultcount']; // prints number of rows found
}

Upvotes: 0

u_mulder
u_mulder

Reputation: 54841

You select one field COUNT( * ) as result of your query. There will be no other fields in a result.

echo "<u><b>Number of votes</u></b>:";
// I added an alias for field
$sql= "SELECT COUNT( * ) as votes_count FROM bb.forslag_stemmer WHERE forslagid=$forslagid";
$resultat = $kobling->query($sql);
$rad = $resultat->fetch_assoc();
// access value by alias
echo $rad['votes_count'];

Upvotes: 2

Related Questions