PHP+sqlite3

本篇文章講述php怎麼與sqlite數據庫協做。php

PHP版本: 5.6.23
sqlite版本: 3.16.2

同mysql同樣,早期php操做這些數據庫都是分別調用各自的驅動。如今加入了PDO這個中間層。能夠看看我這篇筆記PDO用法記錄.下面講的代碼可能並不規範,可是可以工做,個人目的也在於此。html

sqlite3操做

廢話很少說,sqlite能夠看作是小型數據庫,去官網選擇相應版本解壓到某個目錄下,並把該目錄放到環境變量path中。mysql

用vscode打開項目目錄,Ctrl+`打開終端,輸入sqlite3.
clipboard.pngsql

出現上圖即表示安裝成功。shell

貌似sqlite3命令行不能自動完成,要添加的話得本身編譯源碼。see this數據庫

關於sqlite的命令行操做直接去官網看吧。segmentfault

不過有個快速的寫數據庫的辦法就是直接建sql文件,而後用如下命令將sql文件轉成sqlite3數據庫文件。經測試徹底可用。若是不能使用,請注意你的sql語法是否有誤。bash

這是我寫的sql文件,與sqlite3生成的不同,爲了預防出現問題,請使用簡單點的sql語句。測試

CREATE TABLE meals (dish text, price number, meal text);
INSERT INTO "meals" VALUES('eggs',12,'lunch');

這個命令將 .sql 轉成sqlite3支持的.dbfetch

cat test.sql | sqlite3 test.db

php.ini配置

首先確保php.ini裏的全部涉及sqlite的擴展打開。

而後把路徑添加進去,別忘了重啓。

測試

<form action="Ex1-7.php" method="POST">
  test sqlite3: <input type="text" name="meal">
  <br>
  <button type="submit">check meal</button>
</form>
<?php
// Use the SQLite database 'dinner.db'
$db = new PDO('sqlite:dinner.db');
// Define what the allowable meals are
$meals = array('breakfast','lunch','dinner');
// Check if submitted form parameter "meal" is one of
// "breakfast", "lunch", or "dinner"
// fixme: Undefined index: meals
if (in_array($_POST['meal'], $meals)) {
    // If so, get all of the dishes for the specified meal
    $stmt = $db->prepare('SELECT dish,price FROM meals WHERE meal LIKE ?');
    $stmt->execute(array($_POST['meal']));
    $rows = $stmt->fetchAll();
    // If no dishes were found in the database, say so
    if (count($rows) == 0) {
        print "No dishes available.";
    } else {
        // Print out each dish and its price as a row
        // in an HTML table
        print '<table><tr><th>Dish</th><th>Price</th></tr>';
        foreach ($rows as $row) {
            print "<tr><td>$row[0]</td><td>$row[1]</td></tr>";
        }
        print "</table>";
    }
} else {
    // This message prints if the submitted parameter "meal" isn't
    // "breakfast", "lunch", or "dinner"
    print "Unknown meal.";
}
?>

測試結果

clipboard.png

clipboard.png

clipboard.png

clipboard.png

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息