RazorFinger RazorFinger - 8 months ago 13
SQL Question

Removing spaces from a selected mysql field using PHP

I need to select a field in mysql and put it in a hidden text field so i can select it into another file. The problem is, the name of the field has spaces in it, so it gets a little buggy. It's something like this:

$GetArea = $_GET['area'];

Then i add this into a hidden textbox:

<INPUT id=txtArea type=hidden value=".$GetArea." name=txtArea />

But it doesn't read the area when i open the site, because the area name is "Area 123" with spaces. This might be a duplicate, but searching around i really couldn't find the answer. Anyone knows of a way to remove the spaces?


To answer your direct queston of how to remove spaces from a variable: Use Regex,

$GetArea = $_GET['area'];
///      = Area 123.

$GetArea = preg_replace("/\s+/","",$_GET['area']);
///      = Area123

View a regex101 example. Regex is far better than using str_replace as in one line it can handle multiple whitespace generating characters (such as the tab character or new line breaker).

However if [in another situation] you want to preserve the spaces and record them you can substitute them for something else such as a _ character:

$GetArea = $_GET['area'];
///      = Area 123.

$GetArea = preg_replace("/\s+/","_",$_GET['area']);
///      = Area_123

The above example means that when you send the data back to the database you can do a preg_replace search and replacement for all _ characters substituted into replace the space character, as needed. (although MySQL only accepts spaces in Column names when properly encased in backticks).


I would also strongly suggest you get into a habit of encasing your HTML into quotes (single usually) rather than just hanging them out as they are, as this is the principle cause of your issue. so to quote your HTML:

print "<INPUT id='txtArea' type='hidden' value='".$GetArea."' name='txtArea' />";
/** I made an assumption from your syntax your HTML was being printed by PHP **/

This means that you can keep your spaces in your data value of the HTML input element because the whole value section is defined and clearly wrapped in single quote marks.

On a broader note, you really should be looking at not using $_GET and instead transfering data page-to-page with $_POST. Also please research SQL injection and how to prevent it as well as Cross Site Scripting and how to mitigate that. Spaces in MySQL column names is a good habit to avoid.