Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Trimming "The " from mysql query.

I am using a mysql database where I have names that I want to sort alphabetically. The problem is, some of these names contains "The " in front of them. I know that I can use ltrim to remove it but I don't really know on how to use it.

here is what I have.

require_once("../inc/database.php");

try {
    $results = $db->query('SELECT * FROM hotels ORDER BY name');
} catch(Exception $e) {
    echo $e->getMessage();
    die();
};

$hotels = $results->fetchAll(PDO::FETCH_ASSOC);

require_once("../inc/header.php"); 

   foreach($hotels as $hotel){
     echo '<option value="hotels.php?id='.$hotel["id"].'">' .$hotel['name'].'</option>';
   }

This will display

A Hotel B Hotel ... S Hotel The V Hotel U Hotel W Hotel ...

I want The V hotel to be alphabetical with "V Hotel"

1 Answer

Hello Yan,

The easiest way I can think of is with REPLACE.

Example:

SELECT * FROM hotels ORDER BY REPLACE(name, 'The ', '')

So we replace "The " with an empty string.

Just tested it and it works great!