How to prevent MySQL injection

What is SQL injection?
SQL injection is the attempt to issue SQL commands to a database through a website interface, to gain other information. Namely, this information is stored database information such as usernames and passwords.

The code to prevent injection:

// collect data from HTML form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
 
//Prevent MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

// Now you can send to DB secure data
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

Notice:
stripslashes —> Un-quotes a quoted string
mysql_real_escape_string —> Escapes special characters in a string for use in an SQL statement