By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,949 Members | 921 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,949 IT Pros & Developers. It's quick & easy.

protecting from sql injections

P: 19
I am using the code below for search function but it is not protected from injections and I am not programming expert so can anyone help me on this my code is


Expand|Select|Wrap|Line Numbers
  1. <?php include ( "./inc/header.inc.php" );  ?>
  2. <?php
  3. if(!isset($_POST['search'])) {
  4.     header("Location: main.php");
  5. }
  6. $search_sql="SELECT * FROM blogs WHERE title LIKE '%".$_POST['search']."%' OR body LIKE '%".$_POST['search']."%' ";
  7. $search_query=mysql_query($search_sql);
  8. if(mysql_num_rows($search_query) !=0){
  9. $search_rs=mysql_fetch_assoc($search_query);
  10. }
  11. ?>
  12.  
  13.  
  14. <p>Search results</p>
  15. <?php
  16. if(mysql_num_rows($search_query) !=0){
  17.   do { ?>
  18.    <div class="searchresults">
  19.        <p><?php echo $search_rs['title']; ?></p>
  20.        <p><?php echo $search_rs['body']; ?></p></div>
  21.  <?php }
  22.   while ($search_rs=mysql_fetch_assoc($search_query));
  23. }
  24.   else {
  25.        echo "No results found";
  26.   }
  27.  
  28. ?>
just want to add code that can protect from injections.
Sep 16 '15 #1

✓ answered by RonB

Start by not using any of the mysql_ functions. They are depreciated and are prone to sql injection. Instead, you should be using the mysqli_ functions. You also should not be using user supplied data directly. Instead, copy it to a new var and escape it prior to using it in sql statements.

Better still would be to use PDO's prepared statements with placeholders/bind parameters.

Here's some useful php documentation.
SQL Injection
mysqli_ - (MySQL Improved Extension)
PDO (PHP Data Objects)

Share this Question
Share on Google+
1 Reply


Expert Mod 100+
P: 589
Start by not using any of the mysql_ functions. They are depreciated and are prone to sql injection. Instead, you should be using the mysqli_ functions. You also should not be using user supplied data directly. Instead, copy it to a new var and escape it prior to using it in sql statements.

Better still would be to use PDO's prepared statements with placeholders/bind parameters.

Here's some useful php documentation.
SQL Injection
mysqli_ - (MySQL Improved Extension)
PDO (PHP Data Objects)
Sep 16 '15 #2

Post your reply

Sign in to post your reply or Sign up for a free account.