Dont display multiple rows more than once in count query? - php

I'm creating a website that COUNTS all the occurences of something.
Table:
Pizza John
Google John
Pizza Harry
Lets say you like google and pizza. It will show it like this:
John, John, Harry.
I would like it to appear like this:
John, Harry.
What am I doing wrong? Here's my code. Does it have anything to do with the while loop inside the while loop? How could I make it appear the way I want it to.. I can't figure it out.
$people_like = mysqli_query ($link,
"SELECT user_liked_by FROM (
SELECT COUNT(user_liked_by) AS total, id, user_liked_by
FROM whatilike WHERE whats_liked LIKE '%$thing_liked%' &&
user_liked_by !='$user'
GROUP BY user_liked_by
ORDER BY COUNT(user_liked_by) DESC ) as names;
");
while ($rpl = mysqli_fetch_assoc ($people_like)) {
$person_like_u = $rpl ['user_liked_by'];
$pluq = mysqli_query ($link, "SELECT profile_pic FROM users WHERE
username='$person_like_u'");
while ($pluqr = mysqli_fetch_assoc ($pluq)) {
$pli = $pluqr ['profile_pic'];
echo "<a href='profile.php?u=$person_like_u' >
<img src='data/user_photos/$pli' height='50px' width='50px'
style='border-radius:400px;' id='ioplu' ></a>";
}
}

$people = [];
while ($rpl = mysqli_fetch_assoc ($people_like)) {
$people[] = $rpl ['user_liked_by'];
}
$people = array_unique(array_map("trim",$people));
foreach($people as $p){
$pluq = mysqli_query ($link, "SELECT profile_pic FROM users WHERE
username='$p'");
while ($pluqr = mysqli_fetch_assoc ($pluq)) {
$pli = $pluqr ['profile_pic'];
echo "<a href='profile.php?u=$person_like_u' >
<img src='data/user_photos/$pli' height='50px' width='50px'
style='border-radius:400px;' id='ioplu' ></a>";
}
}

Related

Display data once if same

With this code:
$query = "select users.id_user, users.full_name, users.rights, users.group, group.id, group.name
from users
inner join group
on users.group=group.id
where users.rights= 2";
// connection code
while ($re = mysql_fetch_array($res))
{
$id_user = $re["id_user"];
$id_group = $re["id"];
$full_name= $re["full_name"];
$group_name= $re["name"];
echo "<div>";
echo "<p><strong>$group_name</strong></p>";
echo "$full_name<br />";
echo "</div>";
}
?>
I get this:
Group1
User1
Group1
User2
Group2
User3
Group2
User4
and I need it like this:
Group1
User1
User2
Group2
User3
User4
How to show group name just once?
Tweak your query that you use the database power to give you the information you need.
select
usergroup.name
, GROUP_CONCAT(user.name SEPARATOR '<br />') 'users'
from
user
inner join
usergroup
on
user.usergroup_id = usergroup.id
where
user.rights = 2
group by
usergroup.id
see demo http://sqlfiddle.com/#!2/0d104/1 in your php you can use $row['users']
You may use associative arrays for this task. For example, make an array $groups, and in your while loop do something like
$groups[$re["name"]]["full_name"][] = $re["full_name"];
Then, when you display your html loop through $groups and inside it loop though full names.
This is what I came up with:
$query = "SELECT users.id_user, users.full_name, users.rights, users.group, group.id, group.name
FROM users
INNER JOIN group
ON users.group=group.id
WHERE users.rights=2
ORDER BY group.name ASC";
// connection code
$group_name = '';
while ($re = mysql_fetch_array($res))
{
if( $group_name === '' )
{
$group_name = $re["name"];
echo "<div>";
echo "<p><strong>$group_name</strong></p>";
}
elseif( $group_name !== $re["name"] )
{
$group_name = $re["name"];
echo "</div>";
echo "<div>";
echo "<p><strong>$group_name</strong></p>";
}
$id_user = $re["id_user"];
$id_group = $re["id"];
$full_name= $re["full_name"];
echo "$full_name<br />";
}
?>
It's basically ordering the result by the group names, and while it iterates, the group name is being checked. If it's the same, only the name is printed, if it differs, the div is closed, a new one is made and the new group title is echoed.

search query order by asc or desc

Hi what's the best way to do a 'order by' from a query without executing a query for another time? Lets say I have a search query when I have to find names or surnames using a form ,an example :
//Array for storing WHERE part of query
$where=array();
if(!empty($name)) AND !empty($surname)){
$where[]="Name LIKE '%$name%'" .
"AND Surname LIKE '%$surname%'";
}
elseif(!empty($name)){
$where[]="Name LIKE '%$name%'";
}
elseif(!empty($surname)){
$where[]="Surname LIKE '%$surname%'";
}
$where = implode(' AND ', $where);
$sql="SELECT Name,Surname FROM TABLE WHERE $where ORDER BY Name DESC";
$res = mysql_query($sql);
while ($row = mysql_fetch_array($res, MYSQL_NUM)) {
$name = $row[0];
$surname = $row[1];
echo"$name";
echo"$surname";
}
How can I display Name or Surname in ASC mode(ORDER BY Name ASC) after my search"Name LIKE %surname%",without executing again the SQL query? I want for example when I search for a name containing "ich"word to have a list in this way:
MICHAEL
PICHAEL
XICHAEL
=> the ASC mode
XICHAEL
PICHAEL
MICHAEL
=> the DESC mode
I really don't think I'm understanding your question correctly, but I'm going to go out on a limb here and guess you just want to order by two different columns?
$sql="SELECT Name,Surname FROM TABLE WHERE $where ORDER BY Name DESC, Surname ASC";
by the way you had an extra " in your query string
Also, you may want to look into using mysql_fetch_assoc instead of mysql_fetch_array
This is just me nitpicking now ... but instead of using:
echo"$name";
echo"$surname";
You can just write:
echo $name;
echo $surname;
Arr you talking about reversing the order of an array like this?
<?php
//Array for storing WHERE part of query
$where=array();
if(!empty($name) && !empty($surname)){
$where[]="Name LIKE '%$name%'" .
"AND Surname LIKE '%$surname%'";
}
elseif(!empty($name)){
$where[]="Name LIKE '%$name%'";
}
elseif(!empty($surname)){
$where[]="Surname LIKE '%$surname%'";
}
$where = implode(' AND ', $where);
$sql="SELECT Name,Surname FROM TABLE WHERE $where ORDER BY Name";
$res = mysql_query($sql);
$names = array();
$surnames = array();
$wholeNames = array();
$x='0';
while ($row = mysql_fetch_array($res)) {
if(!empty($row['Name'])){
$names[$x] = $row['Name'];
}
if(!empty($row['Surname'])){
$surnames[$x] = $row['Surname'];
}
if(!empty($row['Name'])&&!empty($row['Surname'])){
$wholeNames[$x] = $row['Name'].' '.$row['Surname'];
}
$x++;
}
print "<pre>\n";
print_r ($names);
print_r ($surnames);
print_r ($wholeNames);
print "</pre>\n";
$reversed_names=array_reverse($names);
$reversed_surnames=array_reverse($surnames);
$reversed_wholeNames=array_reverse($wholeNames);
print "<pre>\n";
print_r ($reversed_names);
print_r ($reversed_surnames);
print_r ($reversed_wholeNames);
print "</pre>\n";
?>
Something to watch out for, if you're using LIKE with the wildcards a search for "Art" would match Bart, Arthur, carter, and any other word with "Art" in it.

while (double?) foreach or join?

I have an Excel sheet which is converted to csv and then code imports that into mysql.
In Excel I have in first row A's and B's
I get output, It works but I cannot get into displaying data right.
How I'm trying to display is A B then break and again A B and so on. It is ordered by contact_id but I only get AAAAAA's and 1 B if I try double while.
This is the code with which I have tried to achieve this. Tried double while and I have googled and I have noticed double while is not working, Couldn't get it to work with mysql JOIN either and have never worked with foreach function.
$data = dbquery("SELECT contact_id, contact_first, contact_last, contact_email FROM contact_info WHERE contact_first='A)' ORDER BY contact_id ASC");
$data2 = dbquery("SELECT contact_id, contact_first, contact_last, contact_email FROM contact_info WHERE contact_first='B)' ORDER BY contact_id ASC");
while ($userdata = dbarray($data)) {
echo "<li><ul class='ulcla'>";
echo "<h1>".$userdata['contact_first']."</h1>";
echo "<li>".$userdata['contact_last']."</li>";
echo "</ul><br>";
while ($userdata = dbarray($data2)) {
echo "".$userdata['contact_id']." - ".$userdata2['contact_first']." - ".$userdata2['contact_last']." - ".$userdata2['contact_email']."";
echo "<br>";
}
echo "</ol></div>";
}
How could I loop data like that?
Change while ($userdata = dbarray($data2)) { to while ($userdata2 = dbarray($data2)) {for innner while loop
$data = dbquery("SELECT contact_id, contact_first, contact_last, contact_email FROM contact_info WHERE contact_first='B)' ORDER BY contact_id ASC");
$data2 = dbquery("SELECT contact_id, contact_first, contact_last, contact_email FROM contact_info WHERE contact_first='B)' ORDER BY contact_id ASC");
while ($userdata = dbarray($data)) {
echo "<li><ul class='ulcla'>";
echo "<h1>".$userdata['contact_first']."</h1>";
echo "<li>".$userdata['contact_last']."</li>";
echo "</ul><br>";
while ($userdata2 = dbarray($data2)) {
echo "".$userdata2['contact_id']." - ".$userdata2['contact_first']." - ".$userdata2['contact_last']." - ".$userdata2['contact_email']."";
echo "<br>";
}
echo "</ol></div>";
}
If there are the same amount of each A and B then you can create two arrays from the output and use a simple for loop to go through the keys. So it could echo $userdata[$x] and $userdata2[$x] where $x is the loop iterator.
Try to avoid using multiple loops, especially nested loops.
while ($userdata = dbarray($data)) {
//your stuff
while ($other_userdata = dbarray($data2)) {
//your other stuff
}
}

Returning each unique user from a MySQL table and also the count of the number of rows for each user

I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike

While loop not printing all answers

This might be really simple, but i cannot figure out the problem with this code:
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
Now based on my database the query is returning 2 results, the echo mysql_num_rows($sql) also gives out 2. However the reached is echoed only once. Does anyone see a potential problem with the code?
P.S: My bad, $sql is being repeated, that was a silly mistake
It will only echo once because of this line :
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
your overwriting the $sql variable.
Why not just run a single query and join the data you require ?
try ($sql2 instead of $sql and $sql[0] to $sql2[0]):
$sql = mysql_query("select * from Temporary_Stock_Transfer where Emp_ID = '$emp_id' and Company_ID = '$company_id'");
if(mysql_num_rows($sql) == 0) {
echo "<tr><td colspan='3'><i>You currenty have no items</i></td></tr>";
}else {
while($row = mysql_fetch_array($sql)) {
echo mysql_num_rows($sql);
echo 'reached';
$book_id = $row[1];
$sql2 = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
echo "<tr><td>".$sql2[0]."</td><td>".$row[2]."</td><td><span class='label label-important'>Remove</span></td></tr>";
}
}
I think it'll be because you are ressetting the sql variable
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
when you are still using it in the while loop. :P
It's probably this line:
$sql = mysql_fetch_row(mysql_query("select title from Book where Book_ID = '$book_id'"));
Try using a different variable name.
You are changing the $sql variable inside the loop, therefore the next time you run $row = mysql_fetch_array($sql), the value will be different (probably won't be any based on your code).
Inside the while loop you are re-using the same variable: $sql. This is used to control the terminating condition of the loop.
Using a different variable name, e.g. $sql2 should leave the original variable intact and the loop should proceed as expected.

Categories