CSY2028-assignment-1/functions.php

90 lines
2.3 KiB
PHP
Raw Normal View History

2022-11-16 13:27:51 +00:00
<?php
function fetchCats() {
2022-11-20 13:20:58 +00:00
$pdo = startDB();
2022-11-16 19:17:35 +00:00
$stmt = $pdo->prepare('SELECT * FROM category');
2022-11-16 13:27:51 +00:00
$stmt->execute();
2022-11-20 18:51:17 +00:00
$cats = executeQueryWithoutConstraint('category','*')->fetchAll();
2022-11-16 13:27:51 +00:00
return $cats;
2022-11-16 19:00:51 +00:00
}
2022-11-19 15:38:26 +00:00
function adminCheck() {
if(isset($_SESSION['admin'])) {
if($_SESSION['admin'] != 'y') {
echo '<script>window.location.href = "../index.php";</script>';
}
}
else {
echo'<script>window.location.href = "../index.php";</script>';
}
}
2022-11-20 13:20:58 +00:00
function startDB() {
$server = 'mysql';
$username = 'student';
$password = 'student';
$schema = 'assignment1';
$pdo = new PDO('mysql:dbname=' . $schema . ';host=' . $server, $username, $password);
return $pdo;
}
2022-11-20 14:44:18 +00:00
function checkListing() {
if (!isset($_GET['listing_id'])) {
echo '<script>window.location.href = "index.php";</script>';
}
}
function getListing() {
2022-11-20 18:51:17 +00:00
return getFirstAllMatches('auction', 'listing_id', $_GET['listing_id']);
2022-11-20 14:44:18 +00:00
}
function populateCatSelect() {
$cats = fetchCats();
$output = '';
foreach ($cats as &$cat) {
$output .= '<option value="'. $cat['category_id'] .'">'. $cat['name'] .'</option>';
}
return $output;
}
2022-11-20 18:51:17 +00:00
function executeQuery($tableName, $colName, $constraintCol, $constraint) {
$pdo = startDB();
$stmt = $pdo->prepare('SELECT '. $colName .' FROM '.$tableName.' WHERE '. $constraintCol .' = :constraint');
$values = [
'constraint' => $constraint
];
$stmt->execute($values);
return $stmt;
}
function executeQueryWithoutConstraint($tableName, $colName) {
$pdo = startDB();
$stmt = $pdo->prepare('SELECT'.$colName.'FROM '.$tableName);
$stmt->execute();
return $stmt;
}
function getFirstMatch($tableName, $colName, $constraintCol, $constraint){
return executeQuery($tableName, $colName, $constraintCol, $constraint)->fetch();
}
function getEveryMatch($tableName, $colName, $constraintCol, $constraint){
return executeQuery($tableName, $colName, $constraintCol, $constraint)->fetchAll();
}
function executeAllQuery($tableName, $constraintCol, $constraint) {
return executeQuery($tableName, '*', $constraintCol, $constraint);
}
function getEveryAllMatches($tableName, $constraintCol, $constraint) {
return executeAllQuery($tableName, $constraintCol, $constraint)->fetchAll();
}
function getFirstAllMatches($tableName, $constraintCol, $constraint) {
return executeAllQuery($tableName, $constraintCol, $constraint)->fetch();
}
2022-11-16 19:00:51 +00:00
?>