用pdo连接数据库
程序员文章站
2022-02-11 06:30:30
...
在database.php返回需要的数组
return [
'type' => $type ?? 'mysql',
'port' => $port ?? '3306',
'username' => $username ?? 'root',
'password' => $password ?? '',
'dbname' => $dbname ?? 'chloe',
'host' => $host ?? 'localhost',
'charset' => $charset ?? 'utf8',
];
数据库连接
//配置文件引过来
$config = require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'database.php';
extract($config);
$dsn = sprintf('%s:host=%s;port=%s;dbname=%s', $type, $host, $port, $dbname);
try {
$pdo = new PDO($dsn, $username, $password);
var_dump($pdo);
} catch (PDOException $e) {
die($e->getMessage());
}
// 后端可接受前端传过来的参数
$name = isset($_POST['username']) ? $_POST['username'] : null;
$pwd = isset($_POST['password']) ? $_POST['password'] : null;
$pwd = md5($pwd);
// sql模板
$sql = "SELECT `username`,`password` FROM `user` WHERE `username` = ? AND `password` = ? ";
// prepare准备阶段
$stmt = $pdo->prepare($sql);
// 为占位符绑定参数
// $stmt->bindParam(1, $name);
// $stmt->bindParam(2, $pwd);
$res = $stmt->execute([$name, $pwd]);
if ($res) {
$res = $stmt->fetch(PDO::FETCH_ASSOC);
if ($res) {
echo json_encode(['status' => 1, 'msg' => '登录成功']);
}
}
上一篇: 微信小程序分享朋友圈生成海报