How to prevent SQL injection attacks in PHP

To prevent SQL injection attacks or javascript attacks in your PHP web application, always use parameterized query with prepared statements like:

$txtuserid = htmlspecialchars(addslashes(trim($_POST['txtid'])));
$query = "select * from users where userid=:userid"
$stmt = $conn->prepare($query);
$stmt->bindParam(':userid', $txtuserid);
//$txtuserid getting value through $_POST or URL string
echo "Record inserted successfully...";
catch(PDOException $e)
echo $e->getMessage();

To display value of stored $txtid, when you retrieve it from database, call stripslashes function like this:

$txtid = stripslashes($row['id'])



Add a Comment

Your email address will not be published. Required fields are marked *