How do I get the result into a variable MYSQL - php

I have the following PHP script. How do I get the correct results. Each query should only return a number. I need to get rank in this case. I was also wondering how to combine those two queries into one statement.
function getRankings($country, $deviceid)
{
$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$resultWorld = mysql_query($queryWorld) or die(mysql_error());
$rowWorld = mysql_fetch_row($resultWorld);
$resultCountry = mysql_query($queryCountry) or die(mysql_error());
$rowCountry = mysql_fetch_row($resultCountry);
$arr = array();
$arr[] = array("WorldRanking" => $rowWorld[0], "CountryRanking" => $rowCountry[0]);
echo json_encode($arr);
}
If I type the queries individually into MYSQl I get the correct answers. But the echo produces
[{"WorldRanking":null,"CountryRanking":null}]
It should be something like
[{"WorldRanking":"4","CountryRanking":"1"}]
I think I need to get the value of rank but I do not know how.

try your code like this, but I don't know this code correct or not:
function getRankings($country, $deviceid)
{
$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID='$deviceid' ORDER BY rank LIMIT 1";
$resultWorld = mysql_query($queryWorld) or die(mysql_error());
while ($rowWorld = mysql_fetch_row($resultWorld)){
$value1 = $rowWorld['filedname1'];
}
$resultCountry = mysql_query($queryCountry) or die(mysql_error());
while($rowCountry = mysql_fetch_row($resultCountry)){
$value2 = $rowWorld['filedname2'];
}
$arr[] = array("WorldRanking" => $value1, "CountryRanking" => $value2);
print_r($arr);
}

<?php
function getRankings($country, $deviceid)
{
$queryWorld = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score ) AS rank FROM
ScoreTable b WHERE DeviceID=$deviceid ORDER BY rank LIMIT 1";
$queryCountry = "SELECT 1 + (SELECT count( * ) FROM ScoreTable a WHERE a.score > b.score AND Country='$country') AS rank FROM ScoreTable b WHERE DeviceID=$deviceid ORDER BY rank LIMIT 1";
$resultWorld = mysql_query($queryWorld) or die(mysql_error());
$no_of_results_in_resultWorld = mysql_num_rows($resultWorld);
if($no_of_results_in_resultWorld > 0){
$rowWorld = mysql_fetch_row($resultWorld);
}
$resultCountry = mysql_query($queryCountry) or die(mysql_error());
$no_of_results_in_resultCountry = mysql_num_rows($resultCountry);
if($no_of_results_in_resultCountry > 0){
$rowCountry = mysql_fetch_row($resultCountry);
}
$arr = array();
$arr[] = array("WorldRanking" => $rowWorld[0], "CountryRanking" => $rowCountry[0]);
echo json_encode($arr);
}
check whether it is returning results or not.

Related

joomla php sort array from high to low [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Sort array of objects by one property
(23 answers)
Closed 4 years ago.
I am trying to sort an array from high to low.
The query is written in an Joomla module and is this one:
$authors = array();
if (count($rows))
{
foreach ($rows as $row)
{
$author = JFactory::getUser($row->created_by);
$author->link = JRoute::_(K2HelperRoute::getUserRoute($author->id));
$query = "SELECT id, gender, description, image, url, `group`, plugins FROM #__k2_users WHERE userID=".(int)$author->id;
$db->setQuery($query);
$author->profile = $db->loadObject();
if ($params->get('authorAvatar'))
{
$author->avatar = K2HelperUtilities::getAvatar($author->id, $author->email, $componentParams->get('userImageWidth'));
}
if (K2_JVERSION != '15')
{
$languageCheck = '';
if ($application->getLanguageFilter())
{
$languageTag = JFactory::getLanguage()->getTag();
$languageCheck = "AND i.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") AND c.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').")";
}
$query = "SELECT i.*, c.alias as categoryalias FROM #__k2_items as i
LEFT JOIN #__k2_categories c ON c.id = i.catid
WHERE i.created_by = ".(int)$author->id."
AND i.published = 1
AND i.access IN(".implode(',', $user->getAuthorisedViewLevels()).")
AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )
AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )
AND i.trash = 0 AND created_by_alias='' AND c.published = 1 AND c.access IN(".implode(',', $user->getAuthorisedViewLevels()).") AND c.trash = 0 {$languageCheck} ORDER BY created DESC";
}
else
{
$query = "SELECT i.*, c.alias as categoryalias FROM #__k2_items as i
LEFT JOIN #__k2_categories c ON c.id = i.catid
WHERE i.created_by = ".(int)$author->id."
AND i.published = 1
AND i.access <= {$aid}
AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )
AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )
AND i.trash = 0 AND created_by_alias='' AND c.published = 1 AND c.access <= {$aid} AND c.trash = 0 ORDER BY created DESC";
}
$db->setQuery($query, 0, 1);
$author->latest = $db->loadObject();
$author->latest->id = (int)$author->latest->id;
$author->latest->link = urldecode(JRoute::_(K2HelperRoute::getItemRoute($author->latest->id.':'.urlencode($author->latest->alias), $author->latest->catid.':'.urlencode($author->latest->categoryalias))));
$query = "SELECT COUNT(*) FROM #__k2_comments WHERE published=1 AND itemID={$author->latest->id}";
$db->setQuery($query);
$author->latest->numOfComments = $db->loadResult();
if ($params->get('authorItemsCounter'))
{
if (K2_JVERSION != '15')
{
$languageCheck = '';
if ($application->getLanguageFilter())
{
$languageTag = JFactory::getLanguage()->getTag();
$languageCheck = "AND language IN (".$db->Quote($languageTag).", ".$db->Quote('*').")";
}
$query = "SELECT COUNT(*) FROM #__k2_items WHERE {$where} published=1 AND ( publish_up = ".$db->Quote($nullDate)." OR publish_up <= ".$db->Quote($now)." ) AND ( publish_down = ".$db->Quote($nullDate)." OR publish_down >= ".$db->Quote($now)." ) AND trash=0 AND access IN(".implode(',', $user->getAuthorisedViewLevels()).") AND created_by_alias='' AND created_by={$row->created_by} {$languageCheck} AND EXISTS (SELECT * FROM #__k2_categories WHERE id= #__k2_items.catid AND published=1 AND trash=0 AND access IN(".implode(',', $user->getAuthorisedViewLevels()).") {$languageCheck} )";
}
else
{
$query = "SELECT COUNT(*) FROM #__k2_items WHERE {$where} published=1 AND ( publish_up = ".$db->Quote($nullDate)." OR publish_up <= ".$db->Quote($now)." ) AND ( publish_down = ".$db->Quote($nullDate)." OR publish_down >= ".$db->Quote($now)." ) AND trash=0 AND access<={$aid} AND created_by_alias='' AND created_by={$row->created_by} AND EXISTS (SELECT * FROM #__k2_categories WHERE id= #__k2_items.catid AND published=1 AND trash=0 AND access<={$aid} ) ";
}
$db->setQuery($query);
$numofitems = $db->loadResult();
$author->items = $numofitems;
}
$authors[] = $author;
}
}
return $authors;
}
then the result is passing to these variables and finally authors table is returned. This table I want to sort from high to low. I have tried the php functions but none of them seem to working.
I cannot be sure if the query retrieves something else beyond the items counter and set it as key. But I have tried functions such as arsort which is sorting by value and not key.
$db->setQuery($query);
$numofitems = $db->loadResult();
$author->items = $numofitems;
$authors[] = $author;
arsort($authors);
Any idea is appreciated
Thank you
Generally database queries can be sorted by specifying an order as in
$query->order('my_table.my_column desc')
If you're sorting a PHP array and require a custom sort criteria, you can use your own sort criteria with usort. For example:
// Your comparison function:
function myComparer($object1, $object2)
{
if ($object1->item == $object2->item) {
return 0;
}
return ($object1->item < $object2-item) ? -1 : 1;
}
// Sort the array in place
usort($authors, 'myComparer');
Note you can reverse the order of the sort by simply swapping the comparison return values:
return ($object1->itemCount < $object2-itemCount) ? 1 : -1;

Calculate SUM in PHP

<?php
$today=date('Y-m-d');
$sorgu = mysqli_query($conn, "SELECT * FROM urun");
while ($sira = mysqli_fetch_array($sorgu)) {
$urun = $sira['urun'];
$query = mysqli_query($conn, "SELECT product_name, birim, SUM(quantity) FROM
product WHERE product_name = '$urun' AND quantity != '0' AND quantity > '0'
AND grup!='uygulama' AND skt > '$today' GROUP BY product_name, birim ");
while ($row = mysqli_fetch_array($query)){
if ($row['2'] <= $sira['minstok']) {
echo count($row['0']);
} } } ?>
This code belongs to a table which has a notification system. I want the notification part increase when the line number increases in that table but it turns 11111111... , So how can I make the code give me sum?
Incidentally, everything up to while ($row... can be rewritten as follows:
SELECT p.product_name
, p.birim
, SUM(p.quantity) total
FROM urun u
JOIN product p
ON p.product_name = u.urun
AND p.quantity > 0
AND p.grup != 'uygulama'
AND p.skt > CURDATE()
GROUP
BY p.product_name
, p.birim;

Php number each query result

I am making a leaderboard, I want to number it like 1st place 2nd place etc in a html table field.
How to I number each row of information coming out?
Something like
$result + 1 ?
My query
$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 1");
while($row = mysqli_fetch_array($result)) {
$bank = $row['bank'];
}
Thanks.
You can sort through the query results using:
$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");
$rows = mysqli_num_rows($result);
for($x = 1; $x <= $rows; $x++) {
$row = mysqli_fetch_array($result);
echo "#{$x} " . $row['bank'];
}
This will start counting down, showing "#1... #2... #3..." etc. You can also do this with your while loop:
$result = mysqli_query($con,"SELECT * FROM playerdata WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");
$x = 1;
while($row = mysqli_fetch_array($result)) {
$bank = $row['bank'];
echo "#{$x} " . $bank;
$x++;
}
With query itself you can build the result, I think this is what u needed. Not sure
SELECT #curRank := #curRank + 1 AS rank, a.*
FROM playerdata a, (SELECT #curRank := 0) r
WHERE Admin='0' ORDER BY Bank DESC LIMIT 900
In php
$result = mysqli_query($con,"SELECT #curRank := #curRank + 1 AS rank, a.*
FROM playerdata a, (SELECT #curRank := 0) r
WHERE Admin='0' ORDER BY Bank DESC LIMIT 900");
while($row = mysqli_fetch_array($result)) {
$rank = $row['rank'];
$bank = $row['Bank'];
}

Loop Through Until Variable Reaches 0

I have a query that gives me the number of occurrences using a count, see below:
$query = "SELECT COUNT(a.market_id) AS winners, a.winner,
a.twitter_pubstatus, a.market, a.racetime, a.racecourse, b.course, b.horse,
b.type, b.racetime FROM results a INNER JOIN bets b ON a.racecourse = b.course
WHERE a.twitter_pubstatus = 0 AND a.market = '$win' AND
b.type = '$userwin' AND a.winner = b.horse;";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$checkWinners = $row['winners'];
echo $checkWinners;
This for example will return 11. I now have an IF statement:
<?php if ($checkWinners > 1) { ?>
DO THIS
<? } else { ?>
DO THIS INSTEAD
<? } ?>
Now it runs through this once and that's fine. I want it to loop through so, 11 then goes through the first bit then need it will be 10 and go through until it hits 0 and then stop.
How to do this? While Loop? Help Appreciated
Yes you can do this with a while loop. The basic logic is this:
$c = 10;
while ($c > 0) {
// do something
$c--;
}
But if I had to take a guess, I think maybe what you really want is this:
$query = "SELECT COUNT(a.market_id) AS winners, a.winner,
a.twitter_pubstatus, a.market, a.racetime, a.racecourse, b.course, b.horse,
b.type, b.racetime FROM results a INNER JOIN bets b ON a.racecourse = b.course
WHERE a.twitter_pubstatus = 0 AND a.market = '$win' AND
b.type = '$userwin' AND a.winner = b.horse;";
$result = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_array($result) ) {
$checkWinners = $row['winners'];
echo $checkWinners . '<br/>';
}
This loops through all the rows returned from the query.
while($checkWinners >0){
echo $checkWinners;
$checkWinners--;
}
An even simpler way is to loop through normally, and have MySQL order them as you need, to ensure they are in the right order.
$query = "SELECT COUNT(a.market_id) AS winners, a.winner,
a.twitter_pubstatus, a.market, a.racetime, a.racecourse, b.course, b.horse,
b.type, b.racetime FROM results AS a INNER JOIN bets AS b ON a.racecourse = b.course
WHERE a.twitter_pubstatus = 0 AND a.market = '$win' AND
b.type = '$userwin' AND a.winner = b.horse
ORDER BY winners DESC;"; //<--- ORDER BY
$result = mysql_query($query) or die(mysql_error());
if( mysql_num_rows( $result ) ) { //Check if there's any results
while ( $row = mysql_fetch_array($result) ) { //Iterate results until empty
$checkWinners = $row['winners'];
//Tweet winners code here
echo $checkWinners . '<br/>';
}
//Update database to reflect the updated tweets
$query = "UPDATE results AS a INNER JOIN bets AS b ON a.racecourse = b.course
WHERE a.twitter_pubstatus = 0 AND a.market = '$win' AND
b.type = '$userwin' AND a.winner = b.horse
SET a.twitter_pubstatus = 1;" //Update all of them at once
mysql_query($query) or die(mysql_error()); //Send query, unless fail
} else {
//If no results from initial query
echo "No Winners! :(";
}
Also, you should consider using mysqli over mysql, as mysql extension for PHP has been deprecated. See: Why shouldn't I use mysql_* functions in PHP?.

help with a query

i have a function where i get the ratings of the selected user by id,
it gets the ratings from one type of things, the ratings of a diff type of things and then does a+b
i know it's not very optimized but i'm focus on making all work...
this i do it like this
function votos_usuario($id){
$previa = "SELECT id FROM preguntas WHERE id_usuario = '$id'";
$r_previo = mysql_query($previa);
$ids_p = '0, ';
while($items_previos = mysql_fetch_array($r_previo)){
$ids_p .= $items_previos['id'].", ";
//echo "ids pregunta usuario: ".$items_previos['id']."<br>";
}
$ids = substr($ids_p,0,-2);
//echo $ids;
$consulta = "SELECT valor FROM votos_pregunta WHERE id_pregunta IN ( $ids )";
//echo $consulta;
$resultado = mysql_query($consulta);
$votos_preguntas = 0;
while($voto = mysql_fetch_array($resultado)){
$votos_preguntas = $votos_preguntas + $voto['valor'];
}
//$votos_preguntas= 0;
//$votos_preguntas = mysql_query("SELECT SUM(valor) FROM votos_pregunta WHERE id_pregunta IN (SELECT id FROM preguntas WHERE id_usuario = '$id')");
$previa_r = "SELECT id FROM recetas WHERE id_usuario = '$id'";
$r_previo_r = mysql_query($previa_r);
$ids_r = '0, ';
while($items_previos_r = mysql_fetch_array($r_previo_r)){
$ids_r .= $items_previos_r['id'].", ";
//echo "ids pregunta usuario: ".$items_previos['id']."<br>";
}
$ids = substr($ids_r,0,-2);
$consulta_b = "SELECT valor FROM votos_receta WHERE id_receta IN ( $ids )";
//echo $consulta;
$resultado_b = mysql_query($consulta_b);
$votos_recetas = 0;
while($voto_r = mysql_fetch_array($resultado_b)){
$votos_recetas = $votos_recetas + $voto_r['valor'];
}
$total = $votos_preguntas + $votos_recetas;
return $total;
}
Now the Question,
how can i do it to get all users ordered by rating desc ???? i just can't see it :S
SELECT uid, SUM(Votes)
FROM (
SELECT p.id_usuario uid, SUM(vp.valor) votes
FROM preguntas p JOIN votos_pregunta vp ON p.id = vp.id_pregunta
GROUP BY p.id_usuario
UNION ALL
SELECT r.id_usuario uid, SUM(vr.valor) votes
FROM recetas r JOIN votos_receta vr ON r.id = vr.id_receta
GROUP BY r.id_usuario
) rs
GROUP BY uid
ORDER BY SUM(Votes) DESC
instead of your php loop and all the sub queries, you can use this single query to get what you want:
SELECT (
SELECT SUM(vp.valor)
FROM preguntas p JOIN votos_pregunta vp ON p.id = vp.id_pregunta
WHERE p.id_usuario = '$id')
+ (
SELECT SUM(vr.valor)
FROM recetas r JOIN votos_receta vr ON r.id = vr.id_receta
WHERE r.id_usuario = '$id'
)
Also, when you're only using the associative keys in the result array, using mysql_fetch_assoc() is much, much faster than mysql_fetch_array().
Same applies to using mysql_fetch_row() instead when you're just using the numerical keys.

Categories