欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用PDO扩展连接mysql数据库 实现用户登录时防sql注入的处理

程序员文章站 2022-03-07 18:13:43
...
PDO扩展连接mysql数据库
  1. <?php
  2. //配置数据库信息
  3. $config= [
  4. 'type' => $type ?? 'mysql'
  5. ,'username' => $username ?? 'root'
  6. ,'password' => $password ?? '123456'
  7. ,'host' => $host ?? 'localhost'
  8. ,'port' => $port ?? '3306'
  9. ,'charset' => $charset ?? 'utf8'
  10. ,'dbname' => 'mydb' ];
  11. $dsn = sprintf('%s:host=%s;port=%s;charset=%s;dbname=%s'
  12. ,$config['type']
  13. ,$config['host']
  14. ,$config['port']
  15. ,$config['charset']
  16. ,$config['dbname']);
  17. //连接数据库
  18. try {
  19. $pdo = new PDO($dsn, $config['username'], $config['password']);
  20. } catch (PDOException $e) {
  21. die('Connection error : ' . $e->getMessage());
  22. }
  23. //接受前端传过来的参数
  24. if ( 'login' == $_POST['a'] ){
  25. $n = isset($_POST['username']) ? $_POST['username'] : null;
  26. $p = isset($_POST['password']) ? $_POST['password'] : null;
  27. $p = md5($p);
  28. //使用预处理,防止sql注入攻击
  29. // 准备预处理sql语句
  30. $sql = "SELECT * FROM `webuser` WHERE `username`= ? and `password` = ? ";
  31. // 准备要执行的语句,并返回语句对象
  32. $stmt = $pdo->prepare($sql);
  33. // 执行一条预处理语句
  34. $stmt->execute(array($n,$p));
  35. //返回结果集
  36. $res = $stmt->fetchAll(PDO::FETCH_ASSOC);
  37. if($res){
  38. echo '登陆成功';
  39. }else{
  40. echo '帐号或密码不正确';}
  41. }
  42. ?>
  43. <!doctype html>
  44. <html lang="en">
  45. <head>
  46. <meta charset="UTF-8">
  47. <title>用户登录</title>
  48. </head><body>
  49. <form action="" method="POST">
  50. <input type = 'hidden' name = 'a' value = 'login' >
  51. <table border = '1' >
  52. <tr><td>帐号:</td><td><input type = 'text' name = 'username' ></td></tr>
  53. <tr><td>密码:</td><td><input type = 'password' name = 'password' ></td></tr>
  54. <tr><td colspan = '2' style = 'text-align:center'><input type = 'submit' value = '登 陆'></td></tr>
  55. </table></form></body>
  56. </html>