Chapter 7 - Web & Database
* [Chapter 7 - Web \& Database](#chapter-7---web--database)
Chapter 7 - Web & Database
Index
7.1 Introduction to SQL and DBMS.
DBMS
- collection of programs that manages the database structure and controls access to the data stored in the database.
- MySQL
- Microsoft SQL Server
- Oracle
- PostgreSQL
- SQLite
- Microsoft Access
MySQL
- Free, open-source relational DBMS
- A component of LAMP (Linux, Apache, MySQL, PHP) stack.
- Runs on Linux/Unix, Windows, and Mac OS.
- Access to data based on SQL (Structured Query Language).
- Can be used in many different programming languages.
Pseudo Code
- Connect to host server.
- Select database.
- Write SQL statement
- Execute SQL statement
- Close connection
System Architecture

Database Connection
- Required Information:
- Hostname
- Username
- Password
- Database Name
- PHP can work with a MySQL database using the following methods:
- MySQL extension: deprecated in 2012.
- MySQLi extension: improved version of MySQL.
- PDO (PHP Data Objects): a data-access abstraction layer.
- PDO works on various DBMS, whereas MySQLi works only with MySQL.
MySQLi
- The mysqli extension supports the following approaches:
- Procedural approach
- Object-oriented approach
- Reference to a complete list of the properties and methods of the mysql:
- MySQLi Reference
- Procedural Example:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$query = "SELECT * FROM table";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result))
{
// use row to fetch the elements of each column
}
mysqli_close($conn);
?>
- Object-oriented Example:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$query = "SELECT * FROM table";
$result = $conn->query($query);
$row = $result->fetch_assoc();
echo $row["column_name"];
$conn->close();
?>
PDO
- PDO Example:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
?>
SQL (Structured Query Language)
- A standard language for specifying accesses and modifications to relational databases.
- Supported by DBMS of major vendors.
- Reserved words are not case-sensitive, but table names and table columns may/may not be case-sensitive depending on vendor.
DML && DDL
- SQL can be divided into TWO parts:
- DML (Data Manipulation Language):
- SELECT: extracts data from a database.
- INSERT: inserts new data into a database.
- UPDATE: updates existing data within a database.
- DELETE: deletes all records from a table.
- DDL (Data Definition Language):
- CREATE DATABASE: creates a new database.
- ALTER DATABASE: modifies a database.
- CREATE TABLE: creates a new table.
- ALTER TABLE: modifies a table.
- DROP TABLE: deletes a table.
- CREATE INDEX: creates an index (search key).
- DROP INDEX: deletes an index.
SELECT Statement
- The
SELECTstatement is used to select data from a database. - The
SELECTstatement returned ALL the results from the queried database table. - A simple
SQL SELECTstatement, requires:- Column(s) Name
- Table Name
- Syntax:
SELECT column1, column2, ... FROM table_name;
WHERE Clause
- The
WHEREclause not only used inSELECTstatement, but itUPDATE,DELETEstatement etc. - The
WHEREclause is used toFILTERrecords that satisft a given condition. - The
WHEREclause returnedMATCHINGresults from the queried database table restricted to a specific condition. - "condition" is the filter to be applied on the results. The filter could be a range, single value or sub query.
- With the WHERE clause, the following operators can be used:
-
Operator Description = Equal <> Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern IN To specify multiple possible values for a column
-
#### AND, OR, NOT
- The
AND,OR,NOToperators are used to filter records based on more than one condition. - Exmaple:
SELECT * FROM table_name WHERE column1 = value1 AND column2 = value2;
DISTINCT
- some of the columns may contain duplicate values. This is not a problem, however, sometimes there is a need to list only the different (distinct) values in a table.
- The
DISTINCTkeyword can be used to return only distinct (different) values. - The SQL
DISTINCTkeyword is used in conjunction withSELECTstatement to eliminate all the duplicate records and fetching only unique records. - Example:
SELECT DISTINCT column1, column2, ... FROM table_name;
JOIN
- The
JOINkeyword is used in an SQL statement to query data from TWO or more tables, based on a relationship between certain columns in these tables. - The
INNER JOINkeyword return rows when is at least ONE match in BOTH tables. - IF there are rows in table1 do not have matches in table2, these rows will NOT be listed.
- Example:
SELECT column_name(s) FROM table1 INNER JOIN table2 ON table1.PK = table2.FK;
ORDER BY
- The
ORDER BYkeyword is used to sort the query result by a specified column. - Example:
SELECT column1, column2, ... FROM table_name ORDER BY column1, column2, ... ASC|DESC;
INSERT
- The
INSERT INTOstatement is used to insert new records in a table. - Example:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
UPDATE
- The
UPDATEstatement is used to modify the existing records in a table. - Example:
UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
DELETE
- The
DELETEstatement is used to delete existing records in a table. - Example:
DELETE FROM table_name WHERE column1 = value1;
7.2 Design and model database
Database Model
- An entity represents a particular type of object in the real-world.
- An attribute is a characteristic of an entity.
- A relationship is an association among entities.
- One-to-many (1:M)
- Many-to-many (M:N)
- One-to-one (1:1)
- A constraint is a restriction placed on the data.
Data Dictionary

Table
- Databases are usually organized into one or more tables.
- A table is a collection of related records regarding an entity.
- A table stores data in a series of columns and rows.
Column
- Columns are the attributes or quanlities of the entity described by the table.
- Example:
- Entity: Student
- Attribute (column): student_id
- Each column contains a different type of attribute.
- known as fields.
- A field is an area (within a record) reserved for a specific piece of data.
- Example:
- Fields are defined by field name, data type, and field size.
- Field name
- Each column needs a heading to identify the data it contains.
- These headings are called field names.
- Field names are used to ensure that the data for each record is entered in the same sequence.
- Data type
- Data type ensures that all the data in a column is entered using the same format.
- Example:
- Character: text including such things as telephone numbers, zip codes.
- Numeric: numbers.
- Date: dates.
- Logical: true/false or yes/no.
- Field Size
- Field size are the amount of space reserved for storing data
Row
- Rows are knows as records.
- A record is the collection of values for all the fields pertaining to one entity.
- Every record in a table has exactly the same structure, but different data.
- Each row corresponds to a single record.
- Rows hold the actual data, with one (or zero) items for each column of the table.
- Each row is identified by the values appearing in a particular column which has been identified as a unique INDEX.
Primary Key
- Primary key is a special column or combination of columns that uniquely identifies each record (row) in a table.
- The value that primary key hold must be unique for each record (row), and must not contain any nulls (non-values).
- If it's possible that TWO or more records (past, present, or future) may share the same value for an attribute, it's a poor choice for a primary key.
Example
| Name | Department | Position |
|---|---|---|
| John | Customer management | Clerk |
| Paul | Customer management | Manager |
| Bill | Human Resource | Accountant |
- No field is going to be guaranteed unique.
- There are many people that share the smae name / department / position that may be added to the database in ther future.
Solution:
- To avoid the uncertainty of using a data column as a primary key, many developers will create their own column which contains a computer generated unique value.
- The Auto Increment Data type automatically increments the field each time a new record is created/
- Hence, a better choice might be to use a unique employee ID nummber that you assign to each employee record when they're created.
- Once you decide upon a primary key and set it up in the database, the database management will enforce the uniqueness (entity integrity - PK must be unique and not be null) of the primary key.
- If a record to be inserted into a table has a primary key that duplicates an existing record, the insertion will fail.
Foreign Key
- Foreign keys are columns in a table which provide a link to another table.
- It is used to create relationships (correlate information) between tables.
- Primary key uniquely defines a record, while a foreign key is used to reference the same record from another table.
- When a table's primary key field is added to another table in order to relates the two tables, it is called a foreign key in the referenced table.
- It is not necessarily that a primary key has any corresponding value in the referenced table.
- Similarly, the value used in a Foreign Key column is not necessarily unique to the table it is in but must be unique to the table it is referring to (Referencial Integrity).
Example:
| cust_id (PK) | cust_name | cust_gender |
|---|---|---|
| 001 | John | Male |
| 002 | Paul | Male |
| 004 | Lilly | Female |
| order_id (PK) | item | cust_id (FK) |
|---|---|---|
| 001 | book | 001 |
| 002 | shirt | 002 |
| 003 | pen | 002 |
- We don't need to store all the other customer information (name, gender, etc.) in the order table.
- This is the elegance of the relational model.
- Referential integrity is a database concept that ensures that relationships between tables remain consistent.
- When one table has a foreign key to another table, the concept of referential integrity states that you may not add a record to the table that contains the foreign key unless there is a corresponding record in the linked table.
- It also includes the techniques known as cascade delete and cascade update, which ensure that changes made to the linked table are reflected in the primary table.
- Refertial integrity enforces the following three rules:
- The Order's FK attribtue must points to a valid record in the Customer table.
- If the primary key for a record in the Customer table changes, all corresponding records in the Order table must be modified using a cascading update.
- If a record in the Customer table is deleted, all corresponding records in the Order table must be deleted using a cascading delete.
Relationship
- Relationships are they very core of relational databases.
- The primary key, together with the closely related foreign key concept, are the main way in which relationships are defined.
- Relationships allows description of the connections between different database tables in powerfull ways.
- Once the relationships between your tables are described, that information can be used to perform powerful cross-table queries, known as joins.
- In relational databases, a relationship exists between two tables when one of them has a foreign key that references the primary key of the other table.
- There are three types of relationships:
- One-to-one (1:1)
- One-to-many (1:M)
- Many-to-many (M:N)
- Each relationship are named according to the number of tables rows that may be involved in the relationship.
One-to-Many (1:1)
- Occur when each entry in the first table has one, and only one, counterpart in the second table.
- One-to-one relationships are rarely used because it's often more efficient to simply put all of the information in a single table.
- It would be possible, although not really desirable, to store all the information in one table in this case.
One-to-Many (1:M)
- This is the most common type of database relationship.
- It occur when each record in the first table corresponds to one or more records in the second table but each record in the second table corresponds to only one record in the first table.
- Example:
- Each student has only one teacher, but each teacher may have multiple students.
Many-to-Many (M:N)
- This relationship occur when each record in the first table corresponds to one or more records in the second table and each record in the second table corresponds to one or more records in the first table.
- Example:
- Each Teacher may instruct more than one course and each course may be taught by more than one teacher.
- an order can contain many products, and a product can be included in many orders.
Normalization
- Process of evaluating and correcting table structures to minimize data redundancy and reduce the likelihood of data anomalies.
Related Documents
Design Document: BharatSeva AI
BharatSeva AI is a multi-agent orchestration system built on AWS using Amazon Bedrock Agents with Claude 3.5 Sonnet as the foundation model. The system deploys 10 AI agents (1 Master Orchestrator + 9 Specialist Agents) to assist India's informal sector workers in navigating government schemes across three domains: PM Vishwakarma (artisan credit), PMFBY (crop insurance), and BOCW (construction worker welfare).
OpenClaw Enterprise Transformation Plan
Transform OpenClaw from a single-user personal AI assistant into a **dual-mode platform** that is simultaneously:
Qwen Image and Edit: Open-sourcing and Local GGUF Generations with Lightning
Daniel Sandner, for article on https://sandner.art/
Qwen3-TTS — Model Reference
Models: `Qwen/Qwen3-TTS-12Hz-0.6B-CustomVoice` and `Qwen/Qwen3-TTS-12Hz-1.7B-CustomVoice`