I am trying to get a list of highscores (top 10) of players that played my game.
Everything works except for one thing, the list isn't right.
The first 10 people are correct, but when i go to page 2 the list isn't further going done.
Variables Explain
$gamemode = "Endless"
$filter = "Score"
$startNum = Page1 = 0, Page2 = 10
$maxlimit = 10
Query:
$query = "SELECT ID, Gamemode, Name, Score, ContainersSaved, TimePlayed, Date, ScorePerMinute
FROM $dbName . `highscore`
WHERE Gamemode='$gamemode'
ORDER by `$filter` DESC
LIMIT $startNum, $maxlimit";
Does anyone know what im doing wrong?
If your Score field is varchar try: (or change it to INT)
$order=$filter;
if($filter=='Score') {
$order="ABS($filter);
}
$query = "SELECT ID,Gamemode,Name,Score,ContainersSaved,TimePlayed,Date,ScorePerMinute FROM $dbName . `highscore` WHERE Gamemode='$gamemode' ORDER by $order DESC LIMIT $startNum, $maxlimit";
I fixed it, i forgot to change the 'Score' field from varchar to an INT, so it was trying to Descend on string instead of INT.
Thanks to the tip Imaginaerum gave me :)
Related
I'm trying to get the ID from the next row in MySQL database. How exactly would I do that? The code I'm currently working with the following code. I'm semi-new to PHP and SQL and also 15, so please be understanding if this isn't exactly right.
Here's what I have so far:
$GetNext = "SELECT * FROM sheep WHERE id = '> $row[id]' AND owner = $_SESSION[user_id] AND barn = $row[barn] AND pasture = $row[pasture]";
$get = mysqli_query($conn, $GetNextLeft);
$row = mysqli_fetch_assoc($get);
With 'LIMIT' we can get 1 data.
We sort by 'ORDER BY id ASC' we sort by small to large size.
$GetNext = "SELECT * FROM sheep WHERE id > $row[id] AND owner = $_SESSION[user_id] AND barn = $row[barn] AND pasture = $row[pasture] ORDER BY id ASC LIMIT 1";
You can do this using order by and limit such as:
select s.*
from sheep s
where id > ? and . . .
order by id desc
limit 1;
The ? is a reminder that you should be using parameters in your queries, rather than munging query strings with input values.
You mean the first id greater than row['id']? You should ORDER BY the id, than use limit to get only the first row.
I got a little problem, I've got a database, in that database are different names, id, and coins. I want to show people their rank, so your rank has to be 1 if you have the most coins, and 78172 as example when your number 78172 with coins.
I know I can do something like this:
SELECT `naam` , `coins`
FROM `gebruikers`
ORDER BY `coins` DESC
But how can I get the rank you are, in PHP :S ?
You can use a loop and a counter. The first row from MySql is going the first rank,I.e first in the list.
I presume you want something like:
1st - John Doe
2nd - Jane Doe
..
..
right?
See: http://www.if-not-true-then-false.com/2010/php-1st-2nd-3rd-4th-5th-6th-php-add-ordinal-number-suffix
Helped me a while ago.
You could use a new varariable
$i = "1";
pe care o poti folosi in structura ta foreach,while,for,repeat si o incrementezi mereu.
and you use it in structures like foreach,while,for,repeat and increment it
$i++;
this is the simplest way
No code samples above... so here it is in PHP
// Your SQL query above, with limits, in this case it starts from the 11th ranking (0 is the starting index) up to the 20th
$start = 10; // 0-based index
$page_size = 10;
$stmt = $pdo->query("SELECT `naam` , `coins` FROM `gebruikers` ORDER BY `coins` DESC LIMIT {$start}, {$page_size}");
$data = $stmt->fetchAll();
// In your template or whatever you use to output
foreach ($data as $rank => $row) {
// array index is 0-based, so add 1 and where you wanted to started to get rank
echo ($rank + 1 + $start) . ": {$row['naam']}<br />";
}
Note: I'm too lazy to put in a prepared statement, but please look it up and use prepared statements.
If you have a session table, you would pull the records from that, then use those values to get the coin values, and sort descending.
If we assume your Session table is sessions(session_id int not null auto_increment, user_id int not null, session_time,...) and we assume that only users who are logged in would have a session value, then your SQL would look something like this: (Note:I am assuming that you also have a user_id column on your gebruikers table)
SELECT g.*
FROM gebruikers as g, sessions as s WHERE s.user_id = g.user_id
ORDER BY g.coins DESC
You would then use a row iterator to loop through the results and display "1", "2", "3", etc. The short version of which would look like
//Connect to database using whatever method you like, I will assume mysql_connect()
$sql = "SELECT g.* FROM gebruikers as g, sessions as s WHERE s.user_id = g.user_id ORDER BY g.coins DESC";
$result = mysql_query($sql,$con); //Where $con is your mysql_connect() variable;
$i = 0;
while($row = mysql_fetch_assoc($result,$con)){
$row['rank'] = $i;
$i++;
//Whatever else you need to do;
}
EDIT
In messing around with a SQLFiddle found at http://sqlfiddle.com/#!2/8faa9/6
I came accross something that works there; I don't know if it will work when given in php, but I figured I would show it to you either way
SET #rank = 0; SELECT *,(#rank := #rank+1) as rank FROM something order by coins DESC
EDIT 2
This works in a php query from a file.
SELECT #rank:=#rank as rank,
g.*
FROM
(SELECT #rank:=0) as z,
gebruikers as g
ORDER BY coins DESC
If you want to get the rank of one specific user, you can do that in mysql directly by counting the number of users that have more coins that the user you want to rank:
SELECT COUNT(*)
FROM `gebruikers`
WHERE `coins` > (SELECT `coins` FROM `gebruikers` WHERE `naam` = :some_name)
(assuming a search by name)
Now the rank will be the count returned + 1.
Or you do SELECT COUNT(*) + 1 in mysql...
I am sure this is possible but I think it maybe just very complex to write. I want to search every field by:
='SearchTerm'
then
Like %SearchTerm
then
like SearchTerm%
and finally
like %SearchTerm%. I want to run this on every field in my table which there is around 30 or 40. Is there an easy way to run this over multiple fields or will I have to declare every single one?
I think I have seen a query before where different matches between %query %query% etc are ranked by assigning an integer value and then ordering by this. Would that be possible on a query like this?
Any advice and help in the right direction is much appreciated.
You should use fulltext indexing on the fields you want searched and use MATCH AGAINST instead of LIKE %%. It's much faster and returns results based on relevancy. More info here:
Mysql match...against vs. simple like "%term%"
I do something very similar to what you're describing (in php and mysql)
Here's my code:
$search = trim($_GET["search"]);
$searches = explode(" ",$search);
$sql = "SELECT *,wordmatch+descmatch+usagematch+bymatch as `match` FROM (SELECT id,word,LEFT(description,100)as description,
IFNULL((SELECT sum(vote)
FROM vote v
WHERE v.definition_id = d.id),0) as votecount,
";
$sqlword = "";
$sqldesc = "";
$sqlusage = "";
$sqlby = "";
foreach ($searches as $value) {
$value = mysqli_real_escape_string($con,$value);
$sqlword = $sqlword . "+ IFNULL(ROUND((LENGTH(word) - LENGTH(REPLACE(UPPER(word), UPPER('$value'), '')))/LENGTH('$value')),0)";
$sqldesc = $sqldesc . "+ IFNULL(ROUND((LENGTH(description) - LENGTH(REPLACE(UPPER(description), UPPER('$value'), '')))/LENGTH('$value')),0)";
$sqlusage = $sqlusage . "+ IFNULL(ROUND((LENGTH(`usage`) - LENGTH(REPLACE(UPPER(`usage`), UPPER('$value'), '')))/LENGTH('$value')),0)";
$sqlby = $sqlby . "+ IFNULL(ROUND((LENGTH(`by`) - LENGTH(REPLACE(UPPER(`by`), UPPER('$value'), '')))/LENGTH('$value')),0)";
}
$sql = $sql . $sqlword ." as wordmatch,"
. $sqldesc ." as descmatch,"
. $sqlusage ." as usagematch,"
. $sqlby ." as bymatch
FROM definition d
HAVING (wordmatch > 0 OR descmatch > 0 OR usagematch > 0 OR bymatch > 0)
ORDER BY
wordmatch DESC,
descmatch DESC,
usagematch DESC,
bymatch DESC,
votecount DESC)T1";
$queries[] = $sql;
$result = mysqli_query($con,$sql);
You can see this at work http://unurbandictionary.comule.com/view_search.php?search=George+Miley+Cyrus this is when I search for "George Miley Cyrus"
What it does is it explodes the search string to find each word and returns the number of occurences of each word in each of my column, and then i do an ORDER BY to have relevance (priority) to come back first. So in my case word field has the highest relevance, then description field, then usage field, then by field.
Before this version of my code I was using LIKE but it didn't give me a count of occurences, since I want the row with the most occurences of my search word to return first before other rows.
You should really have some sort of id to select the rows in your table.
You should have put a column with
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
Then you could use
SELECT * FROM table WHERE column1 LIKE "%SearchTerm%" AND id BETWEEN 1 AND 40
I want to get all rows count in my sql.
Table's first 2 columns look like that
My function looks like that
$limit=2;
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
$stmt = $this->db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id, $total, $datetime, $title, $content);
$stmt->store_result();
$count = $stmt->num_rows;
if ($count > 0) {
while ($stmt->fetch()) {
Inside loop, I'm getting exact value of $total, but MySQL selects only 1 row - row with id number 1. (and $count is 1 too)
Tried this sql
SELECT id,dt,title,content FROM news ORDER BY dt DESC LIMIT 2
All goes well.
Why in first case it selects only 1 row? How can I fix this issue?
for ex my table has 5 rows. I want to get 2 of them with all fields, and get all rows count (5 in this case) by one query.
Remove COUNT(*). You will only ever get 1 row if you leave it in there.
Try adding GROUP BY dt if you want to use COUNT(*) (not sure why you're using it though).
EDIT
Fine, if you insist on doing it in a single call, here:
$sql = "SELECT id,(SELECT COUNT(id) FROM news) as total,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
This is likely cause by the variable $limit being set to 1, or not being set and mysql defaulting to 1. Try changing your first line to
$sql = "SELECT id,COUNT(*),dt,title,content FROM news ORDER BY dt DESC";
EDIT
Change to:
$sql = "SELECT SQL_CALC_FOUND_ROWS,id,dt,title,content FROM news ORDER BY dt DESC LIMIT " . $limit;
And then use a second query with
SELECT FOUND_ROWS( )
to get the number of rows that match the query
This totally wreaks of a HW problem... why else besides a professor's retarded method to add complexity to a simple problem would you not want to run two queries?
anyways.... here:
SELECT id, (SELECT COUNT(*) FROM news) AS row_count, dt, title, content FROM news ORDER BY dt DESC LIMIT
I have problem with database. I want to add about 10 new rows after pageload. It should check if there is an article with id (that is actually loading). If its not, add 10 of that id with different tag id.
$sprawdz = "SELECT id_artykulow FROM tag_art WHERE id_artykulow='".$_GET['id']."' " ;
$miasto = mysql_query($sprawdz);
$a = mysql_num_rows($miasto);
while ($a<=10){
$zm = "SELECT id FROM tag_content ORDER BY RAND() LIMIT 1";
$sw = mysql_query($zm);
while($row3=mysql_fetch_array($sw)){
$zmienna = "INSERT INTO tag_art(id_artykulow, id_tagow) VALUES ('".$_GET['id']."', '".$row3['id']."' ) ";
$cokolwiek = mysql_query($zmienna);
}
$a++;
}
There is two tables. One tag_content with id (of the tags), and another tag_art with id_artykulow (= id of the article) and id_tagow (id of the tag taken from tag_content)
Don't know why, but it doesn't add 10 rows (it should be for example ten id_artykulow = 10, with different id_tagow). How to fix it?
Thx for help and let me know if u need more informations (like more code etc.)
why do you have 2 while loops?
cant you just replace
while ($a<=10){
$zm = "SELECT id FROM tag_content ORDER BY RAND() LIMIT 1";
with
if ($a<=10){
$zm = "SELECT id FROM tag_content ORDER BY RAND() LIMIT " . (10-$a);
or just let the databse do all the work by:
$query = "INSERT INTO tag_art(id_artykulow, id_tagow) SELECT '".$_GET['id']."', id FROM tag_content ORDER BY RAND() LIMIT " . (10-$a);
(and i would also recomendate protection agains sql-injections, mysql_real_escape_string())
Or let the database do all the work:
// store id as mysql-variable, but let php force it to an integer first
mysql_query("SET #id = " . (int) $_GET['id']);
// calculate how many new art we need, to get 10, using greatest to avoid negative numbers
mysql_query("SELECT #art_needed := GREATEST(0, 10 - COUNT(*)) FROM tag_art WHERE id_artykulow = #id");
// Need to use prepere to be able to have an mysql-variable as limit
mysql_query("PREPARE art_stmt FROM 'INSERT INTO tag_art(id_artykulow, id_tagow) SELECT ?, id FROM tag_content ORDER BY RAND() LIMIT ?'");
// execute the query using the mysql-variables
mysql_query("EXECUTE art_stmt USING #id, #art_needed");
just reread my old answer, and no longer agrees with "or just let the databse do all the work by" for that answer, the database could do alot more.