protecting from sql injections

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • harman30
    New Member
    • Sep 2015
    • 19

    protecting from sql injections

    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


    Code:
    <?php include ( "./inc/header.inc.php" );  ?>
    <?php
    if(!isset($_POST['search'])) {
    	header("Location: main.php");
    }
    $search_sql="SELECT * FROM blogs WHERE title LIKE '%".$_POST['search']."%' OR body LIKE '%".$_POST['search']."%' ";
    $search_query=mysql_query($search_sql);
    if(mysql_num_rows($search_query) !=0){
    $search_rs=mysql_fetch_assoc($search_query);
    }
    ?>
    
    
    <p>Search results</p>
    <?php
    if(mysql_num_rows($search_query) !=0){
      do { ?>
       <div class="searchresults">
       	<p><?php echo $search_rs['title']; ?></p>
       	<p><?php echo $search_rs['body']; ?></p></div>
     <?php }
      while ($search_rs=mysql_fetch_assoc($search_query));
    }
      else {
      	 echo "No results found";
      }
    
    ?>
    just want to add code that can protect from injections.
  • RonB
    Recognized Expert Contributor
    • Jun 2009
    • 589

    #2
    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)

    Comment

    Working...