Group by is not showing all the rows - php

I am working in WordPress and below is my select query. I have used leftjoin and group by. But only one row is returned if I have duplicate entries in my articles.username coloumn. So I want all the rows to be returned with group by and duplicates should be allowed in username field.
PHP Code
$sqll = "SELECT articles.aid, articles.username, articles.competition, articles.path, articles.category, articles.title, Sum(zvotes.zvotes) AS votessum FROM articles LEFT JOIN zvotes on articles.aid=zvotes.aid GROUP BY articles.competition HAVING articles.category = '$cat' && articles.competition = '$comp' ORDER BY votessum";
$results = $wpdb->get_results($wpdb->prepare($sqll)) or die(mysql_error());
Snapshot of articles table
Snapshot of votes table (currently no data in it)
Below is my full code
echo '<form action="" method="post">';
echo '<select name="category" id="category" style="width:250px; background-color:lightgrey;">';
echo '<option value="" disabled="disabled" selected="selected" ">Select category</option>';
echo '<option value="My Testimony">My Testimony</option>';
echo '<option value="Love & Relationships">Love & Relationships</option>';
echo '<option value="Miscellaneous">Miscellaneous</option>';
echo '</select>';
echo '<input type="submit" name="a" value="Search" style="margin-left:15px; margin-bottom:15px;">';
echo '</form>';
//show after drop down value is selected
if(isset($_POST['a'])){
//echo "zeeshanaslamdurrani". "<br>";
echo do_shortcode('[ujicountdown id="Photos Contest" expire="2015/04/30 00:00" hide="true" url="" subscr="sdf" recurring="" rectype="second" repeats=""]');
global $wpdb;
//get current competition value
$cat =$_POST['category'];
$comp = $wpdb->get_var("SELECT competition FROM competition ORDER BY cid DESC LIMIT 1");
//echo $comp;
$sql = "SELECT * FROM articles WHERE category='$cat'";
$comp = $wpdb->get_var("SELECT competition FROM competition ORDER BY cid DESC LIMIT 1");
echo "current competition is ". $comp;
//test query
$sqll = "SELECT articles.aid, articles.username, articles.competition, articles.path, articles.category, articles.title, Sum(zvotes.zvotes) AS votessum FROM articles LEFT JOIN zvotes on articles.aid=zvotes.aid GROUP BY articles.competition HAVING articles.category = '$cat' && articles.competition = '$comp' ORDER BY votessum";
$results = $wpdb->get_results($wpdb->prepare($sqll)) or die(mysql_error());
foreach( $results as $result ) {
echo '<form action="" method="post">';
echo "<input name='category' type='hidden' value='$result->category'>";
echo $result->title.'<br>';
echo "<img src='$result->path' width='150' height='150' >" . '<br><br>';
echo $result->body.'<br>';
echo "<input name='comp' type='hidden' value='$result->competition'>";
echo $result->username.'<br>';
echo $result->votessum.'<br>';
echo "<input style='margin-bottom:30px;' value='vote' name='submit' type='submit'/></form>";
}//end of foreach
}//end of isset
I have a drop down on the top of the page and a search button as shown below on pressing search the results are shown but if I add duplicate values in username field of articles table I get only 1 row in result.
My page

If you want to show each user, then I think you should be aggregating by the user. In fact, you should be aggregating by every column in the SELECT that is not an argument to an aggregation function.
This may do what you want:
SELECT a.aid, a.username, a.competition, a.path, a.category, a.title,
Sum(z.zvotes) AS votessum
FROM articles a LEFT JOIN
zvotes z
on a.aid = z.aid
WHERE a.category = '$cat' AND a.competition = '$comp'
GROUP BY a.aid, a.username, a.competition, a.path, a.category, a.title
ORDER BY votessum";

Related

SQL Query duplicating values even using Distinct

My query seems to be duplicating the values that are being displayed.
I don't understand why, I have 5 tables
products with an id and category (4 of them), then each category is related to another table where the product_name, price is, then each one of these tables is related to the table called stock, stock is the one where price is.
`
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php
$conn = mysqli_connect("localhost:3307", "root", "", "db_login");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT products.id, products.category, hygiene.product_name, hygiene.price, stock.quantity
FROM products
LEFT JOIN hygiene ON products.id = hygiene.product_id
LEFT JOIN stock ON hygiene.product_id = stock.item_id
WHERE products.category = 'Hygiene'
UNION
SELECT products.id, products.category, food.product_name, food.price, stock.quantity
FROM products
LEFT JOIN food ON products.id = food.product_id
LEFT JOIN stock ON food.product_id = stock.item_id
WHERE products.category = 'Food'
UNION
SELECT products.id, products.category, toys.product_name, toys.price, stock.quantity
FROM products
LEFT JOIN toys ON products.id = toys.product_id
LEFT JOIN stock ON toys.product_id = stock.item_id
WHERE products.category = 'Toys'
UNION
SELECT products.id, products.category, clothes.product_name, clothes.price, stock.quantity
FROM products
LEFT JOIN clothes ON products.id = clothes.product_id
LEFT JOIN stock ON clothes.product_id = stock.item_id
WHERE products.category = 'Clothes'";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result)) {
$product_name = isset($row['product_name']) ? $row['product_name'] : '';
$quantity = isset($row['quantity']) ? $row['quantity'] : '';
$price = isset($row['price']) ? $row['price'] : '';
echo "<tr>";
echo "<form name='update' action='update_stock.php' method='post'>";
echo "<td><input type='text' name='product_name' value='".$row ['product_name']."'></td>";
echo "<td><input type='text' class='stock--update--num' name='quantity' value='".$row['quantity']."'></td>";
echo "<td><input type='text' class='stock--update--num' name='price' value='".$row['price']. "€"."'></td>";
echo "<td><input type='submit' name='update' value='Update'></td>";
echo "</form>";
echo "</tr>";
}
?>
</table>`
I wanted for it to display each item only once with the correct quantity and price.
Other code I tried:
`$conn = mysqli_connect("localhost:3307", "root", "", "db_login");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT products.*, hygiene.product_id, hygiene.product_name, hygiene.price, hygiene.image_path, stock.quantity
FROM products
LEFT JOIN hygiene ON products.id = hygiene.product_id
LEFT JOIN stock ON hygiene.product_id = stock.item_id
WHERE products.category = 'Hygiene'
UNION
SELECT DISTINCT products.*, food.product_id, food.product_name, food.price, food.image_path, stock.quantity
FROM products
LEFT JOIN food ON products.id = food.product_id
LEFT JOIN stock ON food.product_id = stock.item_id
WHERE products.category = 'Food'
UNION
SELECT DISTINCT products.*, toys.product_id, toys.product_name, toys.price, toys.image_path, stock.quantity
FROM products
LEFT JOIN toys ON products.id = toys.product_id
LEFT JOIN stock ON toys.product_id = stock.item_id
WHERE products.category = 'Toys'
UNION
SELECT DISTINCT products.*, clothes.product_id, clothes.product_name, clothes.price, clothes.image_path, stock.quantity
FROM products
LEFT JOIN clothes ON products.id = clothes.product_id
LEFT JOIN stock ON clothes.product_id = stock.item_id
WHERE products.category = 'Clothes'";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<form name='update' action='update_stock.php' method='post'>";
$product_name = isset($row['product_name']) ? $row['product_name'] : '';
$quantity = isset($row['quantity']) ? $row['quantity'] : '';
$price = isset($row['price']) ? $row['price'] : '';
echo "<td><input type='text' name='product_name' value='".$product_name."'></td>";
echo "<td><input type='text' class='stock--update--num' name='quantity' value='".$quantity."'></td>";
echo "<td><input type='text' class='stock--update--num' name='price' value='".$price. "€"."'></td>";
echo "<td><input type='submit' name='update' value='Update'></td>";
echo "</form>";
echo "</tr>";
}`
Wrap all your UNION queries in one single DISTINCT query:
SELECT DISTINCT * FROM(
SELECT...
UNION
SELECT....
UNION
SELECT...
)
But looking at your query closely, you are querying for more columns than you are fetching - I don't think product_ids would make a unique result.

MySQL database selecting athlete data requires position

I am selecting data from a database and displaying it on the page.
One useful value which is not saved in the database is the $position.
It is useful to show the position of each athlete, here as shown I just display an increasing $i value.
The code shown below ORDERS BY run points. The problem is when sorting the list say by something else such as ORDER BY athlete ASC the position allocated to each athlete doesn't move with the athlete.
$selectproduct = mysqli_query($link, "SELECT `athlete`,`reference`,SUM(`Run Points`) AS 'Run Points',COUNT(`eventID`) AS 'num_runs',`Volunteer Points`,`location`,`Gender pos` FROM `Events` WHERE `Gender`='$Gender' AND `location`='$location' GROUP BY `reference` ORDER BY `Run Points` DESC");
while ($rowGetDetails = mysqli_fetch_array($selectproduct)){
$reference=$rowGetDetails['reference'];
$athlete=$rowGetDetails['athlete'];
$points=$rowGetDetails['Run Points'];
$num_runs=$rowGetDetails['num_runs'];
$position=$i;
echo '<tr>';
echo'<td>';
echo $athlete;
echo '</td>';
echo'<td>';
echo $num_runs;
echo '</td>';
echo'<td>';
echo $points;
echo '</td>';
echo '</tr>';
$i=$i+1;
}
When sorting by something else such as athlete ASC in the $selectproduct it still gives $postition as number 1 for the first athlete in the list with a name beginning with A when that is not the athlete with the most points.
There are other options for $selectproduct such as sorting by athlete ASC as below:
$selectproduct = mysqli_query($link, "SELECT `athlete`,`reference`,SUM(`Run Points`) AS 'Run Points',COUNT(`eventID`) AS 'num_runs',`Volunteer Points`,`location`,`Gender pos` FROM `Events` WHERE `Gender`='$Gender' AND `location`='$location' GROUP BY `barcode` ORDER BY `athlete` ASC"
Just assign $i value outside the loop;
$selectproduct = mysqli_query($link, "SELECT `athlete`,`reference`,SUM(`Run Points`) AS 'Run Points',COUNT(`eventID`) AS 'num_runs',`Volunteer Points`,`location`,`Gender pos` FROM `Events_08052017_withdate` WHERE `Gender`='$Gender' AND `location`='$location' GROUP BY `reference` ORDER BY `Run Points` DESC");
$i = 1;
while ($rowGetDetails = mysqli_fetch_array($selectproduct)){
$reference=$rowGetDetails['reference'];
$athlete=$rowGetDetails['athlete'];
$points=$rowGetDetails['Run Points'];
$num_runs=$rowGetDetails['num_runs'];
$position=$i;
echo '<tr>';
echo'<td>';
echo $athlete;
echo '</a>';
echo '</td>';
echo'<td>';
echo $num_runs;
echo '</td>';
echo'<td>';
echo $points;
echo '</td>';
echo '</tr>';
$i=$i+1;
}
try query something like this may be its works for you
SET #rank=0;
SELECT #rank := #rank + 1 AS ranking, t.avg, t.name
FROM(SELECT avg(students_signatures.score) as avg, students.name as name
FROM alumnos_materia
JOIN (SELECT #rownum := 0) r
left JOIN students ON students.id=students_signatures.id_student
GROUP BY students.name order by avg DESC) t

How to count rows of another table in a while loop [PHP] [SQL]

I have a table which shows cities in florida.
I have another table with activities for each city, these tables are connected with a foreign key.
I have a while loop which lists the cities with an image and its population, what i want to do is to make the while loop display the amount of activities i have added in the database for that city.
http://imgur.com/a/w3Ixn see image on top
^
I want the X to be the number of rows in the activities table sharing the city_id with the city.
http://imgur.com/a/w3Ixn image on bottom, to make it easier to understand
I have made a while loop of the first table, but want to add number of activities**(table on right)** for that city inside the while loop and I am wondering how i can to that, this is how my current code looks like
<?php
include "kobling.php";
$sql = "SELECT * FROM city";
$resultat = $kobling->query($sql);
while ($rad=$resultat->fetch_assoc()) {
$navn = $rad["navn"];
$bilde = $rad["bilde"];
$befolkning = $rad["befolkning"];
echo '<div class="byeramme">';
echo "<img src='$bilde' align='left' width='500px' height='250px'";
echo "<p align='center'> $navn</p>";
echo "<p align='center'>Antall bosatte:&nbsp $befolkning</p>";
echo "<p align='center'> Antall attraksjoner:&nbsp X</p>";
echo '</div>';
}
?>
if you need only the count of activitis you could do it with a single query eg:
$sql = "SELECT city.navn as navn
, city.bilde as bilde
, city.befolkning as befolkning
, count(*) as my_count
FROM city
LEFT JOIN attrakjoner on city.city_id = activities.city_city_id
GROUP BY city.city_id ";
then in my_count you have the number of activities
<?php
include "kobling.php";
$sql = "SELECT city.navn as navn
, city.bilde as bilde
, city.befolkning as befolkning
, count(*) as my_count
FROM city
LEFT JOIN attrakjoner on city.city_id = activities.city_city_id
GROUP BY city.id";
$resultat = $kobling->query($sql);
while ($rad=$resultat->fetch_assoc()) {
$navn = $rad["navn"];
$bilde = $rad["bilde"];
$befolkning = $rad["befolkning"];
$myCount = $rad["my_count"];
echo '<div class="byeramme">';
echo "<img src='$bilde' align='left' width='500px' height='250px'";
echo "<p align='center'> $navn</p>";
echo "<p align='center'>Antall bosatte:&nbsp $befolkning</p>";
echo "<p align='center'> Antall attraksjoner:&nbsp $myCount</p>";
echo '</div>';
}
?>

COUNT a number of database rows affiliated with an id

I'm creating a forum and right now I am trying to figure out how to count the number of replies in a topic. I am wanting to count the number of rows per topic_id #. So if there is a topic id of 5 and there are 10 rows in my database of topic_id #5, I want the it to count and output 10.
I tried to structure my query like this
$query2 = mysqli_query($con,"SELECT t.*, COUNT(p.topic_id) AS tid2 FROM forum_topics AS t, forum_posts AS p ORDER BY topic_reply_date DESC")
All this did however was mess up my original query which was this...
$query2 = mysqli_query($con,"SELECT * FROM forum_topics WHERE `category_id` ='".$cid."' ORDER BY topic_reply_date DESC")
And it is now only showing 1 topic rather than the 15 I have and it it outputting a very large Count figure of 406.
How can I get the following code to only count the topic_id associated with the topic that is being outputted and still allow for all of my topics to be outputted?
$query2 = mysqli_query($con,"SELECT t.*, COUNT(p.topic_id) AS tid2 FROM forum_topics AS t, forum_posts AS p ORDER BY topic_reply_date DESC")
or die ("Query2 failed: %s\n".($query2->error));
$numrows2 = mysqli_num_rows($query2);
//if ( false===$query2 ) {
// die(' Query2 failed: ' . htmlspecialchars($query2->error));
//}
if($numrows2 > 0){
$topics .= "<table width='100%' style='border-collapse: collapse;'>";
//Change link once discussion page is made
$topics .= "<tr><td colspan='3'><a href='discussions.php'>Return to Discussion Index</a>".$logged."<hr /></td></tr>";
$topics .= "<tr style='background-color: #dddddd;'><td>Topic Title</td><td width='65' align='center'>Replies</td><td width='65'
align='center'>Views</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
while($row = mysqli_fetch_assoc($query2)){
$tid = $row['id'];
$title = $row['topic_title'];
$views = $row['topic_views'];
$replies = $row['tid2'];
$date = $row['topic_date'];
$creator = $row['topic_creator'];
$topics .= "<tr><td><a href='forum_view_topic.php?cid=".$cid."&tid=".$tid."'>".$title."</a><br /><span class='post_info'>Posted
by: ".$creator." on ".$date."</span></td><td align='cener'>".$replies."</td><td align='center'>".$views."</td></tr>";
$topics .= "<tr><td colspan='3'><hr /></td></tr>";
}
Use GROUP BY clause (tutorial):
SELECT t.*, COUNT(p.topic_id) AS tid2
FROM forum_topics AS t JOIN forum_posts AS p on t.id = p.topic_id
GROUP BY t.id
Also note that OUTER JOIN is used in my example (instead of CROSS JOIN in your example).

MySQL Insert no longer works

I am working in wordpress and below is my code which has a form tag in a for loop and the submit button. When submit button is clicked an insert operation needs to be performed but the insert function no more works. May be it's not able to pick the id ... help will be much appreciated thanks..
PHP Code
$sql = "SELECT 1user.username, 1user.competition, 1user.path, Sum(votes.votes) AS votessum FROM 1user LEFT JOIN votes on 1user.uid=votes.uid GROUP BY 1user.username, 1user.competition";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ) {
echo '<form action="" method="post">';
echo "<img src='$result->path' width='150' height='150' >" . '<br><br>';
echo "<input name='id' type='hidden' value='$result->uid'>";
echo "<input name='comp' type='hidden' value='$result->competition'>";
echo $result->username.'<br>';
echo $result->votessum.'<br>';
echo "<input style='margin-bottom:30px;' value='vote' name='submit' type='submit'/></form>";
}
if(isset($_POST['submit'])){
global $wpdb;
$votes = 1;
$competition = $_POST['comp'];
$uid = $_POST['id'];
//$uid = get_current_user_id();
echo 'id of image = '.$_POST['id'];
echo '<br>'.'competition is'.$_POST['comp'];
if($wpdb->insert(
'votes',
array(
'votes' => $votes,
'competition' => $competition,
'uid' => $uid
)
) == false)
wp_die('Database Insertion failed');
else
echo 'Database insertion successful<p />';
}
yes it is solved found the solution 1user.uid field was missing from the select query .. thanks everybody
Correct select query
$sql = "SELECT 1user.uid, 1user.username, 1user.competition, 1user.path, Sum(votes.votes) AS votessum FROM 1user LEFT JOIN votes on 1user.uid=votes.uid GROUP BY 1user.username, 1user.competition";

Categories