0

can someone help me on how to remove spaces in my sql. for exmaple let say i type in "I am a good boy"... i want it to save in my mysql table column as "iamagoodboy" removing all spaces of anything i send.. where in this code below can i do this, thanks very much

$sql = 'INSERT INTO messages (username,usernameto, message_content, message_time)      VALUES ("' . $username . '", "' . $messageTo . '", "' . $message . '", ' . $time . ')';

$result = mysql_query($sql, $cn) or

die(mysql_error($cn));
Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
Kelvin Bala
  • 97
  • 2
  • 2
  • 11

5 Answers5

3
str_replace(' ', '', $message);

Should work fine for you in PHP. As a general rule, don't put that sort of functionality on the Database, no reason to put the load on that server - do it on the web server instead.

So your code would look like this (assuming you are taking the spaces out of $message):

$sql = 'INSERT INTO messages (username,usernameto, message_content, message_time)      VALUES ("' . $username . '", "' . $messageTo . '", "' . str_replace(' ', '', $message) . '", ' . $time . ')';

A better solution, though, might be to use preg_replace('/\s+/', '', $string); which will strip all whitespace (tabs, linebreaks, etc). Depends on what exactly you want to accomplish.

Chris Sobolewski
  • 12,819
  • 12
  • 63
  • 96
1

Use str_replace:

$string = str_replace(' ', '', $string);

or remove all whitespace

$string = preg_replace('/\s+/', '', $string);

source: How to strip all spaces out of a string in php?

Community
  • 1
  • 1
Eric Goncalves
  • 5,253
  • 4
  • 35
  • 59
  • The preg_replace example is probably what you want as it will also replace multiple consecutive spaces, tabs and newlines – thaJeztah Jan 28 '13 at 20:18
0

You can replace characters using SQL -> SELECT REPLACE(caption,'\"','\'') FROM ...

0

u can try this

 '".str_replace(' ', '', $messageTo)."'

and same for other

echo_Me
  • 37,078
  • 5
  • 58
  • 78
0
$sql = 'INSERT INTO messages " . 
. "(username,usernameto,message_content,message_time) " .
. "VALUES ("'.$username.'","'.$messageTo.'",REPLACE("'.$message.','' '','''')",'.$time .')';

$result = mysql_query($sql, $cn) or   die(mysql_error($cn));
RolandoMySQLDBA
  • 43,883
  • 16
  • 91
  • 132