关闭

预处理语句占位符的使用

标签: mysqlsql注入密码pdo数据库
1092人阅读 评论(0) 收藏 举报

预处理语句占位符的使用,方法绑定参数,sql注入等..

try{
    $user = "root"; // 这里是你的数据库用户名
    $pwd = "yangli"; // 这是是你的数据库密码
    $pdo = new PDO("mysql:dbname=test;host=127.0.0.1", $user, $pwd);
}catch(PDOException$e){
    echo $e->getMessage();
}
$username = $_POST['username'];
$pwd = md5($_POST['password']);
$sql = "SELECT * FROM  user WHERE `user`=:username AND pwd =:pwd";
$stmt = $pdo->prepare($sql); // 准备一条预处理语句

// 占位符的使用方法一, 这样还可以便面sql注入
$res = $stmt->execute(array(":username"=> $username,":pwd" => $pwd)); 
if(!$res){
    echo exit("错误信息: ".var_dump($stmt->errorInfo()));
}
echo $stmt->rowCount(); // 有记录返回1, 没有返回0

// 占位符使用方法二
$sql = "SELECT * FROM user WHERE `user`=? AND pwd=?"; // 1
//$sql = "SELECT * FROM user WHERE `user`=:username AND pwd=:pwd"; // 2
$stmt = $pdo->prepare($sql);
$stmt->execute(array($username, $pwd));
$stmt->execute(array(':username'=> $username, ':pwd' => $pwd));
echo $stmt->rowCount(); // 有记录返回1,没有返回0

方法绑定参数

$sql = "SELECT * FROM user  WHERE `user`= :username AND `pwd`= :pwd"; // 1
$sql = "SELECT * FROM user WHERE `user`=? AND `pwd`=?";
$stmt = $pdo->prepare($sql);



//对于使用命名占位符的预处理语句,应是类似 :name  形式的参数名。对于使用问号占位符的预处理语句,应是以1开始索引的参数位置, 常用的方式一般会使用 :name形式的参数名,这样看起来比较直观。 

$stmt->bindParam(':username', $username); 
$stmt->bindParam(':pwd', $pwd);

// 使用?问好占位符,索引从一开始, 第二个参数必须是一个变量,不能是直接的值
$stmt->bindParam(1, $username);
$stmt->bindParam(2, $pwd);

$stmt->execute();
echo $stmt->rowCount(); //有记录返回1,没有返回0



// 同时可以插入多条语句
$username = "demo6";
$pwd = md5('demo1');
$email = "test1@test.com";
$sql = "INSERT INTO user (`user`, `pwd`, `email`) VALUES (:username, :pwd, :email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':pwd', $pwd);
$stmt->bindParam(':email', $email);
if(!$stmt->execute()){
    var_dump($stmt->errorInfo());exit;
}

$username = "demo7";
$pwd = md5('demo1');
$email = "test2@test.com";
$stmt->bindParam(':username', $username);
$stmt->bindParam(':pwd', $pwd);
$stmt->bindParam(':email', $email);
if(!$stmt->execute()){
    var_dump($stmt->errorInfo());exit;
}
echo $stmt->rowCount();

//删除语句
$id = 6;
$user = 'demo6';
//$sql  = "DELETE FROM user WHERE id = :id AND user=:username";
$sql  = "DELETE FROM user WHERE id = ? AND user=?";
$stmt = $pdo->prepare($sql);
//$stmt->bindParam(':id', $id);
//$stmt->bindParam(':username', $user);
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $user);

$stmt->execute();
echo $stmt->rowCount();

//更新语句
$id = 5;
$user = 'demo7';
$sql = "UPDATE user SET user = :user WHERE id=:id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':user', $user);
$stmt->bindParam(':id', $id);
$stmt->execute();
echo $stmt->rowCount();
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:55200次
    • 积分:1385
    • 等级:
    • 排名:千里之外
    • 原创:84篇
    • 转载:19篇
    • 译文:0篇
    • 评论:5条
    最新评论