i have a simple php page that query the database for a random row (with some exceptions), every time it gets a post request.
i have noticed that the post request take some time to get the response.
because with every post request it reconnect to mysql server, so i thought maybe i could store the pdo in $_SESSION and use it to save some time and not have to authenticate with every request
i don't know if there is any way to fix this :)
<?php
// check for POST Request Only
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
header("HTTP/1.0 405 Method Not Allowed");
exit();
}
$host = 'localhost';
$db = 'Quiz';
$user = 'admin';
$pass = 'password';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
if (!empty($_POST['old'])) {
$in = str_repeat('?,', count($_POST['old']) - 1) . '?';
$sql = "SELECT * FROM QT WHERE id NOT IN ($in) ORDER BY RAND() LIMIT 1";
$stm = $pdo->prepare($sql);
$stm->execute($_POST['old']);
$data = $stm->fetchAll();
echo json_encode($data);
exit();
} else {
$stm = $pdo->prepare('SELECT * FROM QT ORDER BY RAND() LIMIT 1');
$stm->execute();
$data = $stm->fetchAll();
echo json_encode($data);
exit();
}
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
?>