I have a forum where users can post questions and can upvote and downvote.
I want to get the upvote and downvote of each post.
What i did previously was do that in 3 sets queries.
$data = mysqli_query($con,"select * from posts");
while($row = mysqli_fetch_assoc($data)){
$pid = $row['post_id'];
$up = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM up WHERE post_id = $pid"))['c'];
$down = mysqli_fetch_assoc(mysqli_query("SELECT COUNT(*) as c FROM down WHERE post_id = $pid"))['c'];
}
Can anyone show me how can i do these things in one single query because if a get a lot of posts in 1st query then there will be lots of queries to do.
You can use subqueries and put everything in the first query.
This could be a good start :
$data = mysqli_query($con, "select posts.*, " .
"(SELECT COUNT(*) FROM up WHERE post_id = posts.post_id) as totalUp, " .
"(SELECT COUNT(*) FROM down WHERE post_id = posts.post_id) as totalDown " .
"from posts");
while($row = mysqli_fetch_assoc($data)){
// ...
}
you can use corelated subquery for this where upvotes
and downvotes are counted based on the post id
SELECT p.*,
( select count(*) from up where post_id = p.post_id ) as upVotesCount,
( select count(*) from down where post_id = p.post_id ) as downVotesCount,
FROM posts p
Related
I have two tables: users and threads. When a thread is created, it will store the user_id in the table as author_id. I want to display the thread name and the username of its author with the same query. I am currently using two querys as shown:
$query2 = mysql_query("SELECT author_id FROM threads WHERE id = $threadId") or die(mysql_error());
$result2 = mysql_fetch_array($query2);
$author_id = $result2['author_id'];
$query3 = mysql_query("SELECT username FROM users WHERE id = $author_id") or die(mysql_error());
$result3 = mysql_fetch_array($query3);
$author_name = $result3['username'];
<?php
$sql = '
SELECT t.name, u.username
FROM threads t
JOIN users u ON t.author_id = u.id
WHERE t.id = ' . (int)$threadId . '
';
list($thread_name, $author_name) = mysql_fetch_row(mysql_query($sql));
P.S. Mysql php extension is deprecated.
Try this query:
SELECT username
FROM users
WHERE id = (SELECT author_id
FROM threads
WHERE id = $threadId
LIMIT 1)
Note: Limit 1 is not mandatory as id is unique.
I'm trying to display a list of status updates from artists that a logged in user is following.
So far I have this:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
}
But i'm not sure how to loop through and display the returned status updates?
This isn't a strong point of mine, so any pointers would be greatly appreciated!
What prevented you from doing similar to what you'd already done for the first query? Something like follows:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
while($status_result_row = mysqli_fetch_assoc($status_result)) {
echo $status_result_row['mycol']; // This is where you know better than us
}
}
Or if those two tables artist_likes and status_updates have artist_id in common then you could just use one query with a join. (But don't know if you are asking for that).
Just for avoiding multiple query, you can use one query like this:
SELECT l.*, s.*
from artist_likes l, status_updates s
WHERE
l.artist_id = s.artist_id and
l.user_id = '1'
or
SELECT l.*, s.*
from artist_likes l
JOIN status_updates s on (l.artist_id = s.artist_id)
WHERE
l.user_id = '1'
Im working on a message board of some sort and i have everything up an running except one little part, the threads need to be sorted by the date/time of the latest post in them (standard forum format), which im having lots of trouble wrapping my head around.
This is the querys im using, i know its not pretty and its not safe, i will be reworking them once i learn how to do it properly.
$sql = "SELECT Thread_ID, Thread_Title, Board_ID, Author FROM threads WHERE Board_ID='$Board_ID' LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($row = mysql_fetch_assoc($result))
{
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$getauthor = mysql_query("SELECT * FROM members WHERE Member_ID='$Author'");
while ($row = mysql_fetch_assoc($getauthor))
{
$Post_Author = $row['Post_As']; }
$postcount = mysql_query("SELECT Post_ID FROM posts WHERE Thread_ID='$Thread_ID'");
$Posts = mysql_num_rows($postcount);
$getlatest = mysql_query("SELECT * FROM posts WHERE Thread_ID='$Thread_ID' ORDER by Post_DateTime DESC LIMIT 1");
while ($row = mysql_fetch_assoc($getlatest))
{
$Post_DateTime = time_ago($row['Post_DateTime']);
$Member_ID = $row['Member_ID']; }
$getmember = mysql_query("SELECT * FROM members WHERE Member_ID='$Member_ID'");
while ($row = mysql_fetch_assoc($getmember))
{
$Post_As = $row['Post_As']; }
So what im trying to do is Sort $sql by $getlatest, i tried adding another query above $sql that did basically the same as $getlatest and then had $sql order by that but alas it just broke everything.
I know i have to make a variable to sort the $sql by but its that variable thats driving me mad.
any help would be appreciated, thanks.
current error message as requested:
Fatal error: SQL - Unknown column 'posts2.LatestPost' in 'on clause' - SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs FROM threads INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1 ON threads.Thread_ID = Sub1.Thread_ID INNER JOIN members ON threads.Author = members.Member_ID INNER JOIN posts posts2 ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.LatestPost INNER JOIN members members2 ON members2.Member_ID = posts2.Member_ID WHERE threads.Board_ID='1' ORDER BY Sub1.LatestPost DESC LIMIT 0, 25 in C:\wamp\www\forum\include\threads.php on line 86
You should be able to do it using something like this for your first query:-
$sql = "SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, MAX(posts.Post_DateTime) AS LatestPost
FROM threads
LEFT OUTER JOIN posts ON threads.Thread_ID = posts.Thread_ID
WHERE threads.Board_ID='$Board_ID'
GROUP BY SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author
ORDER BY LatestPost DESC
LIMIT $offset, $rowsperpage";
EDIT
Not tested the following but looking at your selects I think you could probably put it together into a single SELECT. Something like this:-
$sql = "SELECT threads.Thread_ID, threads.Thread_Title, threads.Board_ID, threads.Author, Sub1.LatestPost, Sub1.PostCount, members.Post_As, members2.Member_ID AS LastPostMemberID, members2.Post_As AS LastPostMemberPostAs
FROM threads
INNER JOIN (SELECT Thread_ID, MAX(posts.Post_DateTime) AS LatestPost, COUNT(*) AS PostCount FROM posts GROUP BY Thread_ID) Sub1
ON threads.Thread_ID = Sub1.Thread_ID
INNER JOIN members
ON threads.Author = members.Member_ID
INNER JOIN posts posts2
ON posts2.Thread_ID = Sub1.Thread_ID AND posts2.Post_DateTime = Sub1.LatestPost
INNER JOIN members members2
ON members2.Member_ID = posts2.Member_ID
WHERE threads.Board_ID='$Board_ID'
ORDER BY Sub1.LatestPost DESC
LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
while ($row = mysql_fetch_assoc($result))
{
$Thread_ID = $row['Thread_ID'];
$Thread_Title = $row['Thread_Title'];
$Board_ID = $row['Board_ID'];
$Author = $row['Author'];
$Post_Author = $row['Post_As'];
$Posts = $row['PostCount'];
$Post_DateTime = time_ago($row['LatestPost']);
$Member_ID = $row['LastPostMemberID'];
$Post_As = $row['LastPostMemberPostAs'];
I have a table categories that has: id, name, subcategory_id, parent_id. Another table classifieds that has: classified_id, title, description, category_id.
I am trying to to pull numbers of classifieds in each category. So it will look like this.
Accessories(10)
Cars(15)
Dating(12)
I gave it a try like this:
enter $catquery = mysql_query("SELECT * FROM categories WHERE sub_id = '0' ORDER BY name ASC"); here
enter $catrows = mysql_num_rows($catquery); here
enter $catrows = mysql_num_rows($catquery); here
enter $query = "SELECT category_id, COUNT(title) AS `total` FROM classifieds WHERE classified_id = 'category_id' "; here
enter $result = mysql_query($query); here
enter while($row = mysql_fetch_assoc($result)){ $num_items_in_category[$row['category_id']] = $row['total']; here
enter } echo "<li><a href='category.php?cat=".$row['id']."'>".$row['name']. $row['total']. "</a></li>"; here
Thanks fellas
You should be able to accomplish what you're looking for by joining the 2 tables.
SELECT a.name, count(*) as cnt
FROM categories a
join classifieds b
on a.id = b.category_id
group by a.name
COUNT is an aggregate function, so you can get all of the counts at once.
I believe what you are looking for is
$query = "SELECT category-id, COUNT(title) AS `total` FROM classifieds WHERE classified-id = 'category-cat' GROUP BY category-id";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$num_items_in_category[$row['category-id']] = $row['total'];
}
This will give you associative array with the count of records for each category-id
How can I grab the count value from the query MySQL query below using PHP.
Here is My MySQL code.
$dbc = mysqli_query($mysqli,"SELECT COUNT(*) FROM((SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1')
UNION
(SELECT users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.friend_id = users.user_id
WHERE users_friends.friend_id = 1
AND users_friends.friendship_status = '1')) as friends");
using SQL_CALC_FOUND_ROWS should simplify things:
$dbc = mysqli_query($mysqli,"SELECT SQL_CALC_FOUND_ROWS users_friends.id
FROM users_friends
INNER JOIN users ON users_friends.user_id = users.user_id
WHERE users_friends.user_id = 1
AND users_friends.friendship_status = '1'
");
then afterwards do
$rs = mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
$rec = $rs->fetch_array();
$count = $rec[0];
This method will return the number of records that match the query, ignoring any LIMIT statement, whereas using $rs->num_rows will only give you the number of records actually returned. Depends which one you want.
if ($result = mysqli_query($link, "SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
http://us.php.net/manual/en/mysqli.query.php
Assuming that you are correctly connected to the MySQL server and your query are executed correctly, you can use the following code:
$values = mysql_fetch_row($dbc);
$count = $values[0];
Your query should look like SELECT COUNT(*) as numThings FROM xxx
The numThings is what you will reference in PHP:
$result = mysql_query("SELECT COUNT(*) as `numThings` FROM xxx");
$row = mysql_fetch_assoc($result);
$count = $row['numThings'];