Search code examples
phpjavascriptmysqlformstitle

How do I convert text entered in form to Title Case Using PHP before submitting to MySQL?


I am using the PHP below to submit data from an html form to MySQL and to an email address. I would like all of the data entered in all fields apart from the email field to be converted to Title (Proper) Case. I am wondering if there is a simple method of doing this. In searching this site I found this code:

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

but I am not sure if it is what I need and if it is what I need, how to hook it up to the existing code. Could someone help with this?

Thanks,

Nick

<?php

$emailFrom = "****";
$emailTo = "****";
$subject = "****";

$body = "****" . "\n\n" . "Waged/Organisation Rate:" . "\n\n";
$row_count = count($_POST['name']);
$row_count2 = count($_POST['name2']);

$values = array();

 for($i = 0; $i < $row_count; $i++) {
     // variable sanitation...
     $name = trim(stripslashes($_POST['name'][$i]));
     $email = trim(stripslashes($_POST['email'][$i]));
     $organisation = trim(stripslashes($_POST['organisation'][$i]));
     $position = trim(stripslashes($_POST['position'][$i]));

     // this assumes name, email, and telephone are required & present in each element
     // otherwise you will have spurious line breaks. 
     $body .= "Name: " . $name . "    Email: " . $email . "  Organisation: " . $organisation . "   Position: " . $position . "\n\n";

     //prepare the values for MySQL
     $values[] = '(\'' . $name . '\',\'' . $email . '\',\'' . $organisation . '\',\'' . $position . '\')';

}

mysql_select_db($database, $connection);

$query1 = "INSERT INTO conference (Name, Email, Organisation, Position) VALUES "  . implode(',', $values);

$result1 = mysql_query($query1);
if (!$result1) {
  die('Invalid query: ' . mysql_error());
}


 $body .= "Unwaged Rate:" . "\n\n";

 $values = array();

 for($i = 0; $i < $row_count; $i++) {
     // variable sanitation...
     $name = trim(stripslashes($_POST['name2'][$i]));
     $email = trim(stripslashes($_POST['email2'][$i]));

     // this assumes name, email, and telephone are required & present in each element
     // otherwise you will have spurious line breaks. 
     $body .= "Name: " . $name . "    Email: " . $email . "\n\n";

     //prepare the values for MySQL
     $values2[] = '(\'' . $name . '\',\'' . $email . '\')';
}
$query2 = "INSERT INTO conference (Name, Email) VALUES " . implode(',', $values2);

$result2 = mysql_query($query2);
if (!$result2) {
  die('Invalid query: ' . mysql_error());
}

// send email 
$success = mail($emailTo, $subject, $body, "From: <$emailFrom>");
?>

Solution

  • Use PHP's ucwords function.

    http://php.net/manual/en/function.ucwords.php

    Example:

    $subject = "this is a subject";
    $subject = ucwords($subject); //$subject is now "This Is A Subject"