MySQL and HTML: Ordering a row based on a specific value [duplicate] - php

This question already has answers here:
MySQL query order by multiple items
(3 answers)
Closed 8 years ago.
I'm working on a little downloads area of a website where people can submit different themes, and the community can rate them with a + or - 1 (very similar to Stack Overflow).
I currently am pulling data from a MySQL database - much of that isn't terribly important to the question - but here is what my final code and table looks like:
while($record = mysql_fetch_array($myData)){
echo '<tr>';
echo '<td>' . $record['votes'] . '</td>';
echo '<td>' . $record['name'] . '</td>';
echo '<td>' . $record['author'] . '</td>';
echo '<td>' . $record['description'] . '</td>';
echo '</tr>';
}
I would like to order each table row based on the value of the <td> called votes. I understand this is a bit broad since I don't have code supplied, but I've searched the web and found nothing about what I'm attempting to do. I'm sure it can be done by modifying the while function, but I'm not sure how.
If it proves to be any help, my full PHP code is below:
<?php
$con = mysql_connect('host','name','password');
mysql_select_db('database',$con);
$sql = "SELECT * FROM themer";
$myData = mysql_query($sql,$con);
echo '<table>';
while($record = mysql_fetch_array($myData)){
echo '<tr>';
echo '<td>' . $record['votes'] . '</td>';
echo '<td>' . $record['name'] . '</td>';
echo '<td>' . $record['author'] . '</td>';
echo '<td>' . $record['description'] . '</td>';
echo '</tr>';
}
echo '</table>';
?>
EDIT: I apparently was searching for the wrong stuff when I researched this - I didn't know mySQL had the functionality described in the answers below. Now that I know what was up, this might be a possible duplicate - mysql query order by multiple items

The simplest option is to pass the responsibility down to the database level. This is also most likely the best option since you can then add an index; database engines are quite good at querying and ordering results. Add an ORDER BY clause to your query, making your query:
SELECT *
FROM themer
ORDER BY votes
To order this from highest to lowest, you'll need to reverse the sort order. Do this by adding a DESC keyword:
SELECT *
FROM themer
ORDER BY votes DESC
Note: new code should really not be using the mysql_ PHP functions anymore. They are deprecated, and for good reason. Good alternatives include mysqli and PDO.

$sql = 'SELECT * FROM themer
ORDER BY ABS(votes) DESC';

Related

Can't get JOIN statement to return results

I'm actually trying to use JOINS for the first time and I'm having a tough time getting it to go. I have two tables...stories and wp_users and I'm trying to return all stories and include the display_name of the user from users along with each story.
This code works fine to get all results from stories and show story name and genre:
$results = $wpdb->get_results("SELECT * FROM stories where stories.active = 1");
foreach ($results as $row) {
echo '<tr>';
echo '<td>' . $row->story_name; '</td>';
echo '<td>' . $row->genre; '</td>';
Now I want to also include the name of the user who wrote the story ("display_name" from wp_users table)
After reading many sites about joins the below approach seemed best, but sadly it returns no results:
<?php
global $wpdb;
$sql = "SELECT stories.story_name, stories.genre, wp_users.display_name as display FROM
stories LEFT JOIN wp_users ON stories.ID=wp_users.ID where stories.active = 1";
$results = $wpdb->query($sql);
if($results->num_rows) {
while($row = $results->fetch_object()) {
echo "{$row->story_name} {$row->genre} {$row->display}<br>";
}
}
else {
echo 'No results';
}
Here are some suggestions that might help:
In your first code snippet, you are using $wpdb->get_results() while in your second snippet there is $wpdb->query(). There might be some difference in the returned value and the meaning of the parameters.
Find out about the method that asks for error messages after querying and use it to dump the message. Often if no rows are returned it is because there was an error.
Make sure num_rows really is got from $results. Here (http://codex.wordpress.org/Function_Reference/wpdb_Class) it says the expression is $wpdb->num_rows. (You'll find it by searching the site for 'num_rows', it'll scroll down.)
Try to use the MySQL Command Shell or some PhpMyAdmin sandbox to check the query. Entering the SQL directly will show typos and other problems like "unknown column" in the SQL code, and it allows to edit fast. Joining syntax varies between databases, yet your LEFT JOIN is ok to MySQL. There seems to by no problem on the syntactic level.
This docu http://codex.wordpress.org/Function_Reference/wpdb_Class may help to come clear with the code.
Got it!
<?php
global $wpdb;
$results = $wpdb->get_results("SELECT stories.story_name, stories.genre,
wp_users.display_name FROM stories LEFT JOIN wp_users ON stories.ID=wp_users.ID where
stories.active = 1");
if ($results) {
echo '<table>';
echo '<tr>';
echo '<td><b>Story Name</b></td>';
echo '<td><b>Genre</b></td>';
echo '<td><b>Last User on this Website to See</b></td>';
echo '</tr>';
foreach ($results as $row) {
echo '<tr>';
echo '<td>' . $row->story_name; '</td>';
echo '<td>' . $row->genre; '</td>';
echo '<td>' . $row->display_name; '</td>';
echo '</tr>';
}
echo '</table>';
}
?>

Pull rows with only certain data in them PHP & Mysql

I'm trying to pull information and display it in a table form on a php page i have a mysql DB i have something like below which list everything in the table but i would like to have it only show certain information if a certain data is present
Columns i would like to display on the page
object_id, Name and, wish.
but i only want rows from the DB to be displayed if a column
wishState is ("pending")
this is what i have scoured around to find so far wich brings everything in.
$query="SELECT * FROM MY_TABLE";
$results = mysql_query($query);
while ($row = mysql_fetch_array($results)) {
echo '<tr>';
foreach($row as $field) {
echo '<td>' . htmlspecialchars($field) . '</td>';
}
echo '</tr>';
}
Thanks Ryan
The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, is officially deprecated as of PHP v5.5.0 and will be removed in the future. So please don't use mysql_* anymore.
//selects data where wish is pending
$query="SELECT * FROM `MY_TABLE` WHERE `wish`='pending'";
$results = mysqli_query($your_db_connection, $query) or exit(mysqli_error());
while ($row = mysqli_fetch_array($results)) {
//show only object_id, name and wish
echo '<tr>';
echo '<td>' . $row['object_id'] . '</td>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['wish']. '</td>';
echo '</tr>';
}
$query="SELECT * FROM MY_TABLE WHERE `wish`='pending'";
That should work based on the information you gave us. WHERE tells the database to search for rows WHERE the column WISH is equal to "pending".

Creating a HTML table with MYSQL fetching data doesn't work

I'm attempting to create a dynamic table with MYSQL's function: while(mysql_fetch_assoc).. However, when it fetches more than one result, it doesn't create the table anymore (or fill in the tags. Excuse me for explaining this incorrectly)
This is my code. Ignore the Dutch words :)
$sql2 = mysql_query("SELECT * FROM kostendb WHERE ProjectID = '$_GET[id]'") or die (mysql_error());
echo '
<table border="1" style="width:60%">
<tr>
<th>Kostencode</th>
<th>Datum</th>
<th>Bedrag</th>
</tr>';
while($res = mysql_fetch_assoc($sql2))
{
echo '<tr>';
echo '<td>' .$res['KostenID']. '</td>';
echo '<td>' .$res['Datum']. '</td>';
echo '<td>' .$res['Bedrag']. '</td>';
echo '</tr>';
}
echo '</table>';
When it finds more than one result, the while-loop doesn't do anything. When it finds just one result, it works fine.
What is causing this, and how can I fix this?
I've checked out an example script, but it's exactly using my method.
Thanks
You might have mixed mysql with mysqli.
Choose one, don't mix and this might fix your problem.
make a variable like $project = $_GET['ID'];
then put in sql statement as ....WHERE Project_ID = $project");
Try this

none value in php dropdown list

Is there any simple way to add none value in a dropdown list in php?? I tried the below but it doesn't work. It shows all lname values but not the 'None'.
I do not want to enter 1 none value in database and retrieve it. So if it is possible through php itself.
while ($row = mysqli_fetch_array($result))
{
echo "<option value=None>" . $row['lname'] . "</option> <br>";
}
Please help me.
Just add the "none"-option above the others.
echo '<option value="">None</option>';
while ($row = mysqli_fetch_array($result))
{
echo '<option value="' . $row['lname'] . '">' . $row['lname'] . '</option>';
}
Two things odd here:
- You need quotes around the None in value=None --
- a inside of a select options list isn't ever a smart thing to do.

php, sort an array from mysql

I'm running a query on three columns; one column contains text, the other two contain numbers. I do a calculation on these numbers to get a new number called $average. I then spit out the result to an html table. The rows in the table are sorted in the order they come out of the database. I'm trying to sort the table so that the data is displayed from highest $average to lowest (while still be correctly associated with the correct text value from the first column).
I've tried some asort and foreach stuff, but I've only succeeded in making a mess of errors.
Any ideas as how I go about this?
Thanks.
This is the current state of play:
/ db query
if (!$result = mysqli_query($link,"SELECT quiz_name,
quiz_attempts,
cumulative_score
FROM scoredata")) {
echo("There was a problem: " . mysqli_error($link));
exit();
}
...
// got results?
if(mysqli_num_rows($result) >= 1) {
$output = "";
$output .= "<table>\n";
$output .= "<tr><th>Quiz name</th> <th>Played</th> <th>Avg. score</th></tr>\n";
while($row = mysqli_fetch_array($result)) {
$output .= "<tr><td>".str_replace('_', ' ', $row['quiz_name']) . "</td>";
$output .= "<td>" . $row['quiz_attempts'] . "</td>";
// calculate average score
$average = $row['cumulative_score']/$row['quiz_attempts'];
$output .= "<td>" . round($average,2) . "</td></tr>";
}
$output .= "</table>\n";
echo $output;
}
...
You can do calculation and sorting in your query:
SELECT
quiz_name,
quiz_attempts,
cumulative_score,
(cumulative_score/quiz_attempts) as score_avg
FROM scoredata
ORDER BY score_avg DESC
You can
let the db do the sorting (as suggested by other posters)
sort the data yourself (as you are trying to do)
let the user sort the data via JavaScript functions. My favourite is
http://www.javascripttoolbox.com/lib/table/
Make this your query
SELECT quiz_name,
quiz_attempts,
cumulative_score,
cumulative_score / quiz_attempts as avg_score
FROM scoredata
ORDER BY avg_score

Categories