Showing posts with label mysql-injections. Show all posts
Showing posts with label mysql-injections. Show all posts

Aug 7, 2011

How To Stop SQL Injections in PHP | Best Way To Stop MYSQL Injections

Now a days hacking has became a hobby for young generations, people start hacking and destroy the websites just for the sake of fun or business, amongst all of them SQL injections also known as DdoS is becoming very famous. But what is SQL injections? Suppose you have a website or a forum where a user can find something for him/her. That person searches the keyword by using Search option, this is where SQL injections start, a normal search is ok, say about a server can handle couple of searches at a time, but what if same website opened in 100 windows and at the same time 100 searches or more then that are made, then your server will go down and hackers can easily break the firewall and hack your website data from the server.

This is very common now a days, so to get rid of this the php code of search should be changed.

Default Search Code:

[php]
// connect to the mysql database

$unsafe_var = $_POST["keyword"];

mysql_query("SELECT * FROM table1 where keyword='". <code>$unsafe_var</code> ."'");

// disconnect from the mysql database
[/php]

The best way is to use prepared statements
Something Like this

[php]
$preparedStatement = $db->prepare('SELECT * FROM employees WHERE name = :name');

$preparedStatement->execute(array(':name' => $name));

$rows = $preparedStatement->fetchAll();

[/php]

This is the best way to get rid of SQL Injections.
In the above SQL statements you pass to prepare is parsed and compiled by the database server. By specifying parameters (:name) we are telling the database engine where the filter should be on. Then when we call execute the prepared statement is combined with the parameter values we specify.

Simple and secure

So always use safe coding, after all coding is fun not destruction.

Happy Coding :)