user1315621
user1315621

Reputation: 3372

Text validation before storing into MySQL database

it's about one day that I'm looking for a solution, however I don't have all the necessary skills to understand whether what I found is the right or solution or not. So, in conclusion, what are the minimum validation that I have to do before storing a text, received by a post method, into an MySQL DB? Thanks

Upvotes: 3

Views: 1203

Answers (4)

Abhinav
Abhinav

Reputation: 8168

  1. There are filter_var functions provided by php. Its the best bet. You can use the constants for checking whether a value is an Integer, or String or a proper email, etc.

Ex:

$email=$_POST['email'];
$filter_email=filter_var($email,FILTER_VALIDATE_EMAIL);

It will return you false if the filter fails.

  1. Then the best way you can insert the datas into ur DB is by using prepared statements. It almost eliminates the chances of SQL Injection.

You can read about prepared statements in here Prepared Statements

  1. You can also go for regular expressions

Hope this helps

Upvotes: 0

Combine
Combine

Reputation: 4224

$connection = mysqli_connect('localhost', 'user', 'password');

//gets the post info
$text = $_POST['key'];    

//removes the white spaces before and after the string
$text = trim($text);      

// prepares the text for storing it in the database. Helps against MySQL injections.
$text = mysqli_real_escape_string($connection, $text);   

So these I think are the bare minimum. Also you need to check if the info that comes from the POST is valid. For example if you expect to receive number but text is received, you have to deal with these sort of problems.

Upvotes: 1

Donkarnash
Donkarnash

Reputation: 12835

The major concern while getting user input from web forms and storing it in to any db is the possibility of an sql injection. Using prepared statements (as suggested by GhostGambler) can help guard against SQL injection. As a minimum level of protection mysqli_real_escape_string should be used, however note it is not the best protection. The mysql interface is deprecated so use either mysqli or pdo. Prepared statements and parameterized queries provide decent protection against SQL injection.

Upvotes: 0

Ulrich Thomas Gabor
Ulrich Thomas Gabor

Reputation: 6654

Using PDO (or mysqli) with prepared statements:

$st = $db->prepare('INSERT INTO test (x) VALUES (?)');
$st->execute(array($_POST['text']));

Done.

If you want to use the old mysql extension, you might want to use mysql_real_escape_string instead on all values you insert into the query.

Upvotes: 1

Related Questions