<?php
// I fetching data from sql table "product".i want to prevent all unwanted characters and all.please add your suggestions in my code.
if(isset($_GET['search'])){
$search_query = $_GET['user_query'];
$get_pro = "select * from product where title like '%$search_query%'";
$run_pro = mysqli_query($con, $get_pro);
while($row_pro=mysqli_fetch_array($run_pro)){
$pro_title = $row_pro['title'];
echo " <span>$pro_title</span> "
}
}
?>

- 25,449
- 7
- 45
- 62

- 25
- 1
-
Badly formatted question is hard to read: unlikely to get a direct answer. – Richard Apr 23 '17 at 08:21
1 Answers
To prevent SQL Injection PDO(PHP Data Objects) is the best way to go. PDO gives more flexibilty to the programmer as if you want to switch your project to use another database, PDO makes the process very easy. You only have to change the connection string and a few queries. If your project is in initial stage and you want to attain more flexibility I'll highly recommend to switch over to PDO. To know more about PDO you can refer to this link How does PHP PDO's prepared statements prevent sql injection? What are other benefits of using PDO? Does using PDO reduce efficiency?
Okay coming back to the problem you asked. To prevent SQL injection in mysqli interface you could use mysqli_real_escape_string()
function which takes two args:
- connection- Specifies the MySQL connection to use(required)
- escapestring- The string to be escaped(required)
After this step your code will look like this-
$search_query = mysqli_real_escape_string($conn, $_GET['user_query']);
where $conn will be your connection handle. You can append the '%' operator after this step and can use the result to perform the query.

- 1
- 1

- 2,779
- 5
- 28
- 39
-
-
If you found my answer helpful, please don't forget to upvote it. – Kartik Chauhan Apr 23 '17 at 08:35
-
2Mysqli is perfectly fine, and you forgot to mention the only proper way of preventing sql-injection, which is using parameterized queries with placeholders. – Qirel Apr 23 '17 at 09:13
-
As Qirel says here, doing manual escaping is how you end up with SQL injection bugs because you'll have to compose your query using string interpolation or concatenation. Either way you're at risk if you make even a single mistake. Placeholder values *guarantee* you're doing it right if you're absolutely disciplined about using them every time you're injecting user data into your query. – tadman Apr 23 '17 at 09:44