Home Backend Development PHP Tutorial Simple method to prevent SQL injection in PHP

Simple method to prevent SQL injection in PHP

Jun 02, 2018 am 10:24 AM
php method injection

This article mainly introduces the simple method of preventing SQL injection in PHP, and analyzes the common operating techniques and precautions in PHP to prevent SQL injection in the form of examples. The code is fully commented for easy understanding. Friends in need can refer to it

The example in this article describes how to simply implement PHP to prevent SQL injection. Share it with everyone for your reference, the details are as follows:

Method 1: execute and substitute parameters

<?php
if(count($_POST)!= 0) {
  $host = &#39;aaa&#39;;
  $database = &#39;bbb&#39;;
  $username = &#39;ccc&#39;;
  $password = &#39;***&#39;;
  $num = 0;
  $pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);//创建一个pdo对象
  foreach ($_POST as $var_Key => $var_Value) {
    //获取POST数组最大值
    $num = $num + 1;
  }
  //下标为i的数组存储的是商品id, 下标为j数组的存储的是此商品的库存
  for($i=0;$i<$num;$i=$i+2)
  {
    //库存下标
    $j = $i+1;
    //判断传递过来的数据合法性
    if(is_numeric(trim($_POST[$i])) && is_numeric(trim($_POST[$j]))){
      //禁用prepared statements的仿真效果
      $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
      //查询数据库中是否存在该ID的商品
      //当调用 prepare() 时,查询语句已经发送给了数据库服务器,此时只有占位符 ? 发送过去,没有用户提交的数据
      $stmt = $pdo->prepare("select good_id from delphi_test_content WHERE good_id = ?");
      //当调用到 execute()时,用户提交过来的值才会传送给数据库,他们是分开传送的,两者独立的,SQL攻击者没有一点机会。
      $stmt->execute(array($_POST[$i]));
      //返回查询结果
      $count = $stmt->rowCount();
      //如果本地数据库存在该商品ID和库存记录,就更新该商品的库存
      if($count != 0)
      {
        $stmt = $pdo->prepare("update delphi_test_content set content = ? WHERE good_id = ?");
        $stmt->execute(array($_POST[$j], $_POST[$i]));
      }
      //如果本地数据库没有该商品ID和库存记录,就新增该条记录
      if($count == 0)
      {
        $stmt = $pdo->prepare("insert into delphi_test_content (good_id,content) values (?,?)");
        $stmt->execute(array($_POST[$i], $_POST[$j]));
      }
    }
  }
  $pdo = null;
  //关闭连接
}
?>
Copy after login

Method 2: bindParam binding parameter

##

<?php
if(count($_POST)!= 0) {
  $host = &#39;aaa&#39;;
  $database = &#39;bbb&#39;;
  $username = &#39;ccc&#39;;
  $password = &#39;***&#39;;
  $num = 0;
  $pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);//创建一个pdo对象
  foreach ($_POST as $var_Key => $var_Value) {
    //获取POST数组最大值
    $num = $num + 1;
  }
  //下标为i的数组存储的是商品id, 下标为j数组的存储的是此商品的库存
  for($i=0;$i<$num;$i=$i+2)
  {
    //库存下标
    $j = $i+1;
    //判断传递过来的数据合法性(此数据为商品编号以及库存,严格来说字符串全是由数字组成的)
    if(is_numeric(trim($_POST[$i])) && is_numeric(trim($_POST[$j]))){
      //查询数据库中是否存在该ID的商品
      $stmt = $pdo->prepare("select good_id from delphi_test_content WHERE good_id = ?");
      $stmt->execute(array($_POST[$i]));
      $stmt->bindParam(1,$_POST[$i]);
      $stmt->execute();
      //返回查询结果
      $count = $stmt->rowCount();
      //如果本地数据库存在该商品ID和库存记录,就更新该商品的库存
      if($count != 0)
      {
        $stmt = $pdo->prepare("update delphi_test_content set content = ? WHERE good_id = ?");
        $stmt->execute(array($_POST[$j], $_POST[$i]));
        $stmt->bindParam(1,$_POST[$j]);
        $stmt->bindParam(2,$_POST[$i]);
        $stmt->execute();
      }
      //如果本地数据库没有该商品ID和库存记录,就新增该条记录
      if($count == 0)
      {
        $stmt = $pdo->prepare("insert into delphi_test_content (good_id,content) values (?,?)");
        $stmt->bindParam(1,$_POST[$i]);
        $stmt->bindParam(2,$_POST[$j]);
        $stmt->execute();
      }
    }
  }
  $pdo = null;
  //关闭连接
}
?>
Copy after login

Related recommendations:

PHP simply implements the method of uploading files, videos, etc. using the FTP class

PHP simply implements the method of parsing xml into an array

The above is the detailed content of Simple method to prevent SQL injection in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

See all articles