I want to find if there are any duplicate ticket number in my table.
my code below is displaying the first ticket number from classes table which is 1039, I want to diplay if there is a duplicate. 1039 is NOT a duplicate. what is my problem?
$query = "SELECT ticket, COUNT(ticket) AS NumOccurrences FROM classes GROUP BY ticket HAVING (COUNT(ticket) > 1)";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$ticket = $row['ticket'];
}
if($result)
{
echo $ticket. "<br/>";
echo "there are " . mysql_num_rows($result) . " tickets ";
}
else
{
echo "no duplicate ";
}
You need a GROUP BY clause, otherwise you're counting all tickets.
SELECT ticket, COUNT(*) c FROM classes GROUP BY ticket HAVING (c > 1)
Try
SELECT ticket, COUNT(ticket) as `count` FROM classes GROUP BY ticket WHERE `count` > 1
Related
I'm trying to get the latest info about some specific person, and I'm using a query like
SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID DESC LIMIT 1
and
SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID DESC LIMIT 1
because in the Table each day will insert new data for different person at the instant of updating it (for record reference), so I would like to print out a few persons latest info by "ORDER BY ID DESC LIMIT 1"
I have tried to print it out with "mysqli_multi_query" and "mysqli_fetch_row"
like
$con=mysqli_connect($localhost,$username,$password,'Table');
$sql = "SELECT * FROM Table WHERE Name LIKE 'Peter' ORDER BY ID
DESC LIMIT 1 ";
$sql .= "SELECT * FROM Table WHERE Name LIKE 'Mary' ORDER BY ID
DESC LIMIT 1";
// Execute multi query
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con)) {
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
echo '<tr>'; // printing table row
echo '<td>'.$row[0].'</td>';
echo '<td>'.$row[1].'</td>';
echo '<td>'.$row[2].'</td>';
echo '<td>'.$row[3].'</td>';
echo '<td>'.$row[4].'</td>';
echo '<td>'.$row[5].'</td>';
echo '<td>'.$row[6].'</td>';
echo '<td>'.$row[7].'</td>';
echo '<td>'.$row[8].'</td>';
echo '<td>'.$row[9].'</td>';
echo '<td>'.$row[10].'</td>';
echo '<td>'.$row[11].'</td>';
echo '<td>'.$row[12].'</td>';
echo '<td>'.$row[13].'</td>';
echo '<td>'.$row[14].'</td>';
echo'</tr>'; // closing table row
}
// Free result set
mysqli_free_result($result);
}
}
while (mysqli_next_result($con));
}
mysqli_close($con);
?>
In the result page , it doesn't show any error message , but no results are printed.
The individual queries were tested.
Please advise, much thanks
Is there another way to keep the query simple, so there is no need to use mysqli_multi_query?
Best practice indicates that you should always endeavor to make the fewest number of calls to the database for any task.
For this reason, a JOIN query is appropriate.
SELECT A.* FROM test A INNER JOIN (SELECT name, MAX(id) AS id FROM test GROUP BY name) B ON A.name=B.name AND A.id=B.id WHERE A.name IN ('Peter','Mary')
This will return the desired rows in one query in a single resultset which can then be iterated and displayed.
Here is an sqlfiddle demo: http://sqlfiddle.com/#!9/2ff063/3
P.s. Don't use LIKE when you are searching for non-variable values. I mean, only use it when _ or % are logically required.
This should work for you:
$con = mysqli_connect($localhost,$username,$password,'Table');
// Make a simple function
function personInfo($con, $sql)
{
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<table>
<tr>';
for($i=0; $i < count($row); $i++) echo '<td>'.$row[$i].'</td>';
echo '</tr>
</table>';
}
}
}
$sql1 = "SELECT * FROM Table WHERE Name='Peter' ORDER BY ID DESC LIMIT 1 ";
$sql2 = "SELECT * FROM Table WHERE Name='Mary' ORDER BY ID DESC LIMIT 1";
// Simply call the function
personInfo($con, $sql1);
personInfo($con, $sql2);
I have database with 8 different product category for download.
pic, app, ebo, tem, des, cod, mus, cat
I'd like to count clients total downloaded products and total downloads of each product category.
Maximum daily limit downloads for category product is 3.
When user log in should see how many downloads remain.
Here is working code
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "You have downloaded". $row['sum'] ." products.";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client' and product like 'pic'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['sum'] ." downloaded pictures";
$leftovers = 3 - $row['sum'];
echo " $leftovers pictures remain for download";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum FROM service_downloads where client_id like '$client' and product like 'app'";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['sum'] ."downloaded applications";
$leftovers = 3 - $row['sum'];
echo " $leftovers applications remain for download.";
echo "<br />";
}
$query = "SELECT CO.... This procedure repeat eight times for different product category.
result
You have downloaded 12 products.
3 downloaded pictures 0 pictures remain for download.
1 downloaded applications 2 applications remain for download.
3 downl.......
You could use a GROUP BY statement to group your results.
SELECT COUNT(`Product`) AS `Sum`, `Product`
FROM `service_downloads`
WHERE `client_id` = '<client_id>'
GROUP BY `Product`
Then you can use one while statement to loop through each product:
// Print out result
while($row = mysql_fetch_array($result))
{
echo "". $row['Sum'] ."downloaded " . $row['Product'];
$leftovers = 3 - $row['Sum'];
echo " $leftovers " . $row['Product'] . " remain for download.";
echo "<br />";
}
$query = "SELECT COUNT(*) as sum,product FROM service_downloads where client_id like '$client' GROUP BY product";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result))
{
echo "You have downloaded". $row['sum'] ." ".$row['product'];
echo "<br />";
}
This should work
You should breakdown the quantity of downloads per category in one query:
SELECT product,COUNT(*)
FROM service_downloads
WHERE client_id like '$client';
I also don't think you need to use LIKE; you probably want to use =
You can get a single result set with all the sums in it with this query.
SELECT COUNT(*) as sum, product
FROM service_downloads
WHERE client_id = '$client'
AND PRODUCT IN ('pic', 'app', 'abc', 'def', 'ghi')
GROUP BY product WITH ROLLUP
ORDER BY product NULLS FIRST
This will give you one row for each specific product and a summary (rollup) row with a NULL value in the product column.
If this query takes a long time create an index on (client, product) and it should go pretty fast.
If you are showing this data frequently, which is what it sounds like, then you should have a separate table that represents those SUMs and is index by CLIENT_ID.
You can then increment/decrement that value each time you add a new entry.
For example, when you add a new row to service_downloads with an entry in 'pic' for CLIENT_ID 1, then you would also increment this shortcut table:
UPDATE service_counts SET pic=pic+1 WHERE client_id=1;
I have two tables are subscribe and favorite.
subscribe [id subscribeid subscribeto datetime]
favorite [id wordid userid datetime]
So, I want to show these actively in news feed that can separate in each loop, where from which table?my code is look like this
$sql = "(SELECT * FROM favorite) UNION (SELECT * FROM subscribe) ORDER BY datetime DESC";
$result = mysql_query($sql)or die(mysql_error());
while($array = mysql_fetch_array($result)){
if($array['wordid']!=""){
echo "This's favorite feed";
}else{
echo "This's subscribed feed";
}
//echo $array['wordid'];
echo "<hr />";
}
In the condition of if($array['wordid']!="") I think it should work, but when in echo in commented line it always has a values, I don't know why is that.
Please help or suggest, thanks.
You can use alias function to union the result set. Based on cate field you can determine the results from which table.
Use mysqli extension instead of mysql
<?php
$sql = "SELECT id,
subscribeid As common_id,
subscribeto,
datetime, 'subscribe' As cate
FROM subscribe
UNION
SELECT id,
wordid As common_id,
userid As subscribeto,
datetime,
'favorite' As cate
FROM favorite";
$result = mysql_query($sql)or die(mysql_error());
while($array = mysql_fetch_array($result)){
if($array['cate']!="subscribe"){
echo "This's favorite feed";
}else{
echo "This's subscribed feed";
}
//echo $array['wordid'];
echo "<hr />";
}
I generated the below query for php using PHP-MYADMIN,
My question is how to print the 30 rows it generates? when i use "see quote" it just errors out.
i am trying to echo the rows with search term and count in < div >< /div > tags each in its own.
Facebook 38 searches
Another Feed 25 searches
Timeline 18 searches
and so on to row 30.
$result=mysql_query($sql)
$sql = 'SELECT COUNT(*) AS `Rows`, `search`, SUM(searched) FROM `af_timeline_search` GROUP BY `search` ORDER BY SUM(searched) DESC LIMIT 0, 30 ';
/* top searches */
$sqlthis = mysql_query('SELECT COUNT(*) AS `Rows`, `search` FROM `af_timeline_search` GROUP BY `search` ORDER BY `Rows` DESC');
$num=mysql_num_rows($sqlthis);
$arrS = mysql_fetch_array($sqlthis);
$i=0;
while ($i < $num){
echo 'Search '.$arrS[$i].'';
$i++;
}
Screen Shot of Query in PHPmyadmin.
I think the best you can do is to take a look at this: mysql-fetch-array
There you'll find the answer on how to loop over that array :)
$result = mysql_query("SELECT * FROM YOURDATABASE");
while($row = mysql_fetch_array($result))
{
echo $row['search'] . " " . $row['somenumber'];
echo " searches";
}
mysql_close($con);
I have found the solution to this. Thank you all for your guidance. :-) "you all rock"
$sql = "SELECT COUNT(*) AS Rows, search, SUM(searched) FROM anotherfeed.af_timeline_search GROUP BY search ORDER BY SUM(searched) DESC";
$result=mysql_query($sql) or die ('Error! yo.');
$row = mysql_fetch_array($result);
echo '<pre>';
print_r($row);
echo '</pre>';
/* top searches with loop */
$sql = "SELECT COUNT(*) AS Rows, search, SUM(searched) FROM anotherfeed.af_timeline_search GROUP BY search ORDER BY SUM(searched) DESC LIMIT 0, 20";
$result=mysql_query($sql) or die ('Error! yo.');
while($row = mysql_fetch_array($result))
{
echo ' (';
echo urldecode($row['search']) . " " . $row['SUM(searched)'] . "";
echo ') ';
}
I am able to print the array, hopefully i can get the loop down with a while statement. Feel free to add a loop if you have or know one that is better... Thank You.
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.