group rows, count grouped rows and order by grouped rows - php

I want to make an analytics system for a website and I am trying to row accesed urls from a db, group by url, count grouped rows and order DESC by number of grouped rows.
$sql = "SELECT COUNT(*) FROM (SELECT DISTINCT url FROM analytic) ORDER by (SELECT DISTINCT url FROM analytic)";
$countQry = mysqli_query($link, $sql);
while($arr = mysqli_fetch_array($countQry)) {
?>
<?=$arr['url']?>
<?
}
?>
thanks

Try using a GROUP BY:
SELECT url, COUNT(url) AS theCount
FROM analytic
GROUP BY url
ORDER BY theCount DESC
Here is PHP code for you to use:
$sql = "SELECT url, COUNT(url) AS theCount FROM analytic GROUP BY url ORDER BY by theCount DESC";
$countQry = mysqli_query($link, $sql);
while ($row = mysqli_fetch_array($countQry, MYSQLI_ASSOC)) {
echo $row['url'], ", ", $row['theCount'];
}

Related

UNION doesn't work displaying error when combine with GROUP BY

I want to get the data by month so I can use it in my forecast/chart but the UNION doesn't seem to work well when combined with GROUP BY. Hope you can help me solve my problem.
$connect = mysqli_connect("localhost", "root", "", "testingfolder");
$query4 = "SELECT MONTHNAME(consultationstatus_date) AS MONTH,
consultationstatus_diagnosis,
count(*) as number
FROM tbl_consultationstatus
WHERE month(consultationstatus_date)=1
GROUP BY consultationstatus_diagnosis
ORDER BY number DESC LIMIT 1
UNION ALL
SELECT MONTHNAME(consultationstatus_date) AS MONTH,
consultationstatus_diagnosis,
count(*) as number
FROM tbl_consultationstatus
WHERE month(consultationstatus_date)=2
GROUP BY consultationstatus_diagnosis
ORDER BY number DESC LIMIT 1
";
$result4 = mysqli_query($connect, $query4);
while($row = mysqli_fetch_array($result4))
{
echo "['".$row["MONTH"]."', '".$row["number"]."','".$row["consultationstatus_diagnosis"]."'],";
}

MySQLi select from two table with limit

I have been try to combine two tables from mysql database, the two tables are status and status_reply both have the same columns number and name, that is id, account_name, author, postdate, data Please a help will be appreciated.
$limit = "LIMIT 0, 10";
$query = mysqli_query($db_conx, "(SELECT * `status` as type from status WHERE data LIKE '%".$tag."%' ORDER BY postdate DESC $limit)
UNION (SELECT * `status_reply` as type from status_reply WHERE data LIKE '%".$tag."%' ORDER BY postdate DESC $limit)");
//$query = mysqli_query($db_conx, "SELECT * FROM status WHERE data LIKE '%$tag%' ORDER BY postdate DESC $limit");
$statusnumrows = mysqli_num_rows($query);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$statusid = $row["id"];
$account_name = $row["account_name"];
$author = $row["author"];
$postdate = $row["postdate"];
$data = $row["data"];
$data = nl2br($data);
$data = str_replace("&","&",$data);
$data = stripslashes($data);
$statuslist .= '<div id="status_'.$statusid.'" class="status_boxes"><div><b>Ivotised by '.$author.' '.$postdate.':</b>
<article>'.$data.'</article>
</div></div>';
}
Use backquotes ` for field names instead of straight quotes '
Don't forget to quote $tag to protect from an SQL injection: mysqli_real_escape_string
Remember, that is you want to search literally for LIKE wildcard characters "%", "_" as well as backslash. You need to escape them too, using: $tag = addcslashes($tag, '\%_');
$limit = "LIMIT 0, 10";
$query = mysqli_query($db_conx, "
(SELECT `status` as type from status WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)
UNION
(SELECT `status_reply` as type from status_reply WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)");
I realized that I have to remove the type in both status and status_reply as references to the tables and identified each of the columns by their names. Am curious about it too!
$query = mysqli_query($db_conx, "
(SELECT id, account_name, author, postdate, data from status WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)
UNION
(SELECT id, account_name, author, postdate, data from status_reply WHERE data LIKE '%".$tag."%'
ORDER BY postdate DESC $limit)");

select down and up votes for each post php mysql

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

Counting Number Of Classifieds In Category

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 to use a Union properly with Order BY?

The code I have below joins 5 tables and then is suppose to sort by date_timed_added. The query worked perfectly if i only join 4 tables. For some reason after the 4th table, its giving me issues. The issue is that it sorts and displays the 5th table first and then the rest follow. How can i fix it so that it sorts date_time_added properly by querying all the other tables?
//$sid is a variable that is drawn from DB
$sql = "select `client_visit`.`visit_id`, `client_visit`.
`why_visit`, `client_visit`.`date_time_added`, `client_visit`.
`just_date`, `client_visit`.`type` from `client_visit` where
`client_visit`.`system_id` = '$sid' and `client_visit`.
`added_by` = '$sid'
UNION
select `client_notes`.`note_id`, `client_notes`.`note_name`,
`client_notes`.`date_time_added`, `client_notes`.`just_date`
, `client_notes`.`type` from `client_notes` where `client_notes`.
`added_by` = '$sid'
UNION
select `client_conditions`.`med_id`, `client_conditions`.`med_name`,
`client_conditions`.`date_time_added`, `client_conditions`.`just_date`,
`client_conditions`.`type` from `client_conditions` where
`client_conditions`.`system_id` = '$sid' and `client_conditions`.
`added_by` = '$sid'
UNION
select `client_stats`.`stat_test_id`, `client_stats`.`stat_why`,
`client_stats`.`date_time_added`, `client_stats`.`just_date`,
`client_stats`.`type`
from `client_stats` where `client_stats`.`system_id` = '$sid'
and `client_stats`.`added_by` = '$sid'
UNION
select `client_documents`.`doc_id`, `client_documents`.`doc_name`,
`client_documents`.`date_time_added`, `client_documents`.`just_date`,
`client_documents`.`type` from `client_documents` where `client_documents`.
`system_id` = '$sid' and `client_documents`.`added_by` = '$sid'
ORDER BY `date_time_added` DESC LIMIT $startrow, 20";
$query = mysql_query($sql) or die ("Error: ".mysql_error());
$result = mysql_query($sql);
if ($result == "")
{
echo "";
}
echo "";
$rows = mysql_num_rows($result);
if($rows == 0)
{
}
elseif($rows > 0)
{
while($row = mysql_fetch_array($query))
{
//Just using these two variables i can display the same row info
//for all the other tables
$stuffid = htmlspecialchars($row['visit_id']);
$title = htmlspecialchars($row['why_visit');
}
}
}
As per the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/union.html
If you want to order the ENTIRE result set, the ORDER BY clause must be placed on the LAST query in the UNION, with each query being bracketed.
(SELECT ...)
UNION
(SELECT ...)
ORDER BY ...
sth like this should do.
SELECT Tbl1.field1
FROM ( SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
) Tbl1
ORDER BY Tbl1.field1

Categories