月度归档:2024年11月

PHP判断session是否已启动

PHP启用session可以使用session_start()函数,如果重复启动session则会报错,所以在调用该函数前最好加一个判断,判断session是否已启动,代码如下:

<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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']]);