PHP使PDO连接数据库示例代码

以下代码可以写在db.php文件里,以便于在其它文件中引用:

<?php
/**
 * 配置数据库连接
 */

$host = '127.0.0.1';
$db   = 'sport_video';
$user = 'root';
$password = '123456';
$port = "3306";
$charset = 'utf8mb4';

$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

$dsn = "mysql:host=$host;dbname=$db;charset=$charset;port=$port";

try {
    $pdo = new PDO($dsn, $user, $password, $options);
} catch (PDOException $e) {
    throw new PDOException($e->getMessage(), (int)$e->getCode());
}


function alert($msg, $backPage) {
    echo "<script>alert('{$msg}'); window.location.href='{$backPage}';</script>";
}

查询:

$sql = "select username, password, uuid, id from users where username=:username and password=:password";
$sth = $pdo->prepare($sql);
$sth->execute([':username' => $username, ':password'=>$password]);
$result = $sth->fetch();
if ($result) {
    $_SESSION['uid'] = $result['id'];
    $_SESSION['username'] = $result['username'];
    header('Location:index.php');
    exit();
} else {
    $errors[] = 'loginerror';       
}

执行命令:

$sql= "update users set password=:password where id=:id";
$sth = $pdo->prepare($sql);
$sth->execute([':id'=>$_SESSION['uid']]);