您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

php如何实现sql防注入?

2024/6/13 2:21:46发布29次查看
php实现sql防注入方法:1、execute代入参数法,代码为【$stmt->execute(array($_post[$j], $_post[$i])】;2、bindparam绑定参数,代码为【$stmt->bindpara()】。
php实现sql防注入方法:
方法一:execute代入参数
<?phpif(count($_post)!= 0) { $host = 'aaa'; $database = 'bbb'; $username = 'ccc'; $password = '***'; $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; //关闭连接}?>
方法二:bindparam绑定参数
<?phpif(count($_post)!= 0) { $host = 'aaa'; $database = 'bbb'; $username = 'ccc'; $password = '***'; $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; //关闭连接}?>
相关学习推荐:php编程从入门到精通
以上就是php如何实现sql防注入?的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product