Hello all hope you are doing fine. i have been working on a point system where for each message you get points. everything is working fine until it comes to displaying the highest point to the modal with a table. I looked around the whole
stackoverflow but didnt found a solution, The problem is that I have the highest point of 119... but when I use the MAX function I get the lowest value which is 49.8 and it displays only one result .. and also i would like to get a hint or would like to know how can i select other columns in a query which has that MAX() command. Below is my php , I hope this much information is enough! Thank You...
<?php
$get = $mysqli->query("SELECT * FROM boom_users WHERE user_point > 20 LIMIT 5");
while($row = $get->fetch_assoc()){
echo "<table>";
echo "<tr>";
echo "<td><img class='avatar_menu glob_av' src='https://**********z.com/avatar/" . $row['user_tumb'] . "' ></td>";
echo "<td style='width:90%;' class='username " . $row['user_color'] . "'> " . $row['user_name'] . "</td>";
echo "<td>" . $row['user_point'] . "</td>";
echo "</tr>";
echo "</table>";
}
?>
Most likely explanation for MAX(foo) (SQL aggregate function) returning 49.8 when the expected result is 119 is that foo is defined as character type, rather than numeric.
Using the MAX() aggregate function will also "collapse" all of the rows into a single row. A MySQL-sepcific non-standard extension allows for other expressions in the SELECT list to be returned... the values returned for those expressions is not guaranteed to be from the same row that supplies the value returned for MAX().
Absent a concrete specification, including sample data and example of expected output, it's not possible to make a recommendation for an appropriate query. We're just guessing.
Here's a guess:
SELECT b.*
FROM boom_users b
WHERE ( b.user_point + 0 ) > 20
ORDER
BY ( b.user_point + 0 ) DESC
LIMIT 5
Note: the " + 0 " is a convenient MySQL shorthand to cause conversion of character types into numeric type.
Related
I'm going through Head First PHP and I've found this snippet of code in PHP.
It's supposed to display each row of records from a table containing the first_name, last_name and email.
while($row = mysqli_fetch_array($result))
{
echo $row['first_name'] . ' ' . $row['last_name'] .
' : ' . $row['email'] . '<br />';
}
The $row array contains the next row obtained by mysqli_fetch_array(). But how is this a condition to be checked by the while loop? What exactly does the while loop evaluate to be true/false, before running the inner code? And why exactly does the loop stop when the rows have exhausted? There isn't even a condition to check for an EOF!. So how exactly does this work?
Referring to the PHP Documenation, mysqli_fetch_array() "Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset." So, when there are no more results, it returns null which evaluates to false and ends the loop.
I am trying to put together a tool to help me with my upcoming fantasy hockey draft while also learning PHP. I am trying to create multiple lists on a page, one that displays the top 10 available players overall and then others that display the top 10 available players by position.
Here is my SQL query/code
include 'db/connect.php';
$sql='SELECT * FROM players WHERE pick IS NULL';
$players=$conn->query($sql);
if($players === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $players->num_rows;
}
Then later in the page I have a while loop that generates a table with the top ten players
while ($row = $players->fetch_array()) {
if ($i == 10) {
break;
}
echo "<tr>";
echo "<td>" . $row['Rank'] . "</td>";
echo "<td>" . $row['Player'] . "</td>";
echo "<td>" . $row['Team'] . "</td>";
...
And all that works fine. However, when I go to use the same method to generate a list containing only a certain position (C, RW/LW, etc...) it starts off where the top 10 player list ends. (See what I mean here: http://i.imgur.com/JApeftU.png)
I assume this has to do with the $players->fetch_array() however I do not know what the best way would be to get around it.
Any ideas?
Thanks!
Populate rows with all the players.
while ($row = $players->fetch_array()) { //→ $rows = $players->fetch_all();
$rows[] = $row;
}
You can use count() to get total amount of players in the array
$totalPlayers = count($rows);
Now you can loop through the array with for loop
for($i = 0; $i < $totalPlayers; $i++){
//echo out the stuff you want
echo $rows[$i]['player'];
}
Or only ten
for($i = 0; $i < 10; $i++){
//echo out the stuff you want
echo $rows[$i]['player'];
}
Well, for the future visitors, lured by the misleading title, the other answer is okay.
While for you personally, the other answer, as well as your question, is wrong.
And it's your idea on using databases is wrong in the first place.
A database is not like a text file, which you but bound to read every time from first line to last. Databases are quite intelligent and intended to return you the very data you requested.
Think it this way: what if your league will grow up to employ thousands of players. It will burden PHP script with lots of useless info, when it needs only a hundred of players.
So, it seems you need different queries to get differen data sets. First, you need a query
SELECT * FROM players WHERE pick IS NULL ORDER BY field DESC LIMIT 10
To get overall top ten, where field is whatever field you're using to determine the "top" player. And then several queries, each getting players for the certain position.
SELECT * FROM players WHERE pick IS NULL AND position=? ORDER BY field DESC LIMIT 10
Coming back to my project after putting it down for a while: Cycling through a query.
I understand that the below code can be cleaned up (PHP usage and table arrangement) and that MySQL commands are deprecated. ( I am working on that part).
But I can't see why I can't make this work. The print_r() gives Resource ID #5 error. My results show 2 tables, each with identical results all from the same course. I am expecting 8 tables, each table with a different course.
Should I use a while loop? if so how? I realize this is elementary, but this is still all new to me so please be gentle.
<?php
include 'inc.php';
$varVeh=$_POST['Veh_num'];
$sql_course="select course_num from hc_course";
$results_course=mysql_query($sql_course);
print_R($results_course);
foreach(mysql_fetch_array($results_course) as $rc)
{
$sql_HiScores = "SELECT c.course_name as course, e.distance as distance, e.score as score, e.time as time, e.user as User from hc_entries e left join hc_course c on e.course=c.course_num WHERE c.course_num=$rc and e.vehicle=$varVeh ORDER BY course, score DESC ";
$result_HiScores = mysql_query($sql_HiScores);
$sql_vehName="select Veh_name from hc_vehicle_type where Veh_num=$varVeh ";
$result_vehName = mysql_query($sql_vehName);
$vehName=mysql_fetch_assoc($result_vehName);
echo "<table><tr><th>Best Scores for ".$vehName['Veh_name']."</th> </tr></table>";
echo "<table border='1'>";
echo "<tr><th>Course</th><th>Score</th><th>Distance</th><th>Player</th><th>Time</th></tr>";
while($row = mysql_fetch_array($result_HiScores))
{
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
echo "<td>" .$row['User'] . "</td>";
}
echo "</table>";
}
?>
mysql_fetch_array just returns one row of the results, not all the rows. Your foreach loop is just looping over the columns in the first row of results.
If you want to process all the results, you should write:
while ($rc = mysql_fetch_array($results_course))
Then inside your loop, you use $rc['course_num'] to get the course from that row.
But I don't understand why you need that first loop at all. You're JOINing the hc_courses and hc_entries tables in the first query inside the loop. Why don't you just use that same query, but without the c.course_num = $rc condition, so it gets all courses at once instead of doing them one course at a time? Loop over those results, and start a new table every time the course number changes.
Here's the query for that:
SELECT c.course_name as course,
e.distance as distance,
e.score as score,
e.time as time,
e.user as User,
c.course_num as course_num
FROM hc_entries e
JOIN hc_course c ON e.course=c.course_num
WHERE e.vehicle=$varVeh
ORDER BY course, score DESC
The PHP then looks like:
$last_course = null;
while ($row = mysql_fetch_assoc($results_HiScores) {
if ($row['course_num'] !== $last_course) {
// New course number, start a new table
if ($last_course !== null) {
// Close out last table, if any
echo '</table>';
}
$last_course = $row['course_num'];
echo "<table><tr><th>Best Scores for ".$vehName['Veh_name']."</th> </tr></table>";
echo "<table border='1'>";
echo "<tr><th>Course</th><th>Score</th><th>Distance</th><th>Player</th><th>Time</th></tr>";
}
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
echo "<td>" .$row['User'] . "</td>";
echo "</tr>";
}
if ($last_course !== null) {
echo "</table>";
}
And you shouldn't do the hc_vehicle_type query inside the loop. It doesn't use any variables that change during the loop, it's just looking up the name of $_POST['Veh_num']. Just do it once and reuse the result inside the loop.
try:
foreach(mysql_fetch_array($results_course, MYSQL_ASSOC) as $rc)
{
....
}
if second argument is not given, MYSQL_BOTH is assumed, so array has column name, and column number 0,1...,n . so you traversed result set twice (column name and column number)
RTMF : http://us1.php.net/manual/en/function.mysql-fetch-array.php
and The print_r() gives Resource ID #5 error this is not an error!. return value of mysql_query() is result set. it's just a Resource of PHP internal structure.
I'm having problems with SQL query that returns no results instead of the data from the tables.
I have two tables on my DB, one is for Products and the other is Basket. The idea is to take the product id's from the basket and retrieve all the rest of the data from the product table. This is what i did:
$sql = sprintf("SELECT * FROM Basket");
$result = mysql_query($sql, $link);
while ($row = mysql_fetch_array($result)) {
$my_id = $row["Id"];
$prod_s=sprintf("SELECT * FROM Products WHERE Id='%s'",$my_id) ;
$prod= mysql_fetch_array($prod_s);
echo "<td>" . htmlentities($prod["Name"],ENT_QUOTES,"UTF-8") . "</td>";
echo "<td>" . htmlentities($prod["Size"]) . "</td>";
.
.
.
The table is being created but all fields are empty.
Thank you!
First of all, your current code is vulnerable to second-level SQL injections: if one of the IDs in the database is a malicious string (e.g. the good old ; DROP DATABASE foo), you're screwed.
Now, your actual problem is that you're not actually sending the second query to the SQL server. You'll want to run mysql_query() on it and use the result handle with mysql_fetch_array. You're already doing it correctly with the initial query. Just do the same thing again.
Finally, you might want to know that all of this can be done in a single SQL query, using joins. You may want to ask your favourite search engine about those. Good luck!
I think you still have to add a mysql_query for prod_s.
$my_id = $row["Id"];
$prod_s=sprintf("SELECT * FROM Products WHERE Id='%s'",$my_id) ;
$prod_q=mysql_query($prod_s);
$prod= mysql_fetch_array($prod_q);
echo "<td>" . htmlentities($prod["Name"],ENT_QUOTES,"UTF-8") . "</td>";
echo "<td>" . htmlentities($prod["Size"]) . "</td>";
I am using a database that was already created and I can access, but do not have the permission to alter the database at all.
I am using the query
select last_count, query, job_id from twitterinblack46.job where job_id in ('.$job_id_all.') order by last_count desc;
to call three columns (last_count, query, and job_id) and display them in a table.
This query works as I want it to, but the only issue is the query column displays data with either a "%23","%40","%20", or "q=" in front of the desired data.
I need to figure out how to get rid of these strings before displaying the table.
Here is the while statement used to generate the table:
while($row = mysql_fetch_array($result)){
echo"<tr>";
echo "<td>" . $row["job_id"] . "</td>";
echo "<td>" . $row["last_count"] . "</td>";
echo "<td>" . $row['query'] . "</td>";
echo "<tr>";
}
echo "</table>";
I have created this query:
select replace(replace(replace(REPLACE(query,'%23', ''),'%40',''),'q=',''),'%20','') from job;
to get rid of these characters and it works perfectly as I need it, but how can I incorporate this query into my other $result before creating the table?
You can remove the offending strings when printing the table:
echo "<td>" . str_replace(array('%23', '%40', '%20"', 'q='), '', $row['query']) . "</td>";
(If you want to limit removal to only characters at the beginning of the string you can look at preg_replace)
$lst_search = array("%23", "%40", "%20", "q=");
$query = str_replace($lst_search, "", $row["query"]);
Then use $query in place of $row["query"] when creating the table.