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

fetch_car_things.php

53 lines UTF-8 Windows (CRLF)
<?php
/**
 * Fetches all data from kompisar table
 */

// show all error reporting
error_reporting(-1); // Report all type of errors
ini_set('display_errors'1); // Display all errors 
ini_set('output_buffering'0); // Do not buffer outputs, write directly


// Signalera att vi kommer retunera JSON
header('Content-Type: application/json');

include(
'../../incl/dbconnection.php');
/**
 * @var PDO $dbconn
 */

if (!$dbconn) {
  
http_response_code(500);
  echo 
json_encode(['error' => 'Database connection failed.']);
  exit;
}

// Set PDO to throw exceptions on error. This is crucial for the try/catch to work reliably.
$dbconn->setAttribute(PDO::ATTR_ERRMODEPDO::ERRMODE_EXCEPTION);

try {
  
// Alla tabeller vi vill hämta från
  
$tables = ["cars""owners""garage"];
  
  
// Hämta data från alla tabeller
  
$results = [];
  foreach (
$tables as $value) {
    
$sql "SELECT * FROM $value";
    
    
// Use prepare/execute for better security and error handling, even with hardcoded table names.
    
$stmt $dbconn->prepare($sql);
    
$stmt->execute();
    
    
$results[$value] = $stmt->fetchAll(PDO::FETCH_ASSOC);
  }

  
// Skicka som JSON kod
  
echo json_encode($results);
} catch (
PDOException $e) {
  
http_response_code(500);
  echo 
json_encode(['error' => 'Database query failed: ' $e->getMessage()]);
}

$dbconn null
?>