Conectar a um banco de dados e executar instruções SQL

Documentação da API
  • Vermelho
  • Verde
  • Azul
  • Amarelo
Id URL Método Tipo de Dispositivo Tipo de SO SO Navegador User-Agent Data Requisitado
736 /pt-BR/examples/database-demo GET Bot Bot CCBot/2.0 (https://commoncrawl.org/faq/) 2022-11-30 00:08:49
735 /zh-CN/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; MJ12bot/v1.4.8; http://mj12bot.com/) 2022-11-29 23:02:16
734 /pt-BR/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; MJ12bot/v1.4.8; http://mj12bot.com/) 2022-11-29 22:57:14
733 /pt-BR/examples/database-demo GET Desktop Linux Linux Chrome Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36 2022-11-29 07:14:33
732 /zh-CN/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; SemrushBot/7~bl; +http://www.semrush.com/bot.html) 2022-11-29 03:20:32
731 /en/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; SemrushBot/7~bl; +http://www.semrush.com/bot.html) 2022-11-29 00:07:01
730 /fr/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; SemrushBot/7~bl; +http://www.semrush.com/bot.html) 2022-11-28 23:40:45
729 /zh-CN/examples/database-demo GET Bot Bot Google Bot Bot Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) 2022-11-28 22:41:25
728 /es/examples/database-demo GET Desktop Windows Windows 10 Chrome Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Vivaldi/5.3.2679.68 2022-11-28 21:27:58
727 /en/examples/database-demo GET Desktop Windows Windows 10 Chrome Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Vivaldi/5.3.2679.68 2022-11-28 21:27:57
726 /fr/examples/database-demo GET Desktop Windows Windows 10 Chrome Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Vivaldi/5.3.2679.68 2022-11-28 21:27:56
725 /pt-BR/examples/database-demo GET Desktop Windows Windows 10 Chrome Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Vivaldi/5.3.2679.68 2022-11-28 21:27:49
724 /ar/examples/database-demo GET Desktop Windows Windows 10 Chrome Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Vivaldi/5.3.2679.68 2022-11-28 21:27:43
723 /zh-CN/examples/database-demo GET Desktop Windows Windows 10 Chrome Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Vivaldi/5.3.2679.68 2022-11-28 21:27:37
722 /en/examples/database-demo GET Desktop Windows Windows 10 Chrome Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36 Vivaldi/5.3.2679.68 2022-11-28 21:27:28
721 /es/examples/database-demo GET Desktop Linux Linux Chrome Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36 2022-11-28 19:58:10
720 /zh-CN/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; SemrushBot/7~bl; +http://www.semrush.com/bot.html) 2022-11-28 19:29:40
719 /en/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; SeznamBot/4.0-RC1; +http://napoveda.seznam.cz/seznambot-intro/) 2022-11-28 15:02:08
718 /en/examples/database-demo GET Desktop Windows Windows 7 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534+ (KHTML, like Gecko) BingPreview/1.0b 2022-11-28 12:54:34
717 /en/examples/database-demo GET Bot Bot Bing Bot Bot Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm) 2022-11-28 12:54:25

Visão geral do código do banco de dados

// Conecte a um Banco de Dados
$db = new \FastSitePHP\Data\Database($dsn, $user, $password);

// Consulta para Múltiplos Registros
// Retorna um Array de Registros (Array Associativo para cada Registro).
$sql = 'SELECT * FROM pages';
$records = $db->query($sql);

// Consulta para um registro. Retorna um Array Associativo ou [null] se não
// encontrado. Ambas [query()] e [queryOne()] suportam parâmetros opcionais ao
// consultar.
$sql = 'SELECT * FROM pages WHERE id = ?';
$params = [1];
$record = $db->queryOne($sql, $params);

// Utiliza [execute()] para INSERT, UPDATE, DELETE, CREATE e outras Transações.
// Além de utilizar [?] você pode também utilizar parâmetros nomeados no formato
// ":name". Parâmetros nomeados capo tornar o código mais fácil de ler.
$sql = 'INSERT INTO pages (title, content)';
$sql .= ' VALUES (:title, :content)';
$params = [
    'title'   => 'Banco de Dados de Demonstração',
    'content' => '<h1>Banco de Dados de Demonstração<h1>',
];
$rows_affected = $db->execute($sql, $params);

// Muitos exemplos adicionais pode ser encontrados na página Referência Rápida.

Código PHP para esta página

<?php

namespace App\Controllers\Examples;

use FastSitePHP\Application;
use FastSitePHP\Data\Database;
use FastSitePHP\Lang\I18N;
use FastSitePHP\Web\Request;

class DatabaseDemo
{
    /**
     * Return HTML for the Web Page
     */
    public function get(Application $app, $lang)
    {
        // Load Language File
        I18N::langFile('database-demo', $lang);

        // Add Code Example from text file
        $file_path = $app->config['I18N_DIR'] . '/code/database-demo.{lang}.txt';
        $app->locals['i18n']['db_code'] = I18N::textFile($file_path, $app->lang);

        // Add a record for the request and get the 20 most recent records
        $records = $this->insertAndSelectRecords($app);

        // Render the View
        $templates = [
            'old-browser-warning.htm',
            'examples/database-demo.php',
            'examples/database-demo.htm',
            'table-highlighter.htm',
        ];
        return $app->render($templates, [
            'nav_active_link' => 'examples',
            'records' => $records,
            'controller_code' => file_get_contents(__FILE__),
        ]);
    }

    /**
     * JSON Service that logs requests from button clicks.
     * Returns the 20 most recent records.
     */
    public function routePage(Application $app, $lang, $color)
    {
        return ['records' => $this->insertAndSelectRecords($app)];
    }

    /**
     * Add a record for the request and return recent records
     */
    private function insertAndSelectRecords(Application $app)
    {
        $db = $this->connectToDb();
        $this->insertRecord($app, $db);
        $records = $this->getRecentRecords($db);
        return $records;
    }

    /**
     * Return a Db Connection to a SQLite Database in the Temp
     * Directory. Create the file if it doesn't yet exist.
     */
    private function connectToDb()
    {
        // Path to SQLite Db
        $path = sys_get_temp_dir() . '/database-demo.sqlite';
        $this->checkDb($path);

        // Connect and create table the first time the db is used
        $dsn = 'sqlite:' . $path;
        $db = new Database($dsn);
        $sql = <<<'SQL'
            CREATE TABLE IF NOT EXISTS requests (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    url TEXT,
                    method TEXT,
                    user_agent TEXT,
                    date_requested TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
SQL;
        $db->execute($sql);
        return $db;
    }

    /**
     * Delete the SQLite Database every time it reaches over 10 megabytes.
     * It is intended only as a temporary database for this demo page.
     */
    private function checkDb($path) {
        if (is_file($path)) {
            $ten_megabytes = (1024 * 1024 * 10);
            $file_size = filesize($path);
            if ($file_size > $ten_megabytes) {
                unlink($path);
                // Add to a log file each time it's removed
                $log_path = sys_get_temp_dir() . '/database-demo.txt';
                $now = date(DATE_RFC2822);
                $contents = "${path} deleted at ${now}\n";
                file_put_contents($log_path, $contents, FILE_APPEND);
            }
        }
    }

    /**
     * Insert a Record for each Request
     */
    private function insertRecord(Application $app, Database $db)
    {
        $req = new Request();
        $sql = 'INSERT INTO requests (url, method, user_agent) VALUES (?, ?, ?)';
        $params = [$app->requestedPath(), $req->method(), $req->userAgent()];
        $db->execute($sql, $params);
    }

    /**
     * Return the 20 most recent records.
     * The SELECT statement is defined in a [*.sql] file,
     * which allows for easy editing and testing outside of PHP code.
     */
    private function getRecentRecords(Database $db)
    {
        $sql = file_get_contents(__DIR__ . '/../../Models/DatabaseDemo.sql');
        $records = $db->query($sql);
        return $records;
    }
}