I want to count the total comment/post posted on my page. i have a table in my database named test. within table i have a column named comment, where every post is been stored. the problem am having is to echo out the total number of comment and keep updating as viewers keep on posting there comment and i tried using this code
<?php
$handle = mysql_query("SELECT `comment`, COUNT(*) AS `count`
FROM test GROUP BY `comment` ");
if ($handle) {
$results = mysql_fetch_assoc($handle);
echo ($results[0]['count'] + $results[1]['count']);
}
?>
but it keep on echoing out 0. pls help me out.
Try this:
list($count) = mysql_fetch_row(mysql_query("select count(*) from `test`"));
echo $count;
Alternatively, if you are already running a query to get some comments, you can try this:
$sql = mysql_query("select sql_calc_found_rows * from `test` order by `id` desc limit 10");
// ^ Get the 10 most recent comments
list($count) = mysql_fetch_row(mysql_query("select found_rows()"));
// this avoids having to run the entire query again, great for efficiency!
while($comment = mysql_fetch_assoc($sql)) var_dump($comment); // just an example
Related
I'm designing a website and I wrote some webpage that display the list of users.
I used to do a
$query = SELECT * FROM `table_users` WHERE `id`='.$id.'
and then increment the ID with a "while" so I can grab all the users. But it's too slow now, and it glitches when there is a gap between IDs.
So I tried something like
$query = SELECT `name` FROM `tbl_user`ORDER BY `id`
and displaying the userlist with a
while ($i < sizeof(mysql_fetch_array(mysql_query($query)))){
<code to display an user>
$i++
}
But the mysql_fetch_array only returnes one user, the first one (the one with the littliest ID). I want it to return all users in an array. How do I do ?
Try This
$query = "SELECT `name` FROM `tbl_user` ORDER BY `id`";
$user_query = mysql_query($query);
$i=1;
while ($row = mysql_fetch_array($user_query)){
echo $i." : ".$row['name']."<br>";
$i++;
}
Try it like this:
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
//$row is the row which was just gathered
}
And please, use PDO or MySQLi instead of deprecated mysql.
I often read that mysql(i) queries used in while loops are not really performance friendly and I'm going to rewrite my code because I think it get better. But here's my question if a JOIN can work here. It's a single post viewing function but you should see every comment which got posted below. I got the comment loop in the loop which the post is printed.
<?php
$result = (empty($_GET['hash'])) ? $_GET['hash'] = '' : mysqli_query($conn, "SELECT * FROM `userposts` WHERE `hash`='".$_GET['hash']."' LIMIT 1");
while($rows = mysqli_fetch_array($result)){
//Output of single post
$commentresult = mysqli_query($conn, "SELECT * FROM `comments` WHERE `postid`='".$rows['id']."'");
while($commentrows = mysqli_fetch_array($commentresult)){
//Output of all comments
}
}
So I think it gets better but the query with JOIN should be like:
$result = (empty($_GET['hash'])) ? $_GET['hash'] = '' : mysqli_query($conn, "SELECT * FROM `userposts` JOIN comments ON userposts.id = comments.postid WHERE `hash`='".$_GET['hash']."' LIMIT 1");
But if I'm trying to post the data of the comments in the while loop which is the singlepost printed it just prints one comment. So what can I do?
regards
Your code is a bit of a mess. You are sometimes call mysql_fetch_results with a string, which is weird.
What you want is this:
"SELECT * FROM comments LEFT JOIN userposts ON comments.PostID = userposts.ID WHERE userposts.Hash = '$_GET['hash']'"
EDIT: sorry, you want LEFT JOIN with comments on the left. Gives you all the comments
EDIT 2: I set this up and it worked as I expected, even with multiple posts with the same hash.
<?php
$hash = $_GET['hash'];
$result = mysqli_query($conn, "SELECT * FROM comments LEFT JOIN userposts ON comments.PostID = userposts.ID WHERE userposts.Hash = '$hash'");
if ( $row = mysql_fetch_array($result)) {
// output of post.
// output first comment
}
while($row = mysqli_fetch_array($result)){
//Output other comments
}
?>
I have this code:
<?php
$data = mysql_query("SELECT id FROM board") or die(mysql_error());
while($info = mysql_fetch_assoc( $data ))
{
Print " ".$info['id']." ";
myOtherQuery($info['id']);
}
function myOtherQuery($id) {
$result = mysql_query("SELECT COUNT(is_following_board_id) FROM follow WHERE is_following_board_id='$id'");
$c = mysql_result($result, 0);
}
?>
It lists all ID's with a number beside it, defined as $c above in the second query.
For simplicity I have remove the HTML of the code but it aligns in a table.
I'm trying to ORDER BY $c, but don't know how to do it. Since it is defined AFTER the select query: $data = mysql_query("SELECT id FROM board")
It errors if I add: $data = mysql_query("SELECT id FROM board ORDER BY '$c'")
Is there anything I can add to the bottom of the code to make this order by work?
You want to do this in one query, by aggregating the results:
select is_following_board_id, sum(is_following_board_id) as cnt
from follow
group by is_following_board_id
order by cnt desc;
Your approach was to fetch the result and then fetch the count. Rather inefficient, because SQL is designed for this type of query.
I'm trying to count the yes and no votes so that I can just post the total yes/no for my website. This is should be easy, but I must be missing something somewhere since I don't get a return result. At least no php error. My total vores
$result = mysql_query("SELECT * FROM Poll");
$votes_Poll = mysql_num_rows($result);
$vote_yes = mysql_query("SELECT vote, COUNT(*) FROM Poll GROUP BY yes");
$vote_no = mysql_query("SELECT vote, COUNT(*) FROM Poll GROUP BY no");
// Display the results
echo $votes_Poll;
echo "<br>";
echo $vote_yes;
echo "<br>";
echo $vote_no;
thanks in advance
That's because you're echoing out a query object. Each of your queries should be...
$vote_yes = mysql_query("SELECT COUNT(*) AS total FROM Poll WHERE vote = 'yes' ");
$row = mysql_fetch_object($vote_yes);
echo $row->total; //echoes out the number of yes votes
You are misunderstanding how GROUP BY works. You do not use it to select an answer, it is used to select a field, by which aggregate functions are grouped.
If you use:
SELECT `vote`, COUNT(*) FROM Poll GROUP BY `vote`
Then this will return two results, each with two values, the vote (yes or no) and the count for that vote.
$handle = mysql_query("SELECT `vote`, COUNT(*) AS `count` FROM Poll GROUP BY `vote` ORDER BY `vote` DESC");
if ($handle) {
$results = mysql_fetch_assoc($handle);
echo ($results[0]['count'] + $results[1]['count']) . "<br>" . $results[0]['count'] . "<br>" . $results[1]['count'];
}
NB. Using the ORDER BY vote DESC part, that forces the order to yes then no (reverse alphabetical) and then you do not have to check which row is which.
I'm trying to get a pick from my DB that would last for a day (daily pick). I use the following code:
$query = 'SELECT * FROM table ORDER BY rand() LIMIT 1
But as you can see it only gives me a random pick from the table, and every time I refresh the page it gets me a new random pick. How can I make the pick to last for a whole day?
Thanks in advance <3
I'm trying this:
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
But I get the following error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource. This is the part that gets broken:
$results = mysql_query($query);
while($line = mysql_fetch_assoc($results))
So... it should look like this, right? (I mean, choosing the daily random pick?)
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
I'm trying this now:
$dailyPick = 'SELECT * FROM table ORDER BY rand() LIMIT 1';
$cacheKey = 'dailyPick'. date('dmY');
if($cache->has($cacheKey)) {
$dailyPick = $cache->get($cacheKey);
} else {
// hit database
$dailyPick = $cache->save($cacheKey);
}
However, it gets me a mistake that I'm using the 'has' function on a non-object.
If you set the SEED for the rand to an integer value that changes daily, that would solve your problem
$query = "SELECT * FROM table ORDER BY rand(" . date("Ymd") . ") LIMIT 1";
Would do the trick.
A sane means of doing this would be to automatically generate the pick of the day content via a cron job that was setup to run once a day.
As such, the cron job would execute the SQL you provided and store the appropriate content in a flat file/database table, etc. (or perhaps even just store the choosen id in another table for future lookup purposes).
You can try something like this:
$total = 'SELECT COUNT(*) FROM table;';
$query = 'SELECT * FROM table ORDER BY id ASC LIMIT 1 OFFSET ' . (date('Ymd') % $total) . ';';
I think you'll need to update the random picked record with "today" field = 1..
Something like this:
// ------------
// Run this 3 commands once a day
// Reset all records
mysql_query("UPDATE `table` SET `today` = 0");
// Pick one
$sql = mysql_query("SELECT `id` FROM `table` ORDER BY RAND() LIMIT 1");
$id = mysql_result($sql, 0, 'id');
// Update the record
mysql_query("UPDATE `table` SET `today` = 1 WHERE `id` = {$id}");
// ------------
// Now you can find again your "random found record":
$query = mysql_query("SELECT * FROM `table` WHERE `today` = 1");