Webbserverprogrammering 1

Show sourcecode

The following files exists in this folder. Click to view.

ramverket/incl/

config.php
connect_db.php
db_handler.php
footer.php
header.php
ovn_incl1.php
ovn_incl2_end.php
ovn_incl2_start.php
ovn_incl3.php
ovn_incl4_end.php
ovn_incl4_start.php

db_handler.php

80 lines ASCII Windows (CRLF)
<?php 
  
function createTable($conn, $table) {
     
$sql = "CREATE TABLE $table (
      id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      first_name VARCHAR(30) NOT NULL,
      last_name VARCHAR(30) NOT NULL,
      username VARCHAR(30) NOT NULL,
      password VARCHAR(30) NOT NULL,
      type VARCHAR(30) NOT NULL,
      mobile VARCHAR(50),
      email VARCHAR(50)
      )"
;

      
$stmt = $conn->prepare($sql);
      
$stmt->execute();
    }

    function 
tableExists($conn, $table) {
      
$sql = "SHOW TABLES LIKE '$table'";
      
$stmt = $conn->prepare($sql);
      
$stmt->execute();

      return 
$stmt->rowCount() > 0;
    }

    function 
getTableRow($conn, $table, $key, $value) {
      
$sql = "SELECT * FROM $table where $key = '$value'";
      
$stmt = $conn->prepare($sql);
      
$stmt->execute();

      return 
$stmt;
    }

    function 
getAllTableRows($conn, $table) {
      
$sql = "SELECT * FROM $table";
      
$stmt = $conn->prepare($sql);
      
$stmt->execute();

      return 
$stmt;
    }

    function 
insertTableRow($conn, $table, $key_string, ...$values) {
      
$sql = "INSERT INTO $table ($key_string) VALUES (" . implode(",", array_fill(0, count($values), "?")) . ")";
      
$stmt = $conn->prepare($sql);
      
$stmt->execute([...$values]);
      return 
$conn->lastInsertId();
    }

    function 
deleteTableRow($conn, $table, $id) {
      
$sql = "DELETE FROM $table WHERE id = ?";
      
$stmt = $conn->prepare($sql);
      
$stmt->execute([$id]);
    }

    function 
deleteAllTableRows($conn, $table) {
      
$sql = "DELETE FROM $table";
      
$stmt = $conn->prepare($sql);
      
$stmt->execute();
    }

    function 
updateTableRow($conn, $table, $id, $username, $password, $first_name, $last_name, $mobile, $email, $type = "user") {
      
$sql = "UPDATE $table SET username = ?, password = ?, first_name = ?, last_name = ?, mobile = ?, email = ?, type = ? WHERE id = ?";
      
$stmt = $conn->prepare($sql);
      
$stmt->execute([$username, $password, $first_name, $last_name, $mobile, $email, $type, $id]);
    }

    function 
login($conn, $table, $username, $password) {
      
$sql = "SELECT * FROM $table WHERE username = ? AND password = ?";
      
$stmt = $conn->prepare($sql);
      
$stmt->execute([$username, $password]);

      
$user = $stmt->fetch();

      if (!
$user) {
        return [
false, null];
      }
      
      return [
true, $user['id']];
    }
?>