Webbserverprogrammering 1

Show sourcecode

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

Webserver1/Ovningar/mySQL/

admin.php
fetch_car_things.php
fetch_kompisar.php
fetch_users.php
mysql1.php
mysql2.php
mysql3.php
mysql3_satt_att_sortera.php
mysql3car.php
mysql3garage.php
mysql3owner.php
welcome.php

mysql3car.php

183 lines UTF-8 Windows (CRLF)
<?php
include('../../incl/dbconnection.php');
/**
 * @var PDO $dbconn
 */
try {
  if (isset(
$_POST['licence_plate'], $_POST['color'])) {
    
$licence_plate $_POST['licence_plate'];
    
$color $_POST['color'];
    
$owner $_POST['owner'];
    
$garage $_POST['garage'];

    
$sqlCheck "SELECT * FROM cars WHERE licence_plate=?";

    
// Kolla om licence_plate redan finns i tabellen
    
$check_stmt $dbconn->prepare($sqlCheck);
    
$check_stmt->execute([$licence_plate]);
    
$check_result $check_stmt->fetch(PDO::FETCH_ASSOC);
    if (empty(
$check_result) || $licence_plate != $check_result['licence_plate']) {
      
$sqlInsert "INSERT INTO cars (licence_plate, color, garage, owner) VALUES(?, ?, ?, ?)";

      
$garage_id_stmt $dbconn->prepare("SELECT garage_id FROM garage WHERE name=?");
      
$garage_id_stmt->execute([$garage]);
      
$garage_id $garage_id_stmt->fetch(PDO::FETCH_ASSOC)['garage_id'];

      
$owner_id_stmt $dbconn->prepare("SELECT owner_id FROM owners WHERE name=?");
      
$owner_id_stmt->execute([$owner]);
      
$owner_id $owner_id_stmt->fetch(PDO::FETCH_ASSOC)['owner_id'];

      
$insert_stmt $dbconn->prepare($sqlInsert);
      
$insert_stmt->execute([$licence_plate$color$garage_id$owner_id]);
      echo 
"Lade till ny bil med registreringsnummer: $licence_plate";
    } else {
      echo 
"<p>Bil finns redan, ingenting gjordes.</p>";
    }
  } else {
    echo 
"Formuläret är tomt!";
  }
} catch (
PDOException $e) {
  echo 
"Exception occured: " $e;
}
?>

<!DOCTYPE html>
<html lang="sv">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>The Ultimate Garage Interface</title>
  <style>
    table {
      border: 1px solid black;
    }
    #tableContainer tr:nth-child(even) {
      background-color: lightgray;
    }
    th {
      border-bottom: 1px solid black;
    }
  </style>
</head>

<body>
  <h1>The Ultimate Garage Interface&trade;</h1>
  <form action="" method="POST">
    <table>
      <h2>Lägg till bil</h2>
      <tbody>
        <tr>
          <td><label for="licence_plate">Registreringsnummer*:</label></td>
          <td><input type="text" name="licence_plate" pattern="[a-zA-ZåäöÅÄÖ0-9]+" placeholder="ABC123" required></td>
        </tr>
        <tr>
          <td><label for="color">Färg*:</label></td>
          <td><input type="text" name="color" required></td>
        </tr>
        <tr>
          <td><label for="owner">Ägare*:</label></td>
          <td><select name="owner" id="owner" required>
              <?php
              $result 
$dbconn->query("SELECT * FROM owners")->fetchAll(PDO::FETCH_ASSOC);
              foreach (
$result as $owner) {
                
$name $owner['name'];
                echo 
"<option value='$name'>$name</option>";
              }
              
?>
            </select></td>
        </tr>
        <tr>
          <td><label for="garage">Garage*:</label></td>
          <td><select name="garage" id="garage" required>
              <?php
              $result 
$dbconn->query("SELECT * FROM garage")->fetchAll(PDO::FETCH_ASSOC);
              foreach (
$result as $garage) {
                
$name $garage['name'];
                echo 
"<option value='$name'>$name</option>";
              }
              
?>
            </select></td>
        </tr>
        <tr>
          <td>
            <input type="submit" value="Lägg till">
          </td>
        </tr>
      </tbody>
    </table>
  </form>
  <ul>
    <li>
      <a href="./mysql3owner.php">
        <button>Lägg till person -></button>
      </a>
    </li>
    <li>
      <a href="./mysql3garage.php">
        <button>Lägg till garage -></button>
      </a>
    </li>
  </ul>

  <button id="showButton">Visa tabeller</button>
  <div id="tableContainer"></div>

  <script>
    const showButton = document.getElementById("showButton");
    // Show items in table by clicking button
    showButton.addEventListener("click", async () => {
      try {
        const response = await fetch('fetch_car_things.php');
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();

        const tableContainer = document.getElementById("tableContainer");
        let allTablesHTML = "";

        // Build the table HTML
        Object.keys(data).forEach(tableName => {
          const tableData = data[tableName];
          if (tableData.length === 0) {
            return; // Skip this table if it's empty
          }

          let columns = [];
          // Create header
          let tableHTML = `<h2>${tableName}</h2><table><thead>`;
          Object.keys(tableData[0]).forEach(colName => {
            tableHTML += "<th>" + colName + "</th>";
            columns.push(colName);
          })
          tableHTML += "</thead><tbody>";

          // Create rows
          tableData.forEach(row => {
            tableHTML += "<tr>"
            columns.forEach(col => {
              tableHTML += "<td>" + (row[col] !== null ? row[col] : '') + "</td>"
            })
            tableHTML += "</tr>"
          })
          tableHTML += '</tbody></table>';
          allTablesHTML += tableHTML;
        });

        if (allTablesHTML === "") {
          tableContainer.innerHTML = `<p>Ingen data att visa.</p>`;
        } else {
        tableContainer.innerHTML = allTablesHTML;
        }
      } catch (error) {
        console.error('Kunde inte hämta tabelldata:', error);
        document.getElementById('tableContainer').innerHTML = '<p>Ett fel uppstod vid hämtning av data.</p>';
      }
    });
  </script>
</body>

</html>
<?php $dbconn null ?>