I am not experienced with mysql or php and i keep mentioning that in my questions but people keep saying you need mysql injection protection and I’ve looked it up and i really don’t get it. Can anyone help me? I am so new to mysql and am having a bit of trouble with it
Here is my code:
How can it be improved? When i go to view my source code by right clicking on the site, none of the php/mysql appears.
<?php
$conn = mysql_connect("", "", "");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
$search = "%".$_POST["search"]."%";
$searchterm = "%".$_POST["searchterm"]."%";
if (!mysql_select_db("")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT name,lastname,email
FROM test_mysql
WHERE name LIKE '%".$search."%' AND lastname LIKE '%".$searchterm."%'";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if(empty($_GET['search'])){ // or whatever your field's name is
echo 'no results';
} else {
performSearch(); // do what you're doing right now
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br><br><div class="data1">';
echo $row["name"];
echo '</div><br><div class="data2">';
echo $row["lastname"];
echo '</div><br><div class="data3">';
echo $row["email"];
echo '</div>';
}
mysql_free_result($result);
?>
SQL injection is the name of the attack, but the underlying problem is insufficient input verification. Take the following code:
What happens if someone enters
O'Reillyin the search form?Well, the query is eventually constructed as:
This is not a valid SQL query, but will merely lead to an error message. Therefore, your code is buggy; it cannot handle inputs that contain
'.Now, let’s consider a malicious person, Mallory. Causing the error doesn’t help Mallory in his evil ways, unless he wants to stress database administrators who read all the error logs. He inputs:
%'; INSERT INTO test_mysql name,lastname,email. Now, the complete SQL query isVALUES('mal','ory','malory@evil.com');--
The last line is a comment and ignored. Mallory can now write arbitrary things to the database!
Note that this requires the ability to execute more than one command in one MySQL. If that feature is not enabled, Mallory has to resort to using subqueries and predicates. In some cases, Mallory should not be able to view the whole table (for example, he should only be able to view his purchases in a webshop, not other customers’). He can simply input
' OR ''='to see the whole content of the query.You can protect yourself by either escaping values, like this:
Alternatively, use PDO and prepared statements: