· 9 years ago · Nov 27, 2016, 03:24 AM
1#!/usr/local/bin/php -d display_errors=STDOUT
2<?php
3 // begin this XHTML page
4 print('<?xml version="1.0" encoding="utf-8"?>');
5 print("n");
6?>
7<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
8 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
9<html xmlns="http://www.w3.org/1999/xhtml"
10 xmlns:v="urn:schemas-microsoft-com:vml">
11<head>
12<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />
13<title>Accessing a SQLite 3 Database using PHP</title>
14</head>
15<body>
16<p>
17<?php
18
19
20$database = "students.db";
21
22
23try
24{
25 $db = new SQLite3($database);
26}
27catch (Exception $exception)
28{
29 echo '<p>There was an error connecting to the database!</p>';
30
31 if ($db)
32 {
33 echo $exception->getMessage();
34 }
35
36}
37
38
39// define tablename + fieldnames
40$table = "bruins";
41$field1 = "name";
42$field2 = "sid";
43$field3 = "gpa";
44
45
46// Create the table
47$sql= "CREATE TABLE IF NOT EXISTS $table (
48$field1 varchar(100),
49$field2 int(9),
50$field3 decimal(3,1)
51)";
52$result = $db->query($sql);
53
54print "<h3>Creating the table</h3>";
55print "<p>$sql</p>";
56
57// Extract SID and GPA from the $_GET data.
58$name = $_GET['name'];
59
60$SID = $_GET['SID'];
61
62$GPA = $_GET['GPA'];
63
64
65// Insert a new record to DB with name = $name, sid = $SID and gpa = $GPA
66$sql = "INSERT INTO $table ($field1, $field2, $field3)
67 VALUES ('$name', '$SID', '$GPA')";
68
69
70print "Inserting a new record to the bruins table the command I am using is:</br>";
71print "$sql";
72$result = $db->query($sql);
73
74
75// print an XHTML table to display the current table
76$sql = "SELECT * FROM $table";
77$result = $db->query($sql);
78
79
80print "<table border='border'>n";
81print " <tr>n";
82print " <th>" . $field1 . "</th>n";
83print " <th>" . $field2 . "</th>n";
84print " <th>" . $field3 . "</th>n";
85print " </tr>n";
86
87// obtain the results from the SELECT query as an array holding a record
88while($record = $result->fetchArray())
89{
90 print " <tr>n";
91 print " <td>" . $record[$field1] . "<td>n";
92 print " <td>" . $record[$field2] . "<td>n";
93 print " <td>" . $record[$field3] . "<td>n";
94 print " </tr>n";
95}
96
97print "</table>n";
98?>
99</body>
100</html>