Question

I'm a new developer when it comes to PHP. Lately, I make some UI using ext.js and PHP for my actions. This UI can add a profile of a person. Now, My problem is that whenever I add a profile name of a person to the UI and it start with a space character, the data still it be saved along with the space character. All I want is that there must be a catch whenever I add a spaces from the beginning or in the end of a statement.

This is what I've tried so far:

   public function executeAddRegion(sfWebRequest $request)
   {
      try{
 $by = $_SESSION['employee_id'];
 $now = date("Y-m-d H:I:s");

     $description = strip_tags(pg_escape_string($request->getParameter("description")));



 // $description  = $request->getParameter("description");

    $query = "insert into country.regions
                     (description,created_by,date_created)
              values
                     ('".$description."', $by,'$now')";

    $msg = "New Region Successfully Saved.";

    $this->conn->execute($query);

    $data['success']=true;
    $data['msg']=$msg;

  }
  catch(Exception $e)
  {     
    $data['success']=false;
    $data['msg']=$e->getMessage();

  }
  die(json_encode($data));

}
Was it helpful?

Solution

Use trim to remove leading/trailing spaces.
Use ltrim (left trim) to remove leading spaces.
Use rtrim (right trim) to remove trailing spaces.

$data = " hello ";

$data = trim($data); // "hello"
$data = ltrim($data); // "hello "
$data = rtrim($data); // " hello"

Do it, before inserting your data in DB.

Edit: if you want to test if there was spaces, you can do like this:

if (trim($data) == $data)
{
   // OK
}
else
{
   // data contained some spaces (leading or trailing)
}

OTHER TIPS

You could also use MySQL trim string function before inserting or while selecting

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top