I am trying create a order history page. An SQL statement that finds all the applications based on a order_ID in an orderdetails_tbl. Here is the SQL.
SELECT * FROM applications_tbl INNER JOIN orderdetails_tbl ON orderdetails_tbl.app_ID = applications_tbl.app_ID WHERE orderdetails_tbl.order_ID = $orderID
The results are displayed using this PHP.
$result = mysql_query("SELECT *
FROM applications_tbl
INNER JOIN orderdetails_tbl ON orderdetails_tbl.app_ID = applications_tbl.app_ID WHERE orderdetails_tbl.order_ID = ".$order_ID."");
$row = mysql_fetch_assoc($result);
echo "<table>";
do { ?>
<tr style="background-color:#fff">
<td> <img src="getimage.php?ID=<?php echo $row['app_ID']; ?>" width="100" height="100" alt="IMAGE" /></td>
<td width="20%"><?php echo $row['app_name']; ?></td>
<td><?php echo $row['app_desc']; ?></td>
<td width="15%"><?php echo $row['app_cost']; ?></td>
</tr>
<?php
} while ($row = mysql_fetch_assoc($result));
The SQL returns the correct values and the PHP displays them correctly. My issue is that it on the webpage it returns many duplicate results. It appears to be random, but I noticed the more apps/items in the order the more duplicate results. In phpMyAdmin when I run the SQL it doesn't display duplicates.
Cheers for your time. Any advice will be greatly received!
Use GROUP BY
$result = mysql_query("SELECT * FROM applications_tbl
INNER JOIN orderdetails_tbl ON orderdetails_tbl.app_ID = applications_tbl.app_ID
WHERE orderdetails_tbl.order_ID = ".$order_ID." GROUP BY app_ID");
A tip is to use alias to get sql-statements more readable like this:
$result = mysql_query("SELECT * FROM applications_tbl at INNER JOIN orderdetails_tbl od ON od.app_ID = at.app_ID WHERE od.order_ID = ".$order_ID);
But to answer your question you could use DISTINCT on one field and list the fields you want to have included in your recordset or add a GROUP BY -statement at the end of the SQL-statement.
DISTINCT: (example)
$result = mysql_query("SELECT DISTINCT at.id, od.app_ID FROM applications_tbl at INNER JOIN orderdetails_tbl od ON od.app_ID = at.app_ID WHERE od.order_ID = ".$order_ID);
OR
GROUP BY (example)
$result = mysql_query("SELECT * FROM applications_tbl at INNER JOIN orderdetails_tbl od ON od.app_ID = at.app_ID WHERE od.order_ID = ".$order_ID . " GROUP BY at.id");
What is the actual value of $order_ID ? (I ask because you say you have the same query and you only get duplicates when viewing in browser. It seems very odd)
Related
I need to run two statements to return the data I need. The below code will return all needed except the count column which can be retrieved from a different table.
How can I run these two statements in the same code to retrieve the count as well?
Here is the code I have:
<?php
$query = "SELECT * from $CLIENTS_DATABASE order by id DESC";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td><?php echo $row["name"]; ?> </td>
<td><?php echo $row["url"]; ?> </td>
<td><?php echo $row["secret"]; ?> </td>
<td><?php echo $row["count"]; ?> </td>
</tr>
<?php
}
mysqli_free_result($result);
}
?>
The other statement that the count data I need is this:
$query = "SELECT COUNT(*) as count from visits where id_client='$result[id]'"
Thanks for your time and any help you can provide.
Join the two queries.
$query = "SELECT order.*, IFNULL(c.count, 0) AS count
FROM $CLIENTS_DATABASE AS order
LEFT JOIN (SELECT id_client, COUNT(*) AS count
FROM visits
GROUP BY id_client) AS c
ON c.id_client = order.id
ORDER BY order.id DESC";
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.
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 use this SQL query to get results from different tables
<?
$sql = "SELECT gtem.gname AS itmnme, gvendor.gname AS vendor, gtem.col AS qty
FROM gpopackageline
LEFT JOIN gpo ON gpo.gpoid = gpopackageline.gpoid
LEFT JOIN gtem ON gpopackageline.gtemid = gtem.gtemid
LEFT JOIN gvendor ON gitem.gvendorid = gvendor.gvendorid
WHERE gpopackageline.gpoid='".$sdo['swelid']."' ";
$row = dblib_get_row_list($sql);
?>
<td class="contents51" width="100%"><?=$row['itmnme']?> </td>
<td class="contents51" width="100%"><?=$row['vendor']?> </td>
<td class="contents51" width="100%"><?=$row['qty']?> </td>
Issue is I get only 1 and first result printed.
When i test query in phpmyadmin I get all the results
Does anyboby can help with this
Thank You
You need to loop through your results, either by a while, or foreach - depending on your logic.
For example
<?
$sql = "SELECT gtem.gname AS itmnme, gvendor.gname AS vendor, gtem.col AS qty
FROM gpopackageline
LEFT JOIN gpo ON gpo.gpoid = gpopackageline.gpoid
LEFT JOIN gtem ON gpopackageline.gtemid = gtem.gtemid
LEFT JOIN gvendor ON gitem.gvendorid = gvendor.gvendorid
WHERE gpopackageline.gpoid='".$sdo['swelid']."' ";
$getRows = dblib_get_row_list($sql); //Assuming this returns everything in an assoc array
foreach($getRows as $row) {
?>
<td class="contents51" width="100%"><?=$row['itmnme']?> </td>
<td class="contents51" width="100%"><?=$row['vendor']?> </td>
<td class="contents51" width="100%"><?=$row['qty']?> </td>
<?php
}
?>
I don't know what is your dblib_get_row_list is return. If it returns array then it should work as you expected.
<?
$sql = "SELECT gtem.gname AS itmnme, gvendor.gname AS vendor, gtem.col AS qty
FROM gpopackageline
LEFT JOIN gpo ON gpo.gpoid = gpopackageline.gpoid
LEFT JOIN gtem ON gpopackageline.gtemid = gtem.gtemid
LEFT JOIN gvendor ON gitem.gvendorid = gvendor.gvendorid
WHERE gpopackageline.gpoid='".$sdo['swelid']."' ";
$result = dblib_get_row_list($sql);
foreach($result as $row ){
echo "<td class='contents51' width='100%'>".$row['itmnme']."</td>";
echo "<td class='contents51' width='100%'>".$row['vendor']."</td>";
echo "<td class='contents51' width='100%'>".$row['qty']."</td>";
}
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;