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.
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);
Trying to get PHP to read my MYSQL db for transactions, divide them by "category" and print the total for each category.
Using a similar structure as the code below, how can I make it do all of the below for each category number. In my db, categories are a number 1-10.
Any help would be much appreciated!
<?php
$result = mysql_query("SELECT SUM(amount) AS value_sum FROM TRANSACTIONS where category=2")
or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
echo "<div class='col1'>";
echo round ($row['value_sum'], 2);
echo "</div>";
}
?>
$result = mysql_query("SELECT SUM(amount) AS value_sum
FROM TRANSACTIONS
GROUP BY category");
Now you have a row per category.
I have this code:
<?php
$data = mysql_query("SELECT id FROM board") or die(mysql_error());
while($info = mysql_fetch_assoc( $data ))
{
Print " ".$info['id']." ";
myOtherQuery($info['id']);
}
function myOtherQuery($id) {
$result = mysql_query("SELECT COUNT(is_following_board_id) FROM follow WHERE is_following_board_id='$id'");
$c = mysql_result($result, 0);
}
?>
It lists all ID's with a number beside it, defined as $c above in the second query.
For simplicity I have remove the HTML of the code but it aligns in a table.
I'm trying to ORDER BY $c, but don't know how to do it. Since it is defined AFTER the select query: $data = mysql_query("SELECT id FROM board")
It errors if I add: $data = mysql_query("SELECT id FROM board ORDER BY '$c'")
Is there anything I can add to the bottom of the code to make this order by work?
You want to do this in one query, by aggregating the results:
select is_following_board_id, sum(is_following_board_id) as cnt
from follow
group by is_following_board_id
order by cnt desc;
Your approach was to fetch the result and then fetch the count. Rather inefficient, because SQL is designed for this type of query.
I have two tables in my database:
1) blog_table
2) content
In blog_table I have values called postID that may or may not match up to values called id in the table content. I am wanting to know how I can write a while loop or foreach loop that will cycle through content table and perform one action if the id equals the value of postID in the blog_table and perform a different action if it doesn't.
Right now I can only get id = postID
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogtable))
{
$getblogposts1 = mysql_query("SELECT postID FROM `$blog_table`");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
if( $row1['postID'] == $row['id']) {
echo "do something<br>";
}else{
echo "do something else<br>";
}
} echo "<p></p>";
}
[Edit based on OP's comments and revised question]
$getblogposts = mysql_query("SELECT * FROM content WHERE type = '5' AND blogID = '{$_REQUEST['id']}' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getblogposts))
{
$matches = mysql_query("SELECT * FROM $blog_table WHERE postID = $row['id']");
if (mysql_num_rows($matches) > 0)
{
// do something
}
else
{
// do something else
}
}
Regarding a different design, I can't say for sure that it's necessary, but I don't like running a loop of queries like this. I think one query should be enough to get everything you need in this case. Maybe if you describe your application, we could find a better query or more appropriate design.
Just providing an easier to see solution for you to your problem.
I suggest using inner joins which will solve the issue at hand.
For example, Something like:
SELECT * FROM content AS C INNER JOIN $blog_table AS B on B.postID = C.id
Here is a great introduction to joins (inner, left, right, full):
http://www.w3schools.com/sql/sql_join.asp
$blog_table = $_REQUEST['blog_table'];
$getblogtable = mysql_query("SELECT postID FROM `$blog_table`");
while ($row = mysql_fetch_assoc($getblogtable))
{
$postID = $row['postID'];
$getblogposts1 = mysql_query("SELECT * FROM content WHERE id = '$postID' ORDER BY `order` ASC");
while ($row1 = mysql_fetch_assoc($getblogposts1))
{
// if( $row1[id] == $postId )
// do something
// else
// do something else
}
}
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.