Conéctese a una base de datos y ejecute sentencias SQL

Documentación API
  • Rojo
  • Verde
  • Azul
  • Amarillo
ID URL Método Tipo de Dispositivo Tipo de Sistema Operativo OS Navegador Agente de usuario Fecha solicitada
2474 /es/examples/database-demo GET Bot Bot Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com) 2026-07-13 03:56:05
2473 /fr/examples/database-demo GET Bot Bot serpstatbot/2.1 (advanced backlink tracking bot; https://serpstatbot.com/; abuse@serpstatbot.com) 2026-07-13 03:43:29
2472 /zh-CN/examples/database-demo GET Desktop Mac Mac OS X Chrome Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 2026-07-13 03:13:49
2471 /zh-CN/examples/database-demo GET Bot Bot serpstatbot/2.1 (advanced backlink tracking bot; https://serpstatbot.com/; abuse@serpstatbot.com) 2026-07-13 02:35:04
2470 /ar/examples/database-demo GET Bot Bot Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com) 2026-07-13 02:26:03
2469 /pt-BR/examples/database-demo GET Scrapy/2.16.0 (+https://scrapy.org) 2026-07-13 02:22:31
2468 /pt-BR/examples/database-demo GET Bot Bot serpstatbot/2.1 (advanced backlink tracking bot; https://serpstatbot.com/; abuse@serpstatbot.com) 2026-07-13 02:07:48
2467 /es/examples/database-demo GET Mobile / Phone iOS iOS / iPhone Chrome Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.5973.1226 Mobile Safari/537.36 2026-07-13 01:08:57
2466 /en/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; SeznamBot/4.0; +https://o-seznam.cz/napoveda/vyhledavani/en/seznambot-crawler/) 2026-07-13 00:58:34
2465 /es/examples/database-demo GET Mobile Android Android 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible Webkit Mozilla/5.0 (Linux; Android 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible; Bytespider; https://zhanzhang.toutiao.com/) 2026-07-12 21:53:42
2464 /es/examples/database-demo GET Bot Android Android 6.0.1 Chrome Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.7871.46 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) 2026-07-12 20:48:11
2463 /es/examples/database-demo GET Mobile Android Android 8.0 Chrome Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.7143.1785 Mobile Safari/537.36 2026-07-12 18:22:58
2462 /pt-BR/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; DotBot/1.2; +https://opensiteexplorer.org/dotbot; help@moz.com) 2026-07-12 16:59:13
2461 /zh-CN/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; DotBot/1.2; +https://opensiteexplorer.org/dotbot; help@moz.com) 2026-07-12 16:48:35
2460 /zh-CN/examples/database-demo GET Mobile Android Android 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible Webkit Mozilla/5.0 (Linux; Android 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible; Bytespider; spider-feedback@bytedance.com) 2026-07-12 16:32:07
2459 /es/examples/database-demo GET Mobile Android Android 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible Webkit Mozilla/5.0 (Linux; Android 5.0) AppleWebKit/537.36 (KHTML, like Gecko) Mobile Safari/537.36 (compatible; Bytespider; https://zhanzhang.toutiao.com/) 2026-07-12 15:30:23
2458 /ar/examples/database-demo GET Bot Bot Mozilla/5.0 (compatible; DotBot/1.2; +https://opensiteexplorer.org/dotbot; help@moz.com) 2026-07-12 15:05:38
2457 /en/examples/database-demo GET Bot Bot Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com) 2026-07-12 14:26:24
2456 /fr/examples/database-demo GET Mobile / Phone iOS iOS / iPhone Safari Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 2026-07-12 14:20:31
2455 /pt-BR/examples/database-demo GET Mobile / Phone iOS iOS / iPhone Safari Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 2026-07-12 13:17:53

Descripción general del código de base de datos

// Conectarse a una base de datos
$db = new \FastSitePHP\Data\Database($dsn, $user, $password);

// Consulta para registros múltiples
// Devuelve una matriz de registros (matriz asociativa para cada registro).
$sql = 'SELECT * FROM pages';
$records = $db->query($sql);

// Consulta para un registro. Devuelve una matriz asociativa o [nulo] si
// no se encuentra. Tanto [query()] como [queryOne()] admiten parámetros
// opcionales al realizar consultas.
$sql = 'SELECT * FROM pages WHERE id = ?';
$params = [1];
$record = $db->queryOne($sql, $params);

// Utilice [execute()] para INSERT, UPDATE, DELETE, CREATE y otras transacciones.
// Además de usar [?] También puede usar parámetros con nombre en el formato
// de ':nombre'. Los parámetros con nombre pueden hacer que el código sea más
// fácil de leer.
$sql = 'INSERT INTO pages (title, content)';
$sql .= ' VALUES (:title, :content)';
$params = [
    'title'   => 'Database Demo',
    'content' => '<h1>Database Demo<h1>',
];
$rows_affected = $db->execute($sql, $params);

// Se pueden encontrar muchos ejemplos adicionales en la página de
// referencia 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;
    }
}