benhowdle89
benhowdle89

Reputation: 37464

Capitalize first letter of each word pulled from mysql with PHP/jQuery

I've stored Names all lower case into a mysql db but my users want to see them on the website as first letters capitalized. however i'm trying to figure out a way, whether server-side(PHP) or client-side (jQuery), to do this without changing anything in the database? is this possible?

CODE:

$result = mysql_query("SELECT user from `users` order by user asc") or die(mysql_error());
            echo '<select name="user" class="user">';
            while ($row = mysql_fetch_array($result)) {
                echo "<option value='".$row['user']."'>".$row['user']."</option>";
            }
            echo '</select>';

Upvotes: 0

Views: 4191

Answers (8)

Simon Richter
Simon Richter

Reputation: 29598

Note that the mapping between upper and lower case letters is not the same in every country; the most notable example being Turkey, where i <-> İ and ı <-> I; also, names tend to have more complex capitalisation rules (e.g. "MacDonald", "deVries", "von Hohenzollern" are all proper family names)

I'd run the conversion over the database once, and leave the presentation layer alone.

Upvotes: 0

bharath
bharath

Reputation: 1233

something like this

$result = mysql_query("SELECT user from `users` order by user asc") or die(mysql_error());
echo '<select name="user" class="user">';
while ($row = mysql_fetch_array($result)) {
    $user = explode(" ", $row['user']);
    echo "<option value='".$row['user']."'>".ucfirst($user[0]).' '.ucfirst($user[1])."</option>";
}
echo '</select>';

Upvotes: 0

borkweb
borkweb

Reputation: 1024

You could do it with MySQL as well:

SELECT CONCAT(UPPER(SUBSTR(user, 1, 1)), SUBSTR(user, 2)) FROM `users` ORDER BY user ASC

Upvotes: 1

Chris Fletcher
Chris Fletcher

Reputation: 2387

You can also do it with CSS:

#example {
  text-transform: capitalize;
}

Upvotes: 6

Diablo
Diablo

Reputation: 3418

Or you can do it via css like this:

div.caps { text-transform: capitalize; } 

Result is:

This Is Some Text.

Upvotes: 1

Paul Spencer
Paul Spencer

Reputation: 1385

there is also

ucwords($row['user']);

if you want to capitalize all the words.

Upvotes: 7

diagonalbatman
diagonalbatman

Reputation: 18002

in PHP you can use the function UCfirst(str); to achieve this.

You could also do this in your SQL query - but not sure this is best way of doing it.

SELECT CONCAT(UPPER(SUBSTRING(firstName, 1, 1)), 
LOWER(SUBSTRING(firstName FROM 2))) AS properFirstName

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 237895

PHP has the ucfirst function.

echo "<option value='".$row['user']."'>".ucfirst($row['user'])."</option>";

By only changing the value inside the option, rather than the value attribute, you can ensure that the same value will be sent back to the server. Note that you could also use strtolower to ensure that the string is all lower case.

Upvotes: 5

Related Questions