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)
}