dBoys dBoys -4 years ago 56
PHP Question

Displays WHERE for two conditions in the same column

-----------------------------------------------------
| id | posts_id | users_id | ratings |
-----------------------------------------------------
| 1 | 7 | 20 | 5 |
| 2 | 8 | 20 | 3 |
| 3 | 7 | 21 | 4 |
-----------------------------------------------------


Table name: mytable

\I want to make sure that ratings between posts_id and users_id are matched on the same column.

$query = $conn->query("SELECT ratings FROM mytable WHERE posts_id=7 and users_id=20");
$row = $query->fetch_array();
echo $row['ratings'];


This query does not work. I know there must be something wrong.

I want to get results: 5

What is the best query to show ratings?

----------------UPDATE-----------------------------

Sorry, my first problem lies with the connection, and now it is resolved.

But now there is a new problem.

I want to display the total sum of the rating results.

My new code

$Rate = $conn->query("SELECT * FROM mytable WHERE posts_id=7");

while ($Rated = $Rate->fetch_array()) {
echo $Rated['ratings'] + $Rated['ratings'];
}


For example on
posts_id=7


Here I expect
5 + 4 = 9


But my code results exactly
54 + 54


How to fix this code?

Answer Source

For the updated question, this code should be work. We can use sum() function. Check here sum() function

$Rate = $conn->query("SELECT sum(ratings) FROM mytable WHERE posts_id=7");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download