预处理语句
Posted rjbc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了预处理语句相关的知识,希望对你有一定的参考价值。
预处理语句
优点:效率高 (用于执行多个相同的 SQL 语句,并且执行效率更高)、 安全(防止 mysql 注入)
<?php
$dsn = ‘mysql:host = localhost;dbname=user;charset=utf8‘;
try
$pdo = new PDO($dsn,‘root‘,‘123456‘);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
catch(PDOException $e)
die(‘数据库连接失败‘.$e->getMessage());
try
/*
$sql =‘insert into user(name, password, money) value(?,?,?)‘;
$stmt = $pdo->prepare($sql);
$stmt->bindparam(1,$name);
$stmt->bindparam(2,$pwd);
$stmt->bindparam(3,$money); */
/*$sql =‘insert into user(name, password, money) value(:name, :password, :money)‘;
$stmt = $pdo->prepare($sql);*/
/*$stmt->bindparam(‘:name‘,$name);
$stmt->bindparam(‘:password‘,$pwd);
$stmt->bindparam(‘:money‘,$money);
$name= ‘赵本山‘;
$pwd = ‘12345‘;
$money = 1500;
$stmt->execute();
$name = ‘小沈阳‘;
$pwd = ‘abcde‘;
$money = 2000;
$stmt->execute();
$stmt->execute([‘:name‘ => ‘刘备‘,‘:password‘=>‘123456‘,‘:money‘=>‘2000‘]);
$stmt->execute([‘张飞‘,‘abc456‘,‘2000‘]);
$stmt = $pdo->prepare(‘delete from user where id = ?‘);
$stmt ->execute([1]);*/
$stmt = $pdo->prepare(‘update user set name= :name where id= :id‘);
$stmt->execute([‘:name‘=>‘关羽‘,‘:id‘=>‘4‘]);
catch(PDOException $e)
echo $e->getMessage();
以上是关于预处理语句的主要内容,如果未能解决你的问题,请参考以下文章