MYSQL TRIM() Function

Trim Function With mySQL

The trim() function with mySQL behaves like the trim() function with PHP. Both strip white space at the beginning and end of a string. The following example shows how the trim() function can be used with the mysqli_real_escape_string() function.

When functions like trim() and mysql_real_escape_string() are used within a query there is much less code to work with. However, you could apply the php trim() and mysqli_real_escape_string() functions to each post variable instead of adding it into the command.

 

Method A

$firstname = mysqli_real_escape_string($db, trim($_POST[firstname]));
$lastname = mysqli_real_escape_string($db, trim($_POST[lastname]));
$phone = mysqli_real_escape_string($db, trim($_POST['phone']));
$email = mysqli_real_escape_string($db, trim($_POST['email']));

$command = "INSERT INTO tablename VALUES (NULL, '$firstname', '$lastname', '$phone', '$email', now()) ";

$result = mysqli_query($db, $command);

Method B

$firstname = mysqli_real_escape_string($db, $_POST[firstname]);
$lastname = mysqli_real_escape_string($db, $_POST[lastname]);
$phone = mysqli_real_escape_string($db, $_POST['phone']);
$email = mysqli_real_escape_string($db, $_POST['email']);

$command = "INSERT INTO tablename VALUES (NULL, TRIM('$firstname'), TRIM('$lastname'), TRIM('$phone'), TRIM('$email'), now()) ";

$result = mysqli_query($db, $command);