Using PHP to Output MySQL Query Where COUNT(*) is Used [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
mysql count into PHP variable
I have the following query that returns successfully when run from MySQL command prompt:
SELECT `from_email`, COUNT(*)
FROM `user_log`
GROUP BY `from_email`
ORDER BY COUNT(*) DESC
This query returns a result set that has the following columns
`from_email` | COUNT(*)
My question is, how do I go about iterating through the result sets and outputting the results. I have my table formatted I just need from_email in one table cell and the associated COUNT in another for each record.
Thanks in advance

add an ALIAS on it
SELECT `from_email`, COUNT(*) AS totalCount
FROM `user_log`
GROUP BY `from_email`
ORDER BY totalCount DESC
and you can now fetch the value
$row["from_email"]
$row["totalCount"]

Following is the code for connect to database and retrieve the result and display in table.
<?
$conn = mysqli_connect("localhost", "root","root", "test");
$query="SELECT `from_email`, COUNT(*) AS emailCount FROM `user_log` GROUP BY `from_email` ORDER BY COUNT(*) DESC";
$result = mysqli_query($conn, $query);
if ($result) {
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH))
{
$table[] = $row;
}
}
?>
<table border="1">
<tr>
<td width="200">From Email</td>
<td width="50">Count</td>
</tr>
<?
if($table){
for($i=0;$i<count($table);$i++){
?>
<tr>
<td><?=htmlentities($table[$i]["from_email"])?> </td>
<td><?=htmlentities($table[$i]["emailCount"])?> </td>
</tr>
<?
}
}
?>
</table>

Related

Number of entries in DB PHP

I am creating a function to show how many users are online now. This is based on who has opened a page within the last 5 min. Each page load is saved to my DB, below:
At the moment I have the following code
$query = mysql_query("SELECT user_id, timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
$onlineUsers = mysql_num_rows($query);
This is simply totalling the number of rows, how can I do this so it only counts a user_id once? (so in the above database snippet it should be 2 not 5)
use DISTINCT keyword
$query = mysql_query("SELECT DISTINCT(user_id), timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
$onlineUsers = mysql_num_rows($query);
Since mysql_* is deprecated (php 5 onward) and removed in (php 7). So a mysqli_* example is here:-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','username','password','db name');//change credentials here
$online_users = array();
if($conn){
$query = mysqli_query($conn,"SELECT DISTINCT(user_id), timestamp,page FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
if($query){
while($row = mysqli_fetch_assoc($query)){
$online_users[] = $row;
}
}else{
echo "query error:-".mysqli_error($conn);
}
}else{
echo "db connection error:-".mysqli_connect_error();
}
?>
<table>
<tr>
<thead>
<th>User Id</th>
<th>timestamp></th>
<th>Page Visited</th>
</thead>
</tr>
<tbody>
<?php foreach($online_users as $online_user){?<
<tr>
<td><?php echo $online_user['user_id'];?></td>
<td><?php echo $online_user['timestamp'];?></td>
<td><?php echo $online_user['page'];?></td>
</tr>
<?php }?>
</tbody>
</table>
Note:- If you want to show online user name also then you have to do JOIN query.
change table code accordingly.
It's a sample code. modify it accordingly.
You may use group by, e.g
SELECT user_id, timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute) group by user_id;

K/D Ratio with SQL and PHP

So I'm trying to make a K/D ratio with some data from a database using SQL.
The main problem is that the tables are so strange and I'm trying to display it as an HTML table.
There's a table called stats_player_kill (when player kills another)
Here's the content of the table:
So if I want to get the kills, I count the killer column with the same id.
Here's how I get number of kills of each player and display it as an HTML table:
<table class="tablitas" id="kills">
<thead>
<tr>
<th data-column-id="name">Player</th>
<th data-column-id="killer" data-type="numeric">Kills</th>
</tr>
</thead>
<?php
$sql = "select p.name as name, count(*) as amountOfObjects
from stats_player_kill b
join stats_player p on p.id = b.victim
group by b.victim
order by count(*) desc
limit 15";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["name"]."</td><td>".$row["amountOfObjects"]."</td></tr>";
}
echo "</tbody>";
echo "</table>";
echo "</td>";
} else {
echo "0 results";
}
?>
So I need help making the math to divide number of kills by the total deaths.
Sorry for my English and thanks to everyone! :D

Select distinct in SQL?

The select distinct not working and the count(*) is not selecting the number of grouped rows but it is selecting the duplicate msg_contents.Please help..
I wanted to select distinct username and the number of duplicate usernames.
<?php
require_once"cnc.php";
$sort = "SELECT hate_p FROM hate_t";
$qry = mysql_query($sort);
while($fet = mysql_fetch_assoc($qry)) {
if($fet == 0) {
echo "No Entries";
} else {
$sql = mysql_query("
SELECT DISTINCT
username,
msg_content,
COUNT(*) c
FROM messages
WHERE msg_content LIKE '%".$fet['hate_p']."%'
GROUP BY username HAVING c>0"
);
while($messages = mysql_fetch_assoc($sql)) {
?>
<tr>
<td><?php echo $messages['username'];?></td>
<td><?php echo $messages['c'];?></td>
</tr>
<?php
}
}
}
?>
you don't need distinct in this case, you can use group by only, distinct get all rows with distinct all columns you select (username,meg_content,count):
SELECT username,msg_content,COUNT(*) c
FROM messages WHERE msg_content LIKE '%".$fet['hate_p']."%'
GROUP BY username,msg_content
HAVING c>0
remove msg_content from distinct? you already have it. and #gouda is right, you probably don't need the distinct at all.

MySQL resource's fetched row count

Looked all over and couldn't find a way to do this.
I want to count the amount of results from a query that's being looped.
for example...
If I have 5 pokemon, and 2 of them are Pikachus, it will display 4 pokemon but with a 2 next to the pikachu, I want to count the number of different pokemon you own not including the secound Pikachu.
this is what I have so far.
<div class="reg-box3" style="width:100%; margin:5px;">
<?php
$result = mysql_query("SELECT *, COUNT(*) number FROM user_pokemon WHERE belongsto='". $_SESSION{'username'}."'AND (slot='0') GROUP BY pokemon ORDER BY pokemon");
while($row = mysql_fetch_array($result))
{
$sql2 = "SELECT * FROM pokemon WHERE name='".$row['pokemon']."'";
$result2 = mysql_query($sql2) or die(mysql_error());
$battle_get2 = mysql_fetch_array($result2);
?>
<div style="width: 24.5%; float: left;padding:.1%; ">
<?php
$idd= mysql_real_escape_string($row['id']);
$iddd = strip_tags($idd);
?>
You are missing AS from your query before number. If you add it, the desired count will be stored in the $result['number'] variable.
By the way you might find mysql_num_rows() easier in this case. Just call it on your MySQL resource, and it returns the number of rows fetched.
Edit: using mysql_num_rows is this simple: $count = mysql_num_rows($result);
<?php
$result = mysql_query(
<<<SQL
SELECT
`t2`.`name` AS `name`,
COUNT(*) AS `count`
FROM `user_pokemon` AS `t1`
JOIN `pokemon` AS `t2` ON (`t1`.`pokemon` = `t2`.`name`)
WHERE
`t1`.`belongsto` = '{$_SESSION{'username'}}'
AND `t1`.`slot` = 0
GROUP BY `name`
ORDER BY `name`
SQL
);
while($row = mysql_fetch_array($result)){
var_dump($row);
}
?>
No guarantees it works as I don't know your table structure and not sure if I got it right from your queries.
PS: Don't count records with mysql_num_rows(). It requires transferring data from the server while, if you do it directly in MySQL, you get the maximum of performance with the most ease of use.

How the get PHP to print the number of comments from MySQL database

I have a following problem. I have three tables: message, comment and user. I would like PHP to print the data of following fields from MySQL database as a table on my web-page: message.subject, user.username and then number of comments. Everything else works fine but I haven't managed to get PHP to print the number of comments.
This is what I have tried to do so far:
<?php
include("info.php");
$connect;
$sql="SELECT * FROM message, user
WHERE message.userID = user.userID AND
ORDER BY message.messageID DESC";
$result=mysql_query($sql) or die(mysql_error());
$sql2="SELECT message.messageID, COUNT(*) as comments FROM comment
INNER JOIN
message ON comment.messageID = message.messageID
GROUP BY comment.messageID";
$result2=mysql_query($sql2) or die(mysql_error());
<table>
<thead>
<tr>
<th>Subject</th>
<th>Sender</th>
<th>Number of comments</th>
</tr>
</thead>
<tbody>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td>
<a href="php/message.php?id=<?php echo $rows['messageID']; ?>">
<?php echo $rows['subject']; ?>
</td>
<td>
<?php echo $rows['username']; ?>
</td>
<td>
<?php while($rows2=mysql_fetch_array($result2)){ echo $rows2['comments'];}?>
</td>
</tr>
<?php
} mysql_close(); ?>
</tbody>
</table>
Couldn't you just get all this info with one query?
SELECT
m.messageID,
m.subject,
u.username,
c.numOfComments
FROM
message m
INNER JOIN user u ON m.userID = u.userID
LEFT JOIN (SELECT COUNT(1) AS numOfComments, messageID FROM comments GROUP BY messageID) c ON m.messageID = c.messageID
ORDER BY
m.messageID DESC
Try this script:
<?php
include("info.php");
connect();
$sql = "
SELECT
m.messageID,
m.subject,
u.username,
c.numOfComments
FROM
message m
INNER JOIN user u ON m.userID = u.userID
LEFT JOIN (SELECT COUNT(1) AS numOfComments, messageID FROM comments GROUP BY messageID) c ON m.messageID = c.messageID
ORDER BY
m.messageID DESC
";
$result = mysql_query($sql) or die(mysql_error());
echo "<table>
<thead>
<tr>
<th>Subject</th>
<th>Sender</th>
<th>Number of comments</th>
</tr>
</thead>
<tbody>\n";
while ($row = mysql_fetch_assoc($result))
{
$row = array_map("htmlspecialchars", $row); // sanitize to prevent XSS
echo " <tr>
<td>{$row["subject"]}</td>
<td>{$row["username"]}</td>
<td>{$row["numOfComments"]}</td>
</tr>\n";
}
echo " </tbody>
</table>";
?>
There are a few other corrections as well. For instance, your link doesn't have a closing </a> tag, and your script may be vulnerable to XSS attacks. And then there's the nested while-loop, which was causing unnecessary complication and bugs.
The problem i see is that you are nesting your while loops. Please see: http://www.php.net/manual/en/control-structures.while.php#52733
Use one sql statement.
This is the best way to do it (i think):
$sql = "
SELECT message.*, user.*, commentsCounter.comments FROM message
INNER JOIN user
ON user.userID = message.userID
INNER JOIN ( SELECT COUNT( 1 ) as comments, comment.messageID FROM comment GROUP BY comment.messageID ) commentsCounter
ON commentsCounter.messageID = message.messageID
ORDER BY message.messageID DESC
";
Why not just do something like the following?
$query = "SELECT comment FROM message where userId = $userId";
$result = mysql_query($query);
$numberOfComments = mysql_num_rows($result);
echo "$numberOfComments";
At least I believe that is what you're looking for?
Manual says this about mysql_num_rows():
mysql_num_rows — Get number of rows in result
http://www.w3schools.com/sql/sql_func_count.asp
$result3=mysql_query("COUNT(*) FROM comment") or die(mysql_error());
$row=mysql_fetch_array($result3);
$numcomments = $row[0];
echo $numcomments;
I use this (with a different table name) on a few sites.
Answer 2
Assuming you want the comments on a specifc post, try something like this:
$result3=mysql_query("SELECT DISTINCT message.messageID FROM comment ") or die(mysql_error());
$row=mysql_fetch_array($result3);
$numcomments = count($row);
echo $numcomments;

Categories