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

用pdo连接数据库

程序员文章站 2022-02-11 06:30:30
...

在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. }