Order while loop data - php

I'm making a ranking system. But what I want is to order the results I get ($kn) from highest to lowest. How can I do this?
include "includes/core.inc.php";
require "includes/connect.inc.php";
$id = $_GET["id"];
$query = "SELECT * FROM submitted WHERE id= '$id'";
$query_run = $db->query($query);
while($row = mysqli_fetch_assoc($query_run)){
$name= $row["name"];
$sql = "SELECT * FROM submitted WHERE name= '$name' AND pending = 'Accept'";
$sql_run = $db->query($sql);
$count = $sql_run->num_rows;
$nums= "SELECT * FROM ranking WHERE name= '$name'";
$nums_run = $db->query($nums);
$num = $nums_run->num_rows;
$kn = ($count * 0.4) + (($num * 0.2) * 3);
echo '$name';
echo '$kn';
}

Looping over a list and querying each element is almost never a good idea. Instead, you can move the entire logic to the query, and then sort it there:
$query =
"SELECT s.name AS name, (cnt_submitted * 0.4) + ((cnt_ranking * 0.2) * 3) AS kn
FROM (SELECT name, COUNT(*) AS cnt_submitted
FROM submitted
WHERE id = '$id' AND
pending = 'Accept'
GROUP BY name) s
JOIN (SELECT name, COUNT(*) AS cnt_ranking
FROM ranking
GROUP BY name) r ON r.name = s.name
ORDER BY 2 DESC";
$query_run = $db->query($query);
while ($row = mysqli_fetch_assoc($query_run)) {
$name = $row["name"];
$kn = $row["kn"];
echo '$name';
echo '$kn';
}
Note:
The $id variable should probably be a bound variable in a prepared statement to safe-guard against SQL-injection attacks.
I left it as it was in the OP, though, since this is not the point of the question and I don't want to add additional confusion.

You can do it also in PHP:
$result = [];
while (...) {
.....
$kn = ($count * 4) + (($num * 2) * 30);
$result[] = [
'rank' => $kn,
'name' => $name
];
}
usort($result, function($a, $b) {
return $b['rank'] - $a['rank'];
});

Related

PHP SQL inner Join bool(false)

I am attempting to get a 'total weight' for items a character is carrying. I am doing this by selecting the quantity of items in the characteritem table and comparing the weight which is set in the item table and they are joined by the iid (item id) column
I have tried a lot of different methods to no avail so I have looked up join statements. The issue I have is why the $result would return bool(false) and then how I can get the weights to add up afterwards.
Here is the code I am working with currently:
$sql = "SELECT *
FROM `characteritem` WHERE `owner` = '$user'
INNER JOIN item ON characteritem.iid=item.iid";
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$iid = $row['characteritem.iid'];
$quantity = $row['characteritem.quantity'];
$itemweight = $row['item.itemweight'];
$itemtotal = $itemweight + $itemweight;
echo $itemtotal;
}
}
var_dump($result);
SQL is working fine now. I have got the weight and quantity and gotten the individual results. How would I get the values to add together for $itemtotal?
$sql = "SELECT *
FROM `characteritem`
INNER JOIN item ON characteritem.iid=item.iid
WHERE `owner` = '$user'";
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$iid = $row['characteritem.iid'];
$quantity = $row['quantity'];
$itemweight = $row['itemweight'];
$itemtotal = $itemweight * $quantity;
echo $itemtotal;
}
}
Your SQL sintax is wrong, try
$sql = "SELECT *
FROM `characteritem`
INNER JOIN item ON characteritem.iid=item.iid
WHERE `owner` = '$user'";
Try This
$sql = "SELECT *
FROM `characteritem`
INNER JOIN item ON characteritem.iid=item.iid" WHERE `owner` = '$user';
$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$iid = $row['characteritem.iid'];
$quantity = $row['characteritem.quantity'];
$itemweight = $row['item.itemweight'];
$itemtotal = $itemweight + $itemweight;
echo $itemtotal;
}
}
var_dump($result);

Unable to get key value from a mysql multi-dimensional array

I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}

Random row selection using MySQL returns NULL

I am trying to get a random row from MySQL table but all three attemps:
$query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
$query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
give a NULL result in mysql_query($query).
Higher up my PHP code I obtain a row from the same table OK by specifying WHERE, so I don't understand why I can't retrieve a random one.
Here is the code snippet:
$query = "SELECT uid,clu FROM uable WHERE un = '$un'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$resultid = mysql_fetch_assoc($result);
$uid = $resultid['uid'];
file_put_contents('debugging.txt',__LINE__.' - $uid = '.var_export($uid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE uid = $uid AND cn = '$cn'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$cr = mysql_fetch_assoc($result);
$cid= $cr['cid'];
file_put_contents('debugging.txt',__LINE__.' - $cid= '.var_export($cid,true).PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM fable WHERE cid= '$cid'";
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
file_put_contents('debugging.txt',__LINE__.' - $result = '.var_export($result,true).PHP_EOL,FILE_APPEND);
$fr = mysql_fetch_assoc($result);
file_put_contents('debugging.txt',__LINE__.' - $fr = '.var_export($fr,true).PHP_EOL,FILE_APPEND);
echo '<form action="'.$_SERVER['PHP_SELF'].’" method="post">';
if (!$fr) {
$o= $cn;
while ($o= $cn) {
// $ac = mysql_query("SELECT * FROM table") or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
// $num_rows = mysql_num_rows($ac);
//file_put_contents('debugging.txt',__LINE__.' - $num_rows = '.$num_rows.PHP_EOL,FILE_APPEND);
// --$num_rows;
// $query = "SELECT cid FROM table LIMIT 1 OFFSET ".rand(1,$num_rows);
$query = "SELECT cid FROM table OFFSET RANDOM() * (SELECT COUNT(*) FROM table) LIMIT 1";
// $query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
$resultid = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($resultid);
$o= $opr['cn'];
}
file_put_contents('debugging.txt',__LINE__.' - $query = '.$query.PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $resultid = '.var_export($resultid,true).PHP_EOL,FILE_APPEND);
file_put_contents('debugging.txt',__LINE__.' - $op[\'cid\'] = '.$op['cid'].PHP_EOL,FILE_APPEND);
$query = "SELECT * FROM table WHERE cid= ".$op;
$result = mysql_query($query) or die(sqlerror(__LINE__,mysql_errno(),mysql_error()));
$opr = mysql_fetch_assoc($opr);
$o= $opr['cn'];
$od= $opr['description'];
echo '<p>'.$op;
if ($od<> '') {
echo ','.$odesc;
}
echo '</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
} else {
echo '<p>'.$fr['p'].'</p>';
echo '<input type="submit" name="continue" id="continue" value="Continue">';
}
echo '</form>';
The resulting debugging.txt:
24 - $uid = '4'
29 - $cid = '21'
32 - $result = NULL
34 - $fr = false
These queries look OK, but I think you're starting at the wrong place. When you're uncertain how to frame something in SQL, open up a SQL client like SequelPro or Navicat and try writing a few queries by hand until you get the result you want. (Also this gives you a chance to double-check the contents of relevant tables and ensure the expected data are there.) Then you can go back into the PHP with full confidence that the SQL code is correct, so if there's a problem it must be with the PHP (either the variables you inject into a Mysql statement, or the way you call that statement).

Get highest sum value from two tables

Here is my code:
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
<tr> <?php echo $sum; ?></tr>
}while($row_query1 = mysql_fech_assoc($result));
I need to get the highest value of $sum from this loop. Can anyone help?
You can do like this.. take a temporary variable($temp) which can have check upon the sum variable($sum).
$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);
$temp = 0;
do{
$user = $row_query1['user'];
$query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
$result2 = mysql_query($query2);
$row_query2 = mysql_fetch_assoc($result2);
$sum = $row_query1['total1'] + $row_query2['total1'];
if($temp < $sum)
$temp = sum;
echo "<tr>$sum</tr>";
}while($row_query1 = mysql_fech_assoc($result));
echo "maximum sum :".$temp;
I would advice doing a JOIN instead of performing the sub queries yourself:
select user, sum(column) + sum(column1) as total
from table1
INNER JOIN table2 ON names = user
GROUP BY user
The rest should be straightforward in code.

Creating an array of IDs from a while loop

Im trying to generate an array but not sure how to go about it.
I'm currently getting my data like so:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test#test.com'");
$row = mysql_fetch_array($query);
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT * FROM usersettings WHERE userId = ".$row['userId']." AND usersettingCategory".$row1['categoryId']." LIKE 'y'");
$isyes = mysql_num_rows($query2);
if($isyes > 0){
$cat1 = mysql_query("SELECT * FROM shops WHERE shopstateId = 1 AND (categoryId1 = ".$row1['categoryId']." OR categoryId2 = ".$row1['categoryId']." OR categoryId3 = ".$row1['categoryId'].")");
$cat1match = mysql_num_rows($cat1);
if($cat1match > 0){
while($cat1shop = mysql_fetch_array($cat1)){
$cat1msg = mysql_query("SELECT * FROM messages WHERE shopId = ".$cat1shop['shopId']." and messagestateId = 1");
while($cat1msgrow = mysql_fetch_array($cat1msg)){
echo $cat1msgrow['messageContent']." - ".$cat1msgrow['messageCode'];
$cat1img = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$cat1shop['shopimageId']);
$imgpath = mysql_fetch_array($cat1img);
echo " - ".$imgpath['shopimagePath']."<br/>";
}
}
}
}
}
But this can cause duplicates when a user has all 3 of a shops categories picked in their preferences. I am trying to find a way to just pull the message ID out instead of the whole thing and put it into an array giving me, for example:
1,3,5,7,1,3,5,2,4,7,8
Then I can just run a separate query to say get me all messages where the ID is in the array, but i am unsure of the most constructive way to build such an array and examples of array from a while loop I have seen do not seem to be what I am looking for.
Is there anyone out there that can push me in the right direction?
Can't help with this code. But if you want an array from a query without duplicate result, you can use " select DISTINCT (id) " in your query or for more simple solution :
$id_arr = array();
$sql = mysql_query("select id from id_table");
while ($id_result = mysql_fetch_array($sql) {
$id = $id_result['id'];
if (!in_array($id, $id_arr)) {
$id_arr[] = $id;
}
}
I have found a much easier way to create the required result. I think at 6am after a hard night coding my brain was fried and I was making things a lot more complicated than I needed to. A simple solution to my issue is as follows:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test2#test2.com'");
$row = mysql_fetch_array($query);
$categories = "(";
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT usersettingCategory".$row1['categoryId']." FROM usersettings WHERE userId = ".$row['userId']);
$row2 = mysql_fetch_array($query2);
if($row2['usersettingCategory'.$row1['categoryId']] == y){
$categories .= $row1['categoryId'].",";
}
}
$categories = substr_replace($categories ,")",-1);
echo $categories."<br />";
$query3 = mysql_query("SELECT * FROM shops,messages WHERE shops.shopId = messages.shopId AND messages.messagestateId = 1 AND (shops.categoryId1 IN $categories OR shops.categoryId2 IN $categories OR shops.categoryId3 IN $categories)");
while($row3 = mysql_fetch_array($query3)){
$query4 = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$row3['shopimageId']);
$row4 = mysql_fetch_array($query4);
echo $row3['messageContent']." - ".$row3['messageCode']." - ".$row4['shopimagePath']."<br />";
}

Categories