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.
Related
I wanna be able to echo out if Groupname and Username are connected correctly, where the current userid (saved in a session) is $uid.
I've been sitting for hours trying all kinds of JOINs and the closest I've gotten is having it output 1/? members for each team, but not all of them.
EDIT:
$uid = $_SESSION['uid'];
$sql = "SELECT * FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user
INNER JOIN usergroup ON user.userid=usergroup.userid
WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
$row2 = mysqli_fetch_array($result2);
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
Thing is, that it kinda works well, except that it doesn't print all the groupmembers names out, it prints out just one. Which one seems to depend on the order in the table.
You did not have a loop on the second query's resultset. However, it is not needed to have a second SQL query. Just do it in one go; SQL was designed for that.
Also, you'll have much simpler code:
$uid = $_SESSION['uid'];
// Select everything you need in one go (join user table as well)
$sql = "SELECT group.group_id, group.groupname, user.username
FROM group
INNER JOIN usergroup ON group.groupid=usergroup.groupid
INNER JOIN user ON user.userid=usergroup.userid
WHERE usergroup.userid=$uid";
$result=$mysqli->query($sql);
// Don't need to call mysqli_num_rows if you continue like this:
while($row = mysqli_fetch_array($result)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
Maybe you want to echo some <tr> and </tr> tags, or you"ll have everything in one row, like:
echo "<tr><td>".$row['groupname']."</td>"
."<td>".$row['username']."</td>"
."<td>".$row['groupid']."</td></tr>";
There you go: (you were missing nested while loop)
if(mysqli_num_rows($result)>0) {
while($row = mysqli_fetch_array($result)) {
$gid = $row['groupid'];
$sql2 = "SELECT * FROM user INNER JOIN usergroup ON user.userid=usergroup.userid WHERE usergroup.groupid=$gid";
$result2=$mysqli->query($sql2);
if(mysqli_num_rows($result2)>0) {
while($row2 = mysqli_fetch_array($result2)) {
echo "<td>".$row['groupname']."</td>";
echo "<td>".$row2['username']."</td>";
echo "<td>".$row['groupid']."</td>";
}
}
}
}
Side note: You could achieve the same results with just one SQL query, something like:
SELECT
*
FROM
usergroup ug
INNER JOIN
user u ON ug.userid = u.userid
GROUP BY
ug.id
and then in PHP (pseudo code just, do not copy-n-paste)
while($row => mysqli_fetch_array($result)) {
if (!isset($groupsWithUsers[$row['groupid']['users'])) {
$groupsWithUsers[$row['groupid']['users'] = array()
}
$groupsWithUsers[$row['groupid']['users'][$row['userid']] = $row;
}
I am using a code something like below to get data from the second table by matching the id of first table. Code is working well, but I know it slow down the performance, I am a new bee. Please help me to do the same by an easy and correct way.
<?php
$result1 = mysql_query("SELECT * FROM table1 ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ))
{
$tab1_id = $row1['tab1_id'];
echo $row['tab1_col1'] . "-";
$result2 = mysql_query("SELECT * FROM table2 WHERE tab2_col1='$tab1_id' ") or die(mysql_error());
while( $row2 = mysql_fetch_array( $result2 ))
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
}
?>
You can join the two tables and process the result in a single loop. You will need some extra logic to check if the id of table1 changes, because you'll only want to output this value when there's a different id:
<?php
// Join the tables and make sure to order by the id of table1.
$result1 = mysql_query("
SELECT
*
FROM
table1 t1
LEFT JOIN table2 t2 ON t2.col1 = t1.id
ORDER BY
t1.id") or die(mysql_error());
// A variable to remember the previous id on each iteration.
$previous_tab1_id = null;
while($row = mysql_fetch_array( $result1 ))
{
$tab1_id = $row['tab1_id'];
// Only output the 'header' if there is a different id for table1.
if ($tab1_id !== $previous_tab1_id)
{
$previous_tab1_id = $tab1_id;
echo $row['tab1_col1'] . "-";
}
// Only output details if there are details. There will still be a record
// for table1 if there are no details in table2, because of the LEFT JOIN
// If you don't want that, you can use INNER JOIN instead, and you won't need
// the 'if' below.
if ($row['tab2_col1'] !== null) {
echo $row['tab2_col2'] . "-";
echo $row['tab2_col3'] . "</br>";
}
}
Instead of having 2 while loops, what you can do is join the 2 tables and then iterate over the result.
If you're not sure what join is look here: https://dev.mysql.com/doc/refman/5.1/de/join.html
Also here is a fairly simple query written using join: Join Query Example
You can use this. One relation with two tables:
<?php
$result1 = mysql_query("SELECT tab2_col2, tab2_col3 FROM table1, table2 where tab2_col1 = tab1_id ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ),)
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
?>
Like Sushant said, it would be better to use one JOIN or simpler something like that:
SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id
I am trying to add an Option Group to this select box. I am getting the rows and the count of the number of options in the record set. I can either get the count or set the group. I have yet to do both!
<select name="DETAILS">
<?php
include("config.php");
$sql = "SELECT tblDetails.DetailType AS type, CONCAT(tblDetails.DetailName,' (', Count(tblLocDet.DetailID),')') AS DetailName
FROM tblLocations INNER JOIN (tblLocDet INNER JOIN tblDetails ON tblLocDet.DetailID = tblDetails.DetailID) ON tblLocations.LocationID = tblLocDet.LocationID
GROUP BY tblDetails.DetailType, tblDetails.DetailName, tblLocations.CityID, tblLocations.AreaID, tblLocations.CuisineID
HAVING (((tblLocations.CityID)=16) AND ((tblLocations.AreaID)=131) AND ((tblLocations.CuisineID)=3));";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<optgroup label='{$row['type']}'>";
$DetailNames = explode('|', $row['DetailName']);
foreach($DetailNames as $DetailName) {
echo "<option value='".$DetailName."'>".$DetailName."</option>";
}
echo "</optgroup>";
}
?>
</select>
Help is appreciated.
I have two tables in mysql. Following is my script.
<?php
$conn=mysql_connect("localhost",'root','');
mysql_select_db('test');
$sql = "SELECT data_student.name,ozekimessagein.msg
FROM ozekimessagein,data_student
WHERE ozekimessagein.sender=data_student.sender
ORDER BY ozekimessagein.msg";
$res=mysql_query($sql);
$cn=mysql_num_rows($res);
for($x=0;$x<$cn;$x++)
{
list($name,$msg)=mysql_fetch_row($res);
echo "<li>$name,$msg";
}
mysql_close($conn);
?>
this should display the name from table data_student table and the message from ozekimessagein as long as the sender in data_student table match with the sender in the ozekimessagein table. But it doesn't work.
Try this ::
SELECT
data_student.name,
ozekimessagein.msg
FROM ozekimessagein
inner join data_student on ozekimessagein.sender=data_student.sender
ORDER BY ozekimessagein.msg
try this
<?php
$conn=mysql_connect('localhost','root','');
mysql_select_db('test');
$sql = "
SELECT s.name AS names, o.msg AS msgs
FROM ozekimessagein o
INNER JOIN data_student s
ON o.sender = s.sender
ORDER BY s.name";
$res=mysql_query($sql);
while ($row = mysql_fetch_assoc($res)) {
echo "<li>".$row['names']." : ".$row['msgs']."</li>";
}
mysql_close($conn);
?>
I've got a database and I'd like to show some results from it without getting duplicates
Example
<?php
$sql = "select * from my_table order by subcategory ASC";
$result = mysql_query($sql) or die($qry);
if (mysql_num_rows($result) == '0') {
echo "No subcategory";
} else {
while ($line = mysql_fetch_array($result)) {
echo $line[subcategory];
echo "<br>";
}
}
?>
It currently shows me all subcategories even if they are duplicated
Question: How i can filter the results so that it will only show a subcategory once even if it's in there 4 times.
Do I need to add something to this code to shows only without duplicated?
$sql ="select * from rss order by subcategory ASC";
You can use DISTINCT in your SQL, to avoid getting duplicates back from the database, like this:
select distinct * from my_table order by subcategory ASC
Use GROUP BY
$sql = "select subcategory from rss group by subcategory"
See the manual for more information: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html
Look into SELECT DISTINCT and GROUP BY
select * from rss order by subcategory ASC
First of all it is a good practive to expand wildcard. List all of the columns instead of using *
There are two approaches on what you're trying to achieve depending on what you need:
Select distinct column1,column2 from rss order by subcategory desc
select max(column1), max(column2), subcategory from rss order by subcategory desc group by subcategory
use continue; keyword and check for duplicates in your while loop
<?php
$sql = "select * from my_table order by subcategory ASC";
$result = mysql_query($sql) or die($qry);
if (mysql_num_rows($result) == '0') {
echo "No subcategory";
} else {
while ($line = mysql_fetch_array($result)) {
if ($dupes[$line['subcategory']])
continue;
$dupes[$line['subcategory']]++;
echo $line['subcategory'];
echo "<br>";
}
}
?>
or just use distinct
$sql ="select distinct * from rss order by subcategory ASC";
You should take a look at array_unique(). Use it to remove all duplicates from the array.