Mysql real escape string with numeric value

hi all

i m using below code for validating phone number


Do i still need to use
mysql_real_escape_string with the above code even if i m not inserting it into the database till its not a numeric value


No, you don’t need to use mysql_real_escape_string on your $phone_number variable, because you already proved it only contains numbers. So that variable alone could not provoke a SQL Injection.

hi cp

trim should be used after it or before it





I’m not sure it would make a difference, but I usually put trim inside the mysql_real_escape_string call (like your first example).

hi cp

does htmlspecialchars() adds another layer of security if used along with mysql_real_escape_string


No, htmlspecialchars() does nothing for your database security, it does protect you against XSS attacks, and so should only be used when outputting the content to the page and I actually recommend htmlentities() instead of htmlspecialchars().


echo htmlentities($row['content']);

hi cp

I meant to know
Suppose someone enter name as “vin@#$”

then will it be safe to add the name as it is to database
we should first convert post data to htmlspecialchars or htmlentities and then add it to database.


The only characters that are unsafe to a database are single and double quotes (which is why you use [fphp]mysql_real_escape_string[/fphp]).

htmlspecialchars or htmlentities DO NOT need to be used when inserting into the database/table. They only need to be used to prevent XSS attacks.

hi cp

I m new to XSS so can you tell me

XSS Attacks happens only while outputting the data from database
there are other occasions also when XSS attacks can happen.


XSS attacks can occur when you output ANY data that may have been entered by a User via QueryString, Form Data, data stored in a database, etc.

In short, consider the following was entered by your user as a comment (assume this is valid JavaScript)

<script type="text/javascript">document.body.append('<script type="text/javascript' src=''></script>');</script>

Without using [fphp]htmlentities[/fphp], it will try and execute the JavaScript the user entered as a comment.

With htmlentities, it will output the comment as TEXT, so it can’t be executed, as it will substitute all of the < and > signs to be < and > along with the quotes.

The database won’t ever try to execute the JavaScript, so it remains unaffected, but when you write that content back to the page for a user to see, that is where it becomes a problem.

Hopefully this makes sense. Good question :slight_smile:

hi cp

htmlentities() and htmlspecialchars()

both functions work fine

with particular one charset (UTF or ISO)

or both charsets


If you look at the PHP manual pages for both [fphp]htmlentities[/fphp] and [fphp]htmlspecialchars[/fphp], you will see which encodings are supported and that you can tell it to use a specific encoding (if you want).