This is going to be a confusing one.. I'll try to explain it and provide as much information as possible. Basically, what I have is a website where people can upload the amount of kills they get in a game. What I'd like to do, is display people's combined, confirmed kills on a leaderboard.. This is proving harder than I expected (LOL).
Here's what my database looks like:
submission is the unique id of the entry.
usergt is the user's gamertag.
image is not important.
userkilled is the person they have killed.
status is the status of the confirmation of the kill.
conftotal is the total kills that we confirmed from the image (eg. entry 5 recorded 24 kills).
submitted is simply a unix timestamp of the submission date and time.
Here's my PHP on the page itself:
<?php
function getKills($gamertag) {
$conn = new mysqli("localhost", "rpsanet_seals", "k_,2N2Xbu}mr", "rpsanet_seals");
if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);}
$sql = "SELECT conftotal FROM kills WHERE usergt='" . $gamertag . "'";
$result = $conn->query($sql);
$ctotalklls = 0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$ctotalklls = $ctotalklls + $row["conftotal"];
}
} else {
$ctotalklls = 0;
}
return $ctotalklls;
$conn->close();
}
?>
<div class="mykills_content">
<table class="mykills_table">
<tr>
<th class="mk_first">Avatar</th>
<th>Gamertag</th>
<th>Latest Victim</th>
<th class="mk_last">Total Kills</th>
</tr>
<?php
$conn = new mysqli("localhost", "rpsanet_seals", "k_,2N2Xbu}mr", "rpsanet_seals");
if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);}
$sql = "SELECT *, COUNT(*) AS magnitude
FROM kills
WHERE status='confirmed'
GROUP BY usergt
ORDER BY magnitude ASC
LIMIT 5";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '
<tr>
<td class="mykills_submission" data-submission="' . $row["submission"] . '">
<div class="mykills_avatar">
<img src="https://avatar-ssl.xboxlive.com/avatar/' . $row["usergt"] . '/avatarpic-l.png" class="mykills_victim_avatar" draggable="false" />
</div>
</td>
<td>
' . $row["usergt"] . '
</td>
<td>
' . $row["userkilled"] . '
</td>
<td>
' . getKills($row["usergt"]) . '
</td>
</tr>
';
}
echo '</table>';
} else {
echo '</table><div class="fw-nokills">You have not submitted any kills yet.</div>';
}
$conn->close();
?>
</div>
</div>
and this is what it looks like on the page:
I have no idea what I've done wrong or how to fix it. As you can see, the order is incorrect. It should go CheapApples12, then KILLER C00KIE X, then ancrobbo97.
If anything else is not clear, or any other info is needed, just comment and I'll get that to anyone as soon as I can..
I appreciate any help in advance :)
IMPORTANT INFO: The "Total Kills" that are being shown in the screenshot above are being generated from the getKills() function, not the database query result.
Try this simple one liner use sum(conftotal) and use order by sum(conftotal)
SELECT *,sum(conftotal) as totalkills FROM kills WHERE status='confirmed' GROUP BY usergt ORDER BY totalkills desc
SELECT x.avatar, x.gamertag, x.magnitude AS magnitude FROM
( SELECT avatar,gamertag, COUNT(*) AS magnitude
FROM kills
WHERE status='confirmed'
GROUP BY usergt
LIMIT 5
) AS x
ORDER BY magnitude ASC
I can't test what I wrote, but I think you can get the logic out of it.
Using subqueries is slower, but they are quite powerfull.
As I understand you want a descending order to be displayed based on the TotalKills count, please try using the following query.
"SELECT *, COUNT(ref_column_name) AS magnitude
FROM kills
WHERE status='confirmed'
GROUP BY usergt
ORDER BY magnitude desc"
Related
I'm trying to create a leaderboard using a score table from Mysql.
I only use "name" and "score" from my score table.
I can display my leaderboard ordered by best score but can't display the rank with it.
Here is my php file to get datas:
// Connect to server and select database.
$con = mysqli_connect($host, $db_username, $db_password, $db_name);
// Retrieve data from database
$sql = "SELECT *
FROM scores
ORDER BY score DESC
LIMIT 10"; // The 'LIMIT 10' part will only read 10 scores. Feel free to change this value
$result = mysqli_query($con, $sql);
// Start looping rows in mysql database.
while($rows = mysqli_fetch_array($result)){
echo $rows['name'] . "|" . $rows['score'] . "|";
// close while loop
}
// close MySQL connection
mysqli_close($con);
?>
I guess I probably need to have something like this in the end:
while($rows = mysqli_fetch_array($result)){
echo $rows['rank'] . "|" . $rows['name'] . "|" . $rows['score'] . "|";
But can't manage to get it properly…
The result should be displayed like:
<br/> Mardoch 49507
<br/> Gunthylapointe 49504
What am I doing wrong?
Do you want window functions?
select rank() over(order by score desc) rn, s.*
from scores
order by score desc
This adds another column to the resultset, called rn, that contains the rank of each row, ordered by descending score.
Well, I change a bit my code and added this:
// Retrieve data from database
$sql = "SELECT *
FROM scores
ORDER BY score DESC";
//LIMIT 10"; // The 'LIMIT 10' part will only read 10 scores. Feel free to change this value
$result = mysqli_query($con, $sql);
$i = 0;
// Start looping rows in mysql database.
while($rows = mysqli_fetch_array($result)){
$i++;
echo ($i) . "|" . $rows['name'] . "|" . $rows['score'] . "|";
// close while loop
}
It's work a bit better but it stop my leaderboard at a moment and display a lot of 0 after:
screen capture
Seems the problem is because the next score is exactly the same as the previous…So it breaks here
I have a mysql query in which I group each post by the date is was posted. I want to be able to echo the amount of posts that happened each day, know a way?
Here is what I've written so far which does post a new <div> for each day it was posted.
$trendQuery = "
SELECT DATE(timestamp) AS ForDate,
COUNT(*) AS NumPosts
FROM trends
WHERE `trend` = '" . $_GET['graph'] . "'
GROUP BY DATE(timestamp)
ORDER BY ForDate
";
$result = mysql_query($trendQuery);
while ($row = mysql_fetch_array($result)) {
echo'
<div>
<p>Here is where I want to say how many posts that happened!</p>
</div>
';
}
You have your query pretty much set up. To echo the results, you simply need to refer the columns with the alias name, in your case ForDate and NumPosts
$trendQuery = "
SELECT timestamp AS ForDate,
COUNT(*) AS NumPosts
FROM trends
WHERE `trend` = '" . $_GET['graph'] . "'
GROUP BY timestamp
ORDER BY ForDate
";
$result = mysql_query($trendQuery);
while ($row = mysql_fetch_array($result)) {
echo'
<div>
Date: '.$row['ForDate'].' ---- Number of Posts: '.$row['NumPosts'].'<br />
</div>
';
Create a view of your trend query and inner join it with "Select (Id or day that you want to merge) From trend"
i hope that helps
I'm trying to display data starting at a certain time and day and ending and another time and day. here is my code:
<?php
include 'includes/connect3.php';
$query = "SELECT * FROM u_visits WHERE date >= '2013-08-31 22:56:20' AND date <= '2013-
08- 31 23:59:59'";
$result = mysqli_query($con,$query);
echo "<table><tr>
<th>USER ID</th>
<th>TIMES VISITED</th>
</tr>";
while($row = mysqli_fetch_assoc($result))
{
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['visits'] . "</td></tr>";
}
echo "</table>";
?>
When I go to the page, only the table header is displayed with no data showing.
you can also use BETWEEN for range comparisons.
$query = "SELECT * FROM u_visits WHERE `date` BETWEEN '2013-08-31 22:56:20' AND '2013-08-31 23:59:59'";
The reason you didn't see any result is because your query has some errors. The error in your query is that you have a space after 2013-08- in your where clause (date <= '2013-08- 31 23:59:59'";)
Had you used proper error handling, you would have noticed this yourself. One common way to do this is:
$result = mysqli_query($con,$query) or die ('Query execution failed: ' . mysqli_error($con));
Im trying to build a feeds application in php in which im using a simple table with 2 columns..one for name and one for the respective feeds...my feed is appearing properly but there is some problem with the name heres the code...
<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT id, feed, feeddate FROM feeds ORDER BY feeddate DESC LIMIT 20");
while($row = mysql_fetch_array($sql))
{
$name = $row["name"];
$uid = $row["userid"];
$ufeed = $row["feed"];
$feeddate = $row["feeddate"];
$feeds .= '
<table width="90%" align="center" cellpadding="4" bgcolor="#A6D2FF">
<tr>
<td width="7%" bgcolor="#FFFFFF">' . $name . '<br />
</td>
<td width="93%" bgcolor="#D9ECFF"> <span style="font-size:10px; font-weight:bold; color:#A6A6A6;">' . $feeddate . '</span><br />
' . $ufeed . '</td>
</tr>
</table>';
}?>
<?php print "$feeds"; ?>
here the $name thing is simply not displaying as a link!please help..
You are selecting only three columns:
SELECT id, feed, feeddate
"name" is not among them, so it will be always empty.
$row["name"] is not set, because you did not include the name column in the select expression of the database query. Consequently, the statement
$name = $row["name"];
sets $name to null. The same holds for $uid and $row["userid"].
Your sql query should be
$sql = mysql_query("SELECT name, id, feed, feeddate FROM feeds ORDER BY feeddate DESC LIMIT 20");
Also, you have $uid = $row["userid"];. I believe it should be $uid = $row["id"]; as you have id in sql query. You have to change either of them.
If you have id use above query, else use below query.
$sql = mysql_query("SELECT name, userid, feed, feeddate FROM feeds ORDER BY feeddate DESC LIMIT 20");
You are selecting 3 columns id,feed,feed date.But you are printing name,id,feed,feed date. Please select name column also. It will display proper output.
I have a MySQL database called "bookfeather" with several tables that contain list books. Under each table, each book has a given number of votes. The PHP code below allows the user to enter in a book title ($entry), and then returns the total number of votes that book has in all tables ($sum).
How could I use PHP to make a 2-column, 25-row table that lists the 25 books in the database with the highest value for $sum (in descending order)?
Thanks in advance,
John
mysql_connect("mysqlv10", "username", "password") or die(mysql_error());
mysql_select_db("bookfeather") or die(mysql_error());
// We preform a bit of filtering
$entry = strip_tags($entry);
$entry = trim ($entry);
$entry = mysql_real_escape_string($entry);
$result = mysql_query("SHOW TABLES FROM bookfeather")
or die(mysql_error());
$table_list = array();
while(list($table)= mysql_fetch_row($result))
{
$sqlA = "SELECT COUNT(*) FROM `$table` WHERE `site` LIKE '$entry'";
$resA = mysql_query($sqlA) or die("$sqlA:".mysql_error());
list($isThere) = mysql_fetch_row($resA);
$isThere = intval($isThere);
if ($isThere)
{
$table_list[] = $table;
}
}
//$r=mysql_query("SELECT * , votes_up - votes_down AS effective_vote FROM `$table[0]` ORDER BY effective_vote DESC");
if(mysql_num_rows($resA)>0){
foreach ($table_list as $table) {
$sql = "SELECT votes_up FROM `$table` WHERE `site` LIKE '$entry'";
$sql1 = mysql_query($sql) or die("$sql:".mysql_error());
while ($row = mysql_fetch_assoc($sql1)) {
$votes[$table] = $row['votes_up'];
$sum += $row['votes_up'];
//echo $table . ': "' . $row['votes_up'] . " for $entry from $table\"<br />";
}
}
}
else{
print "<p class=\"topic2\">the book \"$entry\" has not been added to any category</p>\n";
}
//within your loop over the DB rows
//$votes[$table] = $row['votes_up'];
//afterwards
if($sum>0){
print "<table class=\"navbarb\">\n";
print "<tr>";
print "<td class='sitenameb'>".'<a type="amzn" category="books" class="links2b">'.$entry.'</a>'."</td>";
print "</tr>\n";
print "</table>\n";
//echo "<p class=\"topic3\">".''.$entry.''. "</p>\n";
echo "<p class=\"topic4\">". number_format($sum) . ' votes in total.'."</p>\n";
Try something like this. All of this hasn't been tested so please add comments for changes. I'll work with you to get the code right.
// After getting your array of tables formated like
$tableArray = array("`tableA`", "`tableB`", "`tableC`");
// create a table statement
$tableStatement = implode(", ", $tableArray);
// create a join statement
$joinStatement = "";
for ($i = 1; $i < count($tableArray); $i++) {
if ($joinStatement != "")
$joinStatement .= " AND ";
$joinStatement .= $tableArray[0] . ".site = " . $tableArray[$i] . ".site"
}
$firstTable = $tableArray[0];
$sql = "SELECT SUM(votes_up) FROM " . $tableStatement . " WHERE " . $joinStatement . " AND " . $firstTable . ".site LIKE '" . $entry . "' GROUP BY " . $firstTable . ".site ORDER BY SUM(votes_up) DESC";
Edit --------
I now realize that the query above won't work perfectly because votes_up will be ambiguous. Also because you probably want to be doing joins that grab records that are only in one table. I think the concept is the right direction even though the query may not be perfect.
You can do something like
$selectStatement = "SUM(tableA.votes_up) + SUM(tableB.votes_up) as total_votes_up"
I did something like this recently. In your database, you'll have to rename each field to a corresponding book name.php like (TaleofTwoCities.php). Now on your page that will display the vote results, you'll need to include some php files that will drive the database query on each load. I called mine "engine1.php" and "engine2.php." These will do all your sorting for you.
$query1 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 0,1"));
$query2 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 1,1"));
$query3 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 2,1"));
and so on.. then..
$num1 = "$query1[0]";
$num2 = "$query2[0]";
$num3 = "$query3[0]";
That part sorts your listings by the number of votes from highest to lowest, with url, in your case, being the name of the books(remember you want it to end in .php - you'll see why in a second), and counter being the field that logs your votes.
Make your second engine.php file and add something like this:
$vquery1 = mysql_fetch_row(mysql_query("SELECT counter FROM pages WHERE
url='book1.php'"));
$vquery2 = mysql_fetch_row(mysql_query("SELECT counter FROM pages WHERE
url='book2.php'"));
$vnum1 = "$vquery1[0]";
$vnum2 = "$vquery2[0]";
and so on... Until you get to 25 for both this and engine 1.
Now, in your results page, after you put in the require_once(engine.php) and require_once(engine2.php) at the start of your body, start an HTML table. You only want two columns, so it'll be something like..
<table border=1 cellspacing=0 cellpadding=0>
<tr>
<?php include $num1; ?>
</tr>
<tr>
<?php include $num2; ?>
</tr>
And so on... By naming your field with "book1.php" and including the engines, $num1 will change to a different .php file depending on votes from high to low. Now all you have to do is make small php files for each book like so - no headers or anything because you're inserting it into the middle of html code already:
<td style="width:650px;"><center><img src="images/book1.jpg" alt="" border="none"
/></a></center></td>
<td style="width:150px;">Votes: <?php echo $vnum1;?></td>
And there you have it. A code that will dynamically give you results from high to low depending on the number of votes each book has.