PHP get largest number from mysql table - php

i have counted the number of voters that voted for certain candidate i want to display which one got the highest voting number. i tried to store them in variables so i can use max() method but i got the error "undefined ".any help please
<?php
$query="select count(*) as total from voting Where ca_id=1";
//ca_id is the candidate id that voter choose
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
echo"$row[total]<br>";
$query="select count(*) as total2 from voting Where ca_id=2";
$result = mysql_query($query);
$row2 = mysql_fetch_assoc($result);
echo"$row2[total2]<br>";
$query="select count(*) as total3 from voting Where ca_id=3";
$result = mysql_query($query);
$row3 = mysql_fetch_assoc($result);
echo"$row3[total3]<br>";
$query="select count(*) as total4 from voting Where ca_id=5";
$result = mysql_query($query);
$row4 = mysql_fetch_assoc($result);
echo"$row4[total4]<br>";
?>

You don't need to perform four queries for this. You could just use a single query. In your case, you could do:
select ca_id, count(*) as counter from voting group by ca_id order by counter desc
And you can get your result with a single query
As mentioned, PDO is a better alternative in this case for your database-related calls

SELECT count(1) co, ca_id FROM voting GROUP BY ca_id ORDER BY co DESC LIMIT 5

Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.
You could use something like which uses the MySQLi extension.
<?php
$mysqli = new mysqli('host', 'user', 'pass', 'db');
$sql = "SELECT COUNT(votes) as vote_count, ca_id as candidate_id FROM voting GROUP BY ca_id ORDER BY vote_count DESC";
$result= $mysqli -> query($sql);
// Error Checking
if($mysqli -> error){
echo 'Error: '.$mysqli -> error;
exit;
}
while($row = $result -> fetch_object()){
// Print out each candidate ID and the amount of votes they had.
echo 'Candidate ID: '.$row -> candidate_id.', Votes: '.$row -> vote_count.'<br/>';
// If you want to just show the highest voted candidate - put the data in an array
$votes[$row -> vote_count] = $row -> candidate_id;
}
echo max(array_keys($votes));
This will also cut the amount of queries your running down to just 1.

first of all use group by to retrieve all data in one query, instead of querying for each of the candidates:
SELECT ca_id, count(*) as total FROM voting GROUP BY ca_id
if you need a top voted id use:
SELECT ca_id, count(*) as total FROM voting GROUP BY ca_id SORT BY total
DESC LIMIT 1
Note: not the most efficient solution but will be way faster then querying for each ca_id.

Related

Guidance with a SQL query - results duplicating

Really need some guidance, I have a website where people can upload images to competitions and they get a result (marks), I want to pull out a LEADERSHIP BOARD to see how everyone is doing. However the SQL Query I have has people names duplicated, could someone tell me where to alter my query so the results for say 1 person entering 3 competitions are added up, and only the TOTAL marks are stated once in the output. The results are kept in tblMembEntComp fldResult.
What I'm currently getting:
My PHP Code:
<p><b>LEADERSHIP BOARD</b></p>
<?php
$query = "SELECT `tblMember`.`fldFName`, `tblMember`.`fldSName`, `tblMembEntComp`.`fldResult` FROM `tblMember` AS `tblMember` JOIN `tblMembEntComp` as `tblMembEntComp` ON `tblMember`.`fldMemberID` = `tblMembEntComp`.`fldMemberID`ORDER BY `fldResult` DESC";
$result = $conn -> query($query);
while($row = $result -> fetch_assoc())
{
echo $row['fldFName']." ".$row['fldSName']." ".$row['fldResult']."<br>";
}
?>
UPDATE:
I have tried the GROUP BY function as suggested by user below however I am getting thrown the error:
You seem to want an aggregation query. Something like:
SELECT m.fldSName, SUM(mec.fldResult) as fldResult
FROM tblMember m JOIN
tblMembEntComp mec
ON m.fldMemberID =mec.fldMemberID
GROUP BY m.fldSName
ORDER BY SUM(mec.fldResult) DESC
You should group by query by tblMember primary key as below:
<?php
$query = "SELECT `tblMember`.`fldFName`, `tblMember`.`fldSName`, `tblMembEntComp`.`fldResult`, `tblMember`.`fldId` FROM `tblMember` AS `tblMember` JOIN `tblMembEntComp` as `tblMembEntComp` ON `tblMember`.`fldMemberID` = `tblMembEntComp`.`fldMemberID` GROUP BY `tblMember`.`fldId` ORDER BY `fldResult` DESC";
$result = $conn -> query($query);
while($row = $result -> fetch_assoc())
{
echo $row['fldFName']." ".$row['fldSName']." ".$row['fldResult']."<br>";
}
?>
You can update group by field as your primary key. Hope it helps you :)

PHP Calculate rank from database

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...

How do I display data retrieved from mysql db in a specific order using php

I am trying to display questions, along with the users answer in a specific order, NOT ASC or DESC, but as defined by the "question_order" column.
I have the following tables in a mysql db:
questions (qid, question_text)
answers (aid, uid, answer)
usermeta (userid, question_order)
"questions" table contains the questions
"answers" table contains every users answers to all questions
"usermeta" table contains the sort order for the questions in "question_order".
"question_order" is unique per user and is in the db as a pipe delimited list. (i.e.: 85|41|58|67|21|8|91|62,etc.)
PHP Version 5.3.27
If this entire procedure can be better accomplished using a completely different method, then please let me know.
My PHP ability is limited. With that said, below is what I have at the moment after several hours of playing ...
$sql = "
SELECT
*
FROM
".USERMETA_TABLE."
WHERE
userid = {$userid}
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row = $result->fetch_assoc();
$order_array = explode('|', $row['question_order']);
$sql = "
SELECT
*
FROM
".QUESTIONS_TABLE."
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row = $result->fetch_assoc();
// my attempt at sorting the questions. the $order_array
// does not have a unique id so I am kind of lost as to
// how to make this work
usort($myArray, function($order_array, $row) {
return $order_array - $row['qid'];
});
$sql = "
SELECT
*
FROM
".QUESTIONS_TABLE."
";
$result = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
while ( $row = $result->fetch_assoc() )
{
$sql = "
SELECT
*
FROM
".ANSWERS_TABLE."
WHERE
uid = {$userid}
AND
qid = ".$row['qid']."
LIMIT
1
";
$result2 = $db->query($sql) OR sql_error($db->error.'<br />'.$sql);
$row2 = $result2->fetch_assoc();
echo ' <p>'.$row['question_text'].'</p>'."\n";
echo ' <p>'.$row2['answer'].'</p>'."\n";
}
Filter out the data when retrieving from db.
Use:- SELECT * FROM [TABLE_NAME] ORDER BY qid DESC
Then in PHP you can use session variables and modify the values accordingly.
If you want to order using ID you can use
SELECT * FROM [TABLE_NAME] ORDER BY qid DESC
this will order in descending order If you want in ascending order use ASC
I went ahead and altered the DB by adding a table to store the question numbers, user sort order, and student user id:
student_id, sort_order, question_id
1 1 8
1 2 2
1 3 97
and then was able to select it all with the following statement:
SELECT q.*
FROM
questions q
JOIN questions_sorting_order qso
ON q.id = qso.question_id
ORDER BY qso.sort_order
WHERE qso.student_id = $student_id
...works great.
Thanks to FuzzyTree for his help on this at: How do I sort data from a mysql db according to a unique and predetermined order, NOT asc or desc

mysql + php: Selecting multiple random results

I've been looking for this for a while but with no success.
I am trying to implement a recomendation bar, for example like in youtube, when you are seeing a video it shows the list or recommended videos on the right.
At this moment I am using this method:
$offset_result = mysql_query( " SELECT FLOOR(RAND() * COUNT(*)) AS `offset` FROM `$tablename` ");
$offset_row = mysql_fetch_object($offset_result );
$offset = $offset_row->offset;
$result_rand = mysql_query( " SELECT * FROM `$tablename` LIMIT $offset, 9 " );
This works fine, but sometimes doesn't show any result, and the problem is also that its not completely random, because it shows for example the first ID as 200, so the next result will be id 201 and then 202 and so.
I would like to know if there is a way to show this 9 randon results, for example 1º result id 500, 2º result id 10, 3º result id 788, etc etc?
Thank you
Not entirely sure this answers what you are looking for, but try:
$result_rand = mysql_query("SELECT * FROM " . $tablename . " ORDER BY RAND() LIMIT 9");
You can use php rand() function to create 5 numbers and save them in an array:
http://php.net/manual/en/function.rand.php
<?php
$rand_array = array();
for($i=1;$i<5;$i++) {
$rand_array[$i] = rand(0,500);
}
?>
and after that create a query with every int with a foreach loop and work with your data.
<?php
foreach ($rand_array as $integer) {
$q = "SELECT * from $tablename WHERE id='$integer';";
}
?>
Does this helps?
First you should use mysqli_ functions instead of mysql_ because the latter is deprecated. Second use order by rand() to get random rows:
$rand_result = mysqli_query( "SELECT * FROM $tablename ORDER BY RAND() LIMIT 9;" );
UNTESTED:
SELECT id, #rownum:=#rownum+1 AS rownum, name
FROM users u,
(SELECT #rownum:=0) r
THis will give a unique number to each row in sequence. Now if you create a temp table with 9 random numbers between 1 and count(*) of your table and JOIN those two together...
Not sure about performance but seems like it might be faster than Rand and order by since I only need 9 random numbers

Selecting the most popular entry from the last ten values entered

I have the selecting from the last ten entries working, but am unsure how to get the most popular from these ten entries? Also how would I count the number of the most popular entry & output it to a percentage?
<?php
$sql = "SELECT data FROM table_answers ORDER BY id DESC LIMIT 10";
$result = mysql_query ($sql, $db);
while ($row = mysql_fetch_array ($result))
{
echo "[".$row['data']."]";
}
?>
And I have tried to do the WHERE value as well but it doesn't return any result.
$sql = "SELECT data FROM table_answers WHERE id IN (SELECT id FROM table_answers
ORDER BY id DESC LIMIT 10) ORDER BY popularity DESC LIMIT 1";
$result = mysql_query ($sql, $db);
while ($row = mysql_fetch_array ($result))
{
echo " [".$row['data']."] ";
}
Anyone have any idea what I might be doing wrong here? please
This should solve the problem -
SELECT tableorder.*
FROM (SELECT *
FROM table
ORDER BY id DESC
LIMIT 10) tableorder
ORDER BY tableorder.popularity DESC
LIMIT 1
The inner query will sort on the basis on id and get the top 10. The outer will again sort the 10 rows on the basis of popularity and return the row with highest popularity.
SELECT data
FROM (
SELECT data
FROM table_answers
ORDER BY id DESC
LIMIT 10
) t
ORDER BY popularity

Categories