I have a really simple question, but unfortunately I can't figure it out myself. I have a list of 12 players which all have an (unique)ID, rating, attribute1 and attribute4. I ONLY want the row of the player with the highest rating followed by attribute1 and then attribute4. So it will first have to sort on rating, if there are 2 with rating 84, SQL will check for attribute1 etc. This is my code.
$sql = "SELECT * FROM `players_db` WHERE `id` = $player[0] OR `id` = $player[1] OR `id` = $player[2] OR `id` = $player[3] OR `id` = $player[4] OR `id` = $player[5] OR `id` = $player[6] OR `id` = $player[7] OR `id` = $player[8] OR `id` = $player[9] OR `id` = $player[10] OR `id` = $player[11] ORDER BY `rating` DESC , `attribute1` DESC, `attribute4` DESC";
$result = $conn->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['rating'];
echo '<br>';
}
I can't figure it out how to go further, as I already tryed
SELECT MAX('rating') FROM players_db WHERE ...
But then it only gets the rating of the highest player, so how can I get the whole row of the player with the highest rating followed by attribute1 and attribute4?
I hope someone can help me out! Thanks!
This query will give the record corresponding to the player with the highest rating. In the event of a tie, attribute1 and attribute4 will be used to break the tie, in that order.
SELECT *
FROM players_db
ORDER BY rating DESC, attribute1 DESC, attribute4 DESC
LIMIT 1
Use LIMIT , So that first it will sort the records by rating, then it will select the first row from top AS used LIMIT 1:
$sql = "SELECT * FROM `players_db` WHERE `id` = $player[0] OR `id` = $player[1] OR `id` = $player[2] OR `id` = $player[3] OR `id` = $player[4] OR `id` = $player[5] OR `id` = $player[6] OR `id` = $player[7] OR `id` = $player[8] OR `id` = $player[9] OR `id` = $player[10] OR `id` = $player[11] ORDER BY `rating` DESC , `attribute1` DESC, `attribute4` DESC LIMIT 1";
$result = $conn->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['rating'];
echo '<br>';
}
Related
I am trying to order in while from higger count of clicks to the lower and I am a bit of lost so I decided to ask the qustion here.
My code :
$stmt = $db->query("SELECT DISTINCT `country` FROM `entries` ORDER by `id` ASC");
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch()) {
$clicks = $db->query("SELECT `id` FROM `entries` WHERE `country` LIKE '{$row['country']}'")->rowCount();
$conversations = $db->query("SELECT `id` FROM `conversations` WHERE `country` LIKE '{$row['country']}' AND `link_id` = '{$id}'")->rowCount();
}
I want the foreach give me results from highest count of $clicks to the lowest.
Any ideas what can I do ?
You can do this query entirely in SQL with something like this (depending on SQL dialect):
$countries = $db->query("SELECT `country`, count(1) AS clicks FROM `entries` GROUP BY `country` ORDER BY clicks DESC");
foreach ($countries as $country) {
echo "${country['country']} has ${country['clicks']} clicks. ";
}
put number of clicks in an array as below :
$clicks[] = $db->query("SELECT `id` FROM `entries` WHERE `country` LIKE '{$row['country']}'")->rowCount();
then you can simply sort the array by rsort php function as below :
echo rsort($clicks);
I have 2 tables. The first one is messages and the second is room. msg_id from messages table is the same as id from room table. What I'm doing is selecting all msg_id and for each of them I wanna run a query that deletes all rooms that their ids dont match with msg_id:
My code:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
while($row = mysql_fetch_array( $result )) {
$me = $row[0]; //$me as a string
$int = (int)$me;//transform $me's value to int
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%" . $int . "%'");}
The $result2 query will delete all entries from room table, no matter the value of $int variable. That means that the check is not working. If I change the $result2 to this i.e.:
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT LIKE '%86%'");
all entries will be Deleted except the room entry with id = 86 (it works fine)
The basic plan is that I must keep all room entries that match their id with msg_id .
DELETE FROM `room` WHERE `id` NOT IN (SELECT `msg_id` FROM `messages`)
if you can't use subquery you can try:
$result = mysql_query("SELECT `msg_id` FROM `messages`");
$ids = [];
while($row = mysql_fetch_array($result)) {
$ids[] = (int) $row[0];
}
$result2 = mysql_query("DELETE FROM `room` WHERE `id` NOT IN (" . implode(',', $ids) . "));
and PLS don't USE mysql_query it is DEPRECATED
Could you use a subquery?
DELETE FROM ROOM WHERE id not in(SELECT msg_id FROM messages);
Try this query,
delete from 'room' where 'id' not in(select 'msg_id' from 'messages');
if it don't work for you, you can try NOT EQUAL TO query
delete from 'room' where 'id' <>(select 'msg_id' from 'messages');
Hi guys i'm quite new to PHP but I'm currently working on this site and I want it to check if the total_online_time for the user is 0 or less then it should execute the script which will create a room for the user. However after trying with this script the .php page won't load.
http://pastebin.com/XDLhFvtE
<?php
$getStats = mysql_query("SELECT total_online_time FROM `users` WHERE id = '".$_SESSION['user']['id']."'");
if ($getStats > 0)
$getRoomKit = mysql_fetch_assoc(mysql_query("SELECT * FROM room_starterkit ORDER BY RAND() LIMIT 1"));
$getRoom = mysql_fetch_assoc(mysql_query("SELECT * FROM `rooms` WHERE id = '".$randomRoomID['id']."' LIMIT 1"));
$welcomeMessage = "Welcome " . $_SESSION['user']['username'];
mysql_query("INSERT INTO `rooms` (caption,owner_id,description,model_name,wallpaper,floor) VALUES ('".$welcomeMessage."', '".$_SESSION['user']['id']."', 'Welcome to Hablore', '".$getRoomKit['room_Model']."', '".$getRoomKit['room_Wallpaper']."', '".$getRoomKit['room_Floor']."') ");
$theRoomID = mysql_fetch_assoc(mysql_query("SELECT id FROM `rooms` ORDER BY `id` DESC LIMIT 1"));
mysql_query("UPDATE `users` SET `home_room` = '".$theRoomID['id']."' WHERE `id` = '".$_SESSION['user']['id']."'");
$getRoomItems = mysql_query("SELECT * FROM room_itemkits WHERE roomKit = '".$getRoomKit['id']."'");
while($CurItem = mysql_fetch_assoc($getItems)){
mysql_query("INSERT INTO `items` (user_id, room_id, base_item, extra_data, x, y, z, rot, wall_pos) VALUES ('".$_SESSION['user']['id']."','".$lastRoomID['id']."','".$CurItem['base_item']."','".$CurItem['extra_data']."','".$CurItem['x']."','".$CurItem['y']."','".$CurItem['z']."','".$CurItem['rot']."','".$CurItem['wall_pos']."')");
}
}
?>
I'm trying to use the result of one query as part of a WHERE in a second query. I'm not sure how to best approach this, any assistance is greatly appreciated:
First Query:
$result = mysql_query("SELECT `keyword` FROM `history` ORDER BY `last_update` ASC LIMIT 1 ");
while($row = mysql_fetch_array($result))
$keyword = $row['keyword'];
Second Query
$result = mysql_query("SELECT `id` FROM `data_store` WHERE `keyword`= [result from my first query] ORDER BY `id` DESC LIMIT 1");
while($row = mysql_fetch_array($result))
$id = $row['id'];
For clarification, keyword.data_store relates to keyword.history
Use subquery
$result = mysql_query("
SELECT `id`
FROM `data_store`
WHERE `keyword` = (SELECT `keyword`
FROM `history`
ORDER BY `last_update` ASC
LIMIT 1)
ORDER BY `id` DESC");
while($row = mysql_fetch_array($result))
$id = $row['id'];
(Stripped out PHP aspects because it is irrelevant)
SELECT `id` FROM `data_store` WHERE
`keyword` IN (
SELECT `keyword` FROM `history` ORDER BY `last_update` ASC LIMIT 1
)
ORDER BY `id` DESC LIMIT 1
$result = mysql_query("SELECT `id`
FROM `data_store`
WHERE `keyword` = (
SELECT `keyword`
FROM `history`
ORDER BY `last_update` ASC
LIMIT 1 )
ORDER BY `id` DESC LIMIT 1");
$activeQuery = mysql_query("SELECT count(`status`) AS `active` FROM `assignments` WHERE `user` = $user_id AND `status` = 0");
$active = mysql_fetch_assoc($activeQuery);
$failedQuery = mysql_query("SELECT count(`status`) AS `failed` FROM `assignments` WHERE `user` = $user_id AND `status` = 1");
$failed = mysql_fetch_assoc($failedQuery);
$completedQuery = mysql_query("SELECT count(`status`) AS `completed` FROM `assignments` WHERE `user` = $user_id AND `status` = 2");
$completed = mysql_fetch_assoc($completedQuery);
There has to be a better way to do that, right? I don't know how much I need to elaborate as you can see what I'm trying to do, but is there any way to do all of that in one query? I need to be able to output the active, failed, and completed assignments, preferably in one query.
You can try something like this query
SELECT Status , COUNT(*) StatusCount
FROM assignments
WHERE Status IN (0, 1, 2)
AND User = $user_id
GROUP BY Status
Try this
$activeQuery = SELECT status, count(status) as "status count" FROM `assignments` WHERE `user` = $user_id GROUP BY `status`
edit: added group by
Instead of doing them individually you could use the following single SQL statement
SELECT count(*), `status`
FROM `assignments`
WHERE `user` = $user_id
AND `status` in (0,1,2)
GROUP BY `status`
ORDER BY `status`
The loop around the result set to extract the results.
SELECT
(SELECT COUNT(*) FROM `assignments` WHERE `user` = $user_id AND `status` = 0) AS active,
(SELECT COUNT(*) FROM `assignments` WHERE `user` = $user_id AND `status` = 1) AS failed,
(SELECT COUNT(*) FROM `assignments` WHERE `user` = $user_id AND `status` = 2) AS completed,
FROM `assignments`
GROUP BY active, failed, completed
Haven't checked the markup, but this is near or near enough.
Use the GROUP BY to get it in one query, but on separate rows.
$query = mysql_query("SELECT `status`, count(*) AS `num` FROM `assignments` WHERE `user` = $user_id AND `status` in (0,1,2) GROUP BY `status` ORDER BY `status` ASC");
$active_count = 0;
$failed_count = 0;
$completed_count = 0;
while ($array = mysql_fetch_assoc($query))
{
if ($array['status'] == 0)
$active_count = $array['num'];
else if ($array['status'] == 1)
$failed_count = $array['num'];
else if ($array['status'] == 2)
$completed_count = $array['num'];
}
When I have the option, I'm in the habit of using prepared statement(s) to help protect against sql-injection protection and for efficiency (requires using mysqli).
But if this is not an option, then
SELECT
CASE `status`
WHEN 0 THEN `active`
WHEN 1 THEN `failed`
WHEN 2 THEN `completed`
ELSE `unknown`
END
AS `statuslabel`,
COUNT(status)
AS `statuscount`
FROM `assignments`
WHERE `user` = $escaped_user_id
GROUP BY `statuslabel`
ORDER BY `statuslabel`
Note the use of the $escaped_user_id, which would be created beforehand:
$escaped_user_id = mysql_real_escape_string($user_id);