0

any advise how do I secure my GET code below to prevent SQL Injection or any hacking activities?

http://localhost/hobby.php?hobby=soccer

<?php

include "connect.php";


$hobby = (isset($_GET['hobby'])) ? $_GET['hobby'] : '';
$hobby = str_replace("'", "''", $hobby);

$hobby = strip_tags($hobby);
$hobby = trim ($hobby);

if ($hobby != '') {
    
    $sql = "SELECT Name, Hobby from myself where Hobby like '%$hobby%'";

    $stmt = sqlsrv_query( $conn, $sql );
    
    $result = array();
    $row_check = sqlsrv_has_rows( $stmt );


    if ($row_check == true) {
        while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
            $result['Response'][] = array(
        'Name' => $row['Name'],
        'Hobby' => $row['Hobby']
            );
        }
    } 
    sqlsrv_free_stmt( $stmt);
    sqlsrv_close( $conn);
?>
twister
  • 41
  • 8

1 Answers1

0

The best thing to do is use PDO as suggested by @giacomo-m

php.net/manual/en/book.pdo.php

Toby Allen
  • 10,997
  • 11
  • 73
  • 124