My question is regarding the application of a DB connection and SQL injection. I am using the codes provided below to successfully connect to my database. I would like to ask:
- How the foreach stops SQL injection?
- If there is a better more efficient way to make the connection more secure?
- Will the connection still work and provide me with valid data from the database, if dbconnect.php were to be included in another file (for example; global.php), which in return was included in the main file where the actual use of database is?
example_file.php:
<?php
//MySQL Database Connect
include './includes/dbconnect.php';
//This stops SQL Injection in POST vars
foreach ($_POST as $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);
}
//This stops SQL Injection in GET vars
foreach ($_GET as $key => $value) {
$_GET[$key] = mysql_real_escape_string($value);
}
?>
dbconnect.php:
<?php
$con = mysql_connect("localhost","username","password");
if (!$con){ die('Could not connect: ' . mysql_error()); }
mysql_select_db("databasename", $con);
?>
Thanks a lot!