select data from multiple table using php union - php

anyone can help me how to select from multiple MySQL table and sort by the gameplayed limit 15 using php?
<?php
//$query = "SELECT id, gamename, gameplayed FROM action, adventure, augur, beauty, chess, joke, mmorpg, multiplayer, platform, puzzle, racing, shooting, sport, stratergy WHERE id = :id";
$query = '
SELECT id, gamename, gameplayed FROM((
SELECT id, gamename, gameplayed
FROM action
ORDER BY gameplayed
DESC LIMIT 15
) UNION (
SELECT id, gamename, gameplayed
FROM adventure
ORDER BY gameplayed
DESC LIMIT 15
))as t ORDER BY gameplayed';
$query_params = array(':id' => '1');
//$query = "SELECT id, gamename FROM action, adventure, augur, beauty, chess, joke, mmorpg, multiplayer, platform, puzzle, racing, shooting, sport, stratergy ORDER BY gameplayed DESC LIMIT 15";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
foreach($rows as $row):
echo $rows['t'];
endforeach;
unset($row);
?>
i search google found the solution is using union , but i'm keep getting error "undefine index t"

Try changing your SQL query to this
SELECT id, gamename, gameplayed
FROM action
LIMIT 15
UNION
SELECT id, gamename, gameplayed
FROM adventure
ORDER BY gameplayed DESC
LIMIT 15
ORDER BY gameplayed

It don't see a field named "t" in your select query? Try to var_dump() $rows, then you may see whats going wrong.
What you are doing is trying to select a table alias. You cannot select them, only select fields.
Your result should now look at the beginning of the subarrays of your array $rows like the elements of the first table and the second, mixed, following the order in the gameplayed column.

You have tried to make all the results from the UNION select as an alias 't' ? It won't work, you have to use them one by one i.e.:
...UNION (
SELECT t.id as 'tid', t.gamename as 'tgamename', t.gameplayed as 'tgameplayed'
FROM adventure AS t
...
$row['tid']; $row['tgamename']; $row['tgameplayed']

Related

Is it possible for MySQL to order by a certain column but if a value of another column is X put it at the end?

I have 3 tables, users, warnings, warningnames.
The content of the tables is as follows:
Users(simplified):
u_id, username, password, rank
Warnings:
w_id, wn_id, u_reporter_id, u_reported_id
Warningnames:
wn_id, warningInfo, warningPoints
I have a loop in PHP which gets me all users with a simple query:
SELECT *
FROM users
WHERE u_id < :startcount
ORDER BY u_id DESC
LIMIT :perpage
How do I make a query which gets all users but puts the users with the most warnings at the top and the users with rank 0 at the bottom?
The query I have so far is:
SELECT users.*, COUNT(warnings.w_id) as warningCount
FROM users
LEFT JOIN warnings
ON users.u_id = u_reported_id
WHERE u_id < :startcount
ORDER BY warningCount DESC
LIMIT :perpage
But that doesn't return what I want, it just returns the warningCount of all users in a single query that fit the WHERE statement.
Example fiddle:
http://sqlfiddle.com/#!9/ec6c2d/6
Sample PHP code:
<?php
$query = $this->handler->prepare('SELECT * FROM users WHERE u_id < :startcount ORDER BY u_id DESC LIMIT :perpage');
try{
$query->execute([
':startcount' => 25,
':perpage' => 25
]);
}
catch(PDOException $e){
echo $e->getMessage();
}
while($fetch = $query->fetch(PDO::FETCH_ASSOC)){
echo $fetch['username'] . '<br />';
}
?>
How can I correct this and order by a warningCount column but put all users with rank 0 at the end?
If I understand it, you want to order by warning count, but ignore users with rank = 0 on that query ??
if that's the case, what you need is group by, and then order by using case when,
here's what I came up :
SELECT users.*, COUNT(warnings.w_id) as warningCount
FROM users
LEFT JOIN warnings
ON users.u_id = u_reported_id
WHERE u_id < 10
group by users.u_id
ORDER BY
case when rank = 0
then 0
else COUNT(warnings.w_id) + 1
end
DESC
LIMIT 25
I add +1 on order by to make sure, users with rank 0 is always at the bottom.
Edit :
I Add the where startCount and the limit to the query
The SQL Fiddle was helpful in explaining you situation, and I think you're looking for GROUP BY. Also note that you can order by multiple fields.
I've edited your fiddle slightly: https://www.db-fiddle.com/f/av9d6ordS9XVpavwzZUs8W/0
SELECT u.*, COUNT(w.wn_id) warnings
FROM users u
INNER JOIN warnings w ON u.u_id = w.u_reported_id
GROUP BY u.u_id
ORDER BY warnings DESC, u.rank DESC
# LIMIT 10

MySQLi : How to sort to make a ladder

I'm setting up a website based on server voting's. I would like to sort servers votes with mysqli and give them a rank, per example:
1: 88 votes Server1
2: 54 votes Server2
3:34 votes Server3...
I already have my servers and votes in my database, but I can't find the solution to sort them and to give them a rank.
It is like:
{rank} : {number of server's vote} {server name}
I already tried this:
$totalserv = $database->prepare("SELECT COUNT(*) FROM `servers` ");
$votes = $database->query("SELECT `votes` FROM `servers` ORDER BY votes ASC");
But I don't understand how to make $vote a list and attribute it a rank.
You can try this, change DESC and ASC accordingly
SELECT * FROM `table` ORDER BY LEFT(`votes`,2) DESC;
Your query
$votes = $database->query("SELECT `votes` FROM `servers` ORDER BY LEFT(`votes`,2) ASC");

Get total points of user in MySQL Table with PHP

I have a MySQL table with the columns "user" and "warningpoints" for each warning as you can see in the table above. How can I get the user which has the most warningpoints in total in PHP?
You can use GROUP BY and ORDER BY and LIMIT:
SELECT t.user,sum(t.warningPoints) as sum_points
FROM YourTable t
GROUP BY t.user
ORDER BY sum_points DESC
LIMIT 1;
Or if there is only one record per person, no need to group :
SELECT t.user,t.warningPoints
FROM YourTable t
ORDER BY t.warningPoints DESC
LIMIT 1;
You can simply add below statements in your php code.
$sql = "SELECT User, Max(warningpoints) AS MaxWarningpoints FROM MyGuests GROUP BY User";
$result = $conn->query($sql);

How can I order by count in mysql when the count need data to calculate from this select statement?

Look at my code, I want the select statement order by the count percentage after I fetch the data from this select statement, obviously, it's not logical. What can I do? Help, appreciate.
<?php
//myslq connection code, remove it because it's not relate to this question
$stm =$db->prepare("SELECT id ,term_count, COUNT(user_id) as count FROM sign WHERE term IN (:term_0,:term_1) GROUP BY user_id ORDER by count DESC");
//trying replace order by count with $combine_count, but it's wrong
$term_0="$term[0]";
$term_1="$term[1]";
$stm->bindParam(":term_0", $term_0);
$stm->bindParam(":term_1", $term_1);
stm->execute();
$rows = $stm->fetchALL(PDO::FETCH_ASSOC);
foreach ($rows as rows) {
$count=$rows['count'];
$term_count_number=$rows['term_count'];
$count_percentage=round(($count/$count_user_diff)*100);
$count_key_match=round(($count/$term_count_number)*100);
$combine_count=round(($count_percentage+$count_key_match)/2);
//issue is here, I want the select statement order by $combine_count
}
?>
SELECT id ,term_count, COUNT(user_id) as `count`
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY user_id
ORDER by `count` DESC");
Since "count" is a function, it would be better to put backtics around the non-function "counts", as done above.
GROUP BY should list the field not aggregated. Otherwise, it does not know which id and term_count to fetch. So, depending on what you are looking for,
Either do
SELECT user_id, COUNT(*) as `count` -- I changed this line
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY user_id
ORDER by `count` DESC");
or do
SELECT id ,term_count, COUNT(*) as `count`
FROM sign
WHERE term IN (:term_0,:term_1)
GROUP BY id ,term_count -- I changed this line
ORDER by `count` DESC");
SQL Syntax Logic
SELECT column1, count(column1) AS amount
FROM table_name
GROUP BY column1
ORDER BY amount DESC
LIMIT 12

Get top 5 most popular items in mysql database?

I have a database that looks something like this:
user_id photo_id
1 1
1 2
1 3
1 4
2 5
2 6
I want to get a list of the most popular users from it. Like this:
Popular Users: 1 (4) & 2 (2)
How would I go about doing that in mysql in PHP?
Thanks, Coulton
PS: I do know much about mysql commands so you don't have to dumb it down. Thanks!
The basic query would be:
select user_id, count(user_id) as cnt
from yourtable
group by user_id
order by cnt desc
To display the results, something like:
$results = array()
while($row = mysql_fetch_assoc($query_result)) {
$results[] = "{$row['user_id']} ({$row['cnt']})"
// repeat for however many results you want
}
echo "Popular user: ", implode(" & ", $results);
select user_id, count(user_id) as count from table order by count desc group by user_id
something like that anyway...
This can be accomplished using only SQL commands. Here's what I'd do:
SELECT user_id, count(user_id) uid_count
FROM <<table>>
GROUP BY user_id
ORDER BY uid_count DESC
LIMIT 5;
GROUP BY collects rows that all have the same user_id, and ORDER BY ... DESC sorts the results in descending order, so the first rows represent the most popular users. LIMIT gives you the top 5 results.
The database query will look something like this:
select user_id, count(photo_id) as c
from table group by user_id
order by c desc limit 5;
In PHP, it would look something like this:
$sql = 'select user_id, count(photo_id) as c from table group by user_id order by c desc limit 5';
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['user_id'];
echo $row['c'];
}
SELECT COUNT(a.category_id) as cnt,b.category,b.image FROM bookings as a
INNER JOIN service_category as b ON a.category_id=b.category_id
GROUP BY a.category_id ORDER BY cnt DESC LIMIT 6

Categories