-1

I recently have made a search engine using an html form , php and mysqli. What it does is whatever terms i put in the form it searches that in my mysql database and echos it back on my html page. So far its working as I wanted. However I have seen people warn for Mysql injection attacks on the tutorial i made this engine from so can anyone please check my code below and give me an advice.

<?php

$k = mysqli_real_escape_string($_GET['k']);
$terms = mysqli_real_escape_string(explode(" ", $k));
$query = "SELECT * FROM xaplinks WHERE ";
$i = 0;

foreach ($terms as $each) {
 $i++;
 if ($i == 1) {
   $query .= "xap_name LIKE '%$each%'"; }
 else {
   $query .= "OR xap_name LIKE '%$each%'"; }
}

$con = mysqli_connect('mysql.hostinger.in','steve','password', 'win');

$query = mysqli_real_escape_string(mysqli_query($con, $query));
$numrows = mysqli_num_rows($query);

if ($numrows > 0) {
  while ($row = mysqli_fetch_assoc($query)) {
    $name = $row['xap_name'];
    $link = $row['xap_link'];

    echo "<a href='$link'>$name</a></br>";
  }
}
else {
  echo "No results found. :( ";
}
mysqli_close($con);
?>

I read online that escape string in mysqli can help prevent injection so ive used it but not sure if its properly implemented. Im very new to mysqli.

Any help / tip would be appreciated , Thanks in advance. :)

  • Use prepared statements via PDO. This may also be of interest: http://htmlpurifier.org/ for further XSS protection from injection into your actual data. – Ryan Rentfro Jan 04 '16 at 05:24
  • 1
    `explode` returns an array but `mysqli_real_escape_string` expects a string. – Gumbo Jan 04 '16 at 05:33

2 Answers2

1

Use the PDO class instead of the mysqli class. Further, use prepared statements.

Dalc
  • 21
  • 4
0

You can create a prepared statement using mysqli->prepare

Should solve your problem.

$queryPrepared = mysqli->prepare($query)

See more here. PHP MySQLI Prevent SQL Injection

Community
  • 1
  • 1