-1

i am going to prevent SQL injection using PDO but i Want to know can my code prevent SQL injection
Here is my code

connection.php

<?php
$hostname='localhost';
$username='root';
$password='root';

try {
      $pdo_obj = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
      $pdo_obj->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
      $pdo_obj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    }
 catch(PDOException $e)
    {
      echo $e->getMessage();
    }

    ?>

my function.php

    <?php

    function getdata($pdo_obj, $sql, $params=NULL)      // pdo prepaired statements
    {
       $stmt = $pdo_obj->prepare($sql);
        $stmt->execute($params);
        return $stmt; 
    }
?>

and my page.php

<?php
$searchTerm = $_GET['term'];
 $result=getdata($pdo_obj,"SELECT b_type FROM b_details WHERE b_type LIKE '%".$searchTerm."%'")->fetchAll();
// my work
?>

every thing working fine but i am not sure is this code prevent SQL Injection Thanks in Advance

Sarjerao Ghadage
  • 1,420
  • 16
  • 31

1 Answers1

3

You aren't using your function's ability to protect from injection. To do so you have to send any data via parameters.

<?php
$searchTerm = '%'.$_GET['term'].'%';
$sql = "SELECT b_type FROM b_details WHERE b_type LIKE ?";
$result = getdata($pdo_obj, $sql, [$searchTerm])->fetchAll(PDO::FETCH_COLUMN);

BTW, I added a PDO::FETCH_COLUMN constant that will make the returned array more convenient, given only one column is selected.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345