Blogger Information
Blog 31
fans 0
comment 0
visits 14268
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
用pdo连接数据库
木子木杉
Original
664 people have browsed it

在database.php返回需要的数组

  1. return [
  2. 'type' => $type ?? 'mysql',
  3. 'port' => $port ?? '3306',
  4. 'username' => $username ?? 'root',
  5. 'password' => $password ?? '',
  6. 'dbname' => $dbname ?? 'chloe',
  7. 'host' => $host ?? 'localhost',
  8. 'charset' => $charset ?? 'utf8',
  9. ];

数据库连接

  1. //配置文件引过来
  2. $config = require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php';
  3. extract($config);
  4. $dsn = sprintf('%s:host=%s;port=%s;dbname=%s', $type, $host, $port, $dbname);
  5. try {
  6. $pdo = new PDO($dsn, $username, $password);
  7. var_dump($pdo);
  8. } catch (PDOException $e) {
  9. die($e->getMessage());
  10. }
  11. // 后端可接受前端传过来的参数
  12. $name = isset($_POST['username']) ? $_POST['username'] : null;
  13. $pwd = isset($_POST['password']) ? $_POST['password'] : null;
  14. $pwd = md5($pwd);
  15. // sql模板
  16. $sql = "SELECT `username`,`password` FROM `user` WHERE `username` = ? AND `password` = ? ";
  17. // prepare准备阶段
  18. $stmt = $pdo->prepare($sql);
  19. // 为占位符绑定参数
  20. // $stmt->bindParam(1, $name);
  21. // $stmt->bindParam(2, $pwd);
  22. $res = $stmt->execute([$name, $pwd]);
  23. if ($res) {
  24. $res = $stmt->fetch(PDO::FETCH_ASSOC);
  25. if ($res) {
  26. echo json_encode(['status' => 1, 'msg' => '登录成功']);
  27. }
  28. }
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post