Member Avatar for LastMitch

Hi

I have a question regarding Ascending Order and Descending Order.

I want to learn how to write a Ascending Order and Descending Order on any list.

For example:

I want to create a booklist and I want to organized it by a library code system.

Category----ID-----Arthur
History-------123----Scholastic
Art------------456----Da Vinci
Math---------789----Newton

This is something I recently learn from another thread I created regarding about if & else statement.

Here is a code:

1) category.php
2) list.php

The 'category' is from the database and the script is called "category.php"

This script is called "list.php" which I'm trying to learn and understand how to pull the info.

( - ) : I'm not to sure how to write it or I don't know what to put in it!

<?php

$orderBy = 'Arthur';
$orderBy = 'Category ';
$orderBy = 'ID';
$orderSort = 'ASC';
$orderSort = 'DESC';

if (-){
      $orderBy = (-);
      $orderSort = (-) == 'ASC' ? 'ASC' : 'DESC';
      }
?>

HTML:

<?php
if ( (-) =='Arthur' and (-) == 'ASC'):
<a href="category.php?ord=Arthur&se=DESC"><span class="style1">Arthur</span></a>
else
<a href="category.php?ord=Arthur&se=ASC"><span class="style1">Arthur</span></a>
endif;
?>

I really apprecaited if someone explain to me how to write it correctly.

Recommended Answers

All 25 Replies

Dude,
if you want to sort by desc, or asc, then just have an html option where the values are <?php self...?sort=asc

then have your php code

if(!isset('something')) {
mysql code ORDER BY ASC
}

check out www.w3schools.com. really good play to begin learning.

Member Avatar for LastMitch

Hi fobos,

Thank for the reply but I don't quite understand what you wrote? I don't want to be rude.

You have to specfic:

> if(!isset('something')) {
> mysql code ORDER BY ASC
> }

This

www.w3schools.com

good resource to learn the basic.

The issue I have is a bit more complicate. I have 2 different files. I wish it was 1 file that I can put everything in it but not in this case.

Hey,

So let's say I have a list of names:

    $narray[0]="Alfred";
    $narray[1]="Robert";
    $narray[2]="Deepak";
    $narray[3]="Teresa";
    $narray[4]="Joshua";
    $narray[5]="Chandni";
    $narray[6]="Sadiq";
    $narray[7]="Vladimir";

And with this list, I wanted to sort the names AND then print the names by ASC, or DESC then we need to handle what is being passed through the url (Take the value after the question mark):

 <?php

    $narray[0]="Alfred";
    $narray[1]="Robert";
    $narray[2]="Deepak";
    $narray[3]="Teresa";
    $narray[4]="Joshua";
    $narray[5]="Chandni";
    $narray[6]="Sadiq";
    $narray[7]="Vladimir";

        if(!isset($_GET['se'])) die('Please enter the type of sort');

          $type = $_GET['se'];

        //$type = 'ASC';
        // Or use a switch statement
        if($type=='DESC')
        {
            rsort($narray);
        }else if($type=='ASC')
        {
            sort($narray);
        }

        for($i=0; $i<8; $i++)
        {
            print $narray[$i] . " ";
        }
    ?>

Then whichever of the values you put into the url:

site.com/names.php?se=DESC

Vladimir Teresa Sadiq Robert Joshua Deepak Chandni Alfred

site.com/names.php?se=ASC
Alfred Chandni Deepak Joshua Robert Sadiq Teresa Vladimir

Hope this helps :)

Member Avatar for LastMitch

@ phorce

Thanks for the reply. I'll look over and see how it compile.

Member Avatar for LastMitch

@ phorce

I already have database (it's on the server) I don't think I need to create another list?

$narray[0]="Alfred";
$narray[1]="Robert";
$narray[2]="Deepak";
$narray[3]="Teresa";
$narray[4]="Joshua";
$narray[5]="Chandni";
$narray[6]="Sadiq";
$narray[7]="Vladimir";

The script that you wrote doesn't really pull the data from the base.

<?php
if(!isset($_GET['se'])) die('Please enter the type of sort');
$type = $_GET['se'];

//$type = 'ASC';

// Or use a switch statement

if($type=='DESC'){
rsort($narray);
}else if($type=='ASC'){
sort($narray);
}for($i=0; $i<8; $i++){
print $narray[$i] . " ";}
?>

I really appreciated help.

Member Avatar for diafol

Is Arthur the Author ?:)

//THESE ARE THE POSSIBLE VALUES OF YOUR GET VARIABLES TO CHECK AGAINST
$ordsby_allowed = array('Author','Category','ID'); //put these in order of importance
$ordse_allowed = array('DESC','ASC'); //put these in order of importance

//CHECK THAT THERE IS A URL QUERYSTRING
if(!empty($_GET)){
    //CLEAN ALL QUERYSTRING VALUES
    $get = array_map('mysql_real_escape_string',$_GET);
    //CHECK FOR EXISTENCE OF VALID ord AND se - ACCEPT IF EXIST OR APPLY DEFAULT VALUE (1st VALUE IN ALLOWED ARRAY) IF NOT
    $ord = (isset($get['ord']) && in_array($get['ord'],$ordsby_allowed)) ? $get['ord'] : $ordsby_allowed[0];
    $se = (isset($get['se']) && in_array($get['se'],$ordse_allowed)) ? $get['se'] : $ordse_allowed[0];
}else{
    //NO QUERYSTRING VALUES THEREFORE APPLY DEFAULTS
    $ord = $ordsby_allowed[0];
    $se = $ordse_allowed[0];    
}
//RUN QUERY
$result = mysql_query("SELECT * FROM `booklist` ORDER BY `$ord` $se");
//...(carry on)...

I should point out that in_array() makes a case-sensitive comparison, so 'desc' and 'id' will NOT match. This is a trivial matter to overcome - you can apply the array_map to a user function and apply both mysql_real_escape_string and strtolower and then make all data in the allowed arrays lowercase. MYSQL statements are not case-sensitive.

commented: The Code Works ! Thanks Ardav! +2

If I understand correctly: you want to construct an SQL statement depending on a field to be sorted on and the sort direction (ASC, DESC)?

If the above is true then the simplest option is to have the field to be sorted on and the sort direction in a querystring (using a form with method="get" - I hope you know how to do this).

Then just check whether both values have been passed and construct a query:

// if field to sort and sort order have been set
if(isset($_GET['sortfield']) and isset($_GET['sortdir']) {
    // assign querystring values to variables
    // all the security stuff is omitted here for simplicity
    // but do not to forget to check for correct values yourself!!!
    $sortfield = $_GET['sortfield']; 
    $sortdir = $_GET['sortdir']
} else {
    // prepare default values
    $sortfield = 'Category';
    $sortdir = 'ASC';
}
$query = "SELECT Category, ID, Arthur FROM booklist ORDER BY $sortfield $sortdir"
// do connecting to the db, reading from the table, displaying results etc
// ...

I havent noticed ardav has already replied with more detailed example some minutes before me so do not pay too much attention to my reply :-)

Member Avatar for LastMitch

@ broj1

Thanks for the reply! I'll look over it anyway and see how it works. Thanks!

Member Avatar for LastMitch

@ ardav

I never knew your were Dudley Moore fan? You know if you have some hair on your profile you defintely look like him!

Well, all joking aside ...

Thanks for the reply! I really appreciated that you took your time again write and post another script!

I will take a look at it and configure it to the script I have.

You mention:

I should point out that in_array() makes a case-sensitive comparison, so 'desc' and 'id' will NOT match.

I will take note of that if that comes up! Thanks!

Member Avatar for diafol

You know if you have some hair on your profile

That's my grandad. I'm 17 and still in school. :)

Member Avatar for LastMitch

@ broj1

You're right about the "Ardav" example! It does have more detailed than the one you have and you have the same if & else statement as "Ardav"! I appreciated that you took time writing! Thanks!

A further impovement would be to use Ajax for sorting the data but only if you have significant amount of other content on the page. When changing sort order or field to sort by, using Ajax, only the sorted data would be refreshed not the whole page. If you have only the booklist data on the page it is not worth bothering with Ajax.

If you are familiar with jQuery, I guess Ajax is quite simple to implement. See http://api.jquery.com/jQuery.ajax/.

Member Avatar for LastMitch

@ broj1

I used Ajax a couple for times. I'm not a big fan of it. The script I used was a image script that is in Ajax. Unfortunately, it doesn't work in IE and Firefox (the image script that is in Ajax). I never used other scripts in Ajax. But thanks for the suggestion.

Member Avatar for LastMitch

@ ardav

That's my grandad. I'm 17 and still in school. :)

You and "Veedeoo" are PenPals!

Actually you look like "Jason Statham", it won't shock me if a bunch of ladies come up to you and ask if you are "Jason Statham! Most likely you say "YES" and you are a dog~!

But all joking a side,

This is script is bit challenging. I try to compile it, it comes up nothing. I'll still work on it a bit and get back to you or maybe just post the errors I'm getting. But thanks.

Member Avatar for LastMitch

I apologies for taking so long to reply back.

This is the error I'm keep getting:

"Fatal error: Can't use function return value in write context in ..."

I try to dump it (I learn this from "Biiim" a few threads ago)

<?php
$expected_array_got_string = 'somestring';
var_dump(isset($expected_array_got_string['some_key']));
var_dump(isset($expected_array_got_string[0]));
?>

This is what I got:

bool(false)
bool(true)
bool(true)
Member Avatar for LastMitch

I try to use this to test out the isset

<?php
function isset_or(&$check, $alternate = NULL)
{
return (isset($check)) ? (empty($check) ? $alternate : $check) : $alternate;
} 
?> 

isset() returns TRUE if a value is NULL? That does sound right to anyone?

I should point out that in_array() makes a case-sensitive comparison, so 'desc' and 'id' will NOT match.

I kept in mind what "Ardav" mention a few post ago that it might be case sensitive?

isset() function returns either true or false. If the checked variable is NULL or is not set , isset() returns false. That is what the PHP manual claims.

Maybe you should post the last version of your code. It would be easier to try to find the bug.

Member Avatar for diafol

isset is fine a lot of the time, but $_GET and $_POST are always set - not the individual array items, but the superglobals themselves. so testing for isset($_POST) should always give a true.

Try this out in a blank page to see what I mean:

session_start();
echo "GET:<br />";
var_dump($_GET);
echo "<br />POST:<br /> ";
var_dump($_POST);
echo "<br />SESSION:<br />";
var_dump($_SESSION);
echo "<br />COOKIE:<br />";
var_dump($_COOKIE);

So testing for empty() may be safer. Of course an isset() will still work with a specified superglobal item. AS broj1 states - there are slight differences between isset and empty - it depends on the test conditions that you apply, e.g. what do you expect for 'false',0,NULL etc...

AFAIK and you'll need to check the manual:

isset() will return true for everything except for: var not set (obviously) and var = NULL
empty() will return true for when var = 0, var = NULL, var = false, var not set

commented: Thanks for the example, very detail! +2
Member Avatar for LastMitch

@ broj1

Thanks for the reply again! Yes, it does say that in the manual.

Member Avatar for LastMitch

@ ardav

I apologies for replying so late again. Thanks for the replying again! I had to visit my mom because it was Mother's day over the weekend. I look over the code you wrote and it makes alot of sense! I will put that code in the blank page and see how it goes.

AFAIK? I think you text too much as far as i know

Ardav, I can't call you Diafol

oherwydd nad ydych yn y Diafol!

I'm a Christian I'm not to fond of that word ...

I'll double check my work and get back to you if I have any issue.

Member Avatar for diafol

oherwydd nad ydych yn y Diafol!
I'm a Christian I'm not to fond of that word ...

I'm not and I am :)

Member Avatar for LastMitch

@ Ardav

I'm testing the database with the code you wrote. It actually dump the whole database. True or False. I'll let you when I'm done.

Rwydd hynt iddo Ardav!

Member Avatar for LastMitch

@ Ardav

I just want to "Thank You" for being patience and writing the code and taking your time to explaining it to me how it works and also showing me how to test out the database. I'm a pretty slow learning, it does take me a while to grasp how languages works. I think testing out the database was a bit challenge because my MYSQL is not that good! But I resolve the issue with that and the simple code that you wrote works great! The Ascending Order and Descending Order or button is functional now!

Member Avatar for diafol

Sweet :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.