🚧 Under construction — VoTechWorks is being built. A free tech program — complimentary, as our commitment to get America working.
voTechWorksGrade 13 · a vocational technology learning center, by urbanicity
newSchoolWorks.com › VoTechWorks › Technology & Design › Web & Software Development › PHP and Python Web Programming › Lesson 9
TEC-WEB46-03 · Lesson 9 · 15 clock hours · lab

Database Connectivity: PHP and Python with MySQL/MariaDB

Objective. Students connect PHP scripts using PDO and Python scripts using mysql-connector-python to a MySQL/MariaDB database and execute parameterized SELECT, INSERT, UPDATE, and DELETE statements safely

⚠ Pending professional review

This lesson, its worked examples and its practice questions has not yet been verified by an industry-certified professional or by a certification or approval body. It is a study draft and may contain errors. Do not use it as instructions for work on a job site or on live equipment. Always follow your instructor, your supervising professional, and current official references and regulations.

VoTechWorks program approval and accreditation are still in progress. Credentials are issued only by the certifying bodies named in each program, after their own exams.

Database Connectivity: PHP and Python with MySQL/MariaDB

Web applications almost always need to store and retrieve data. MySQL and MariaDB are open-source relational database management systems (RDBMS) that are widely used in professional web development. MariaDB is a community-maintained fork of MySQL that is largely compatible with MySQL at the application level. In this lesson you will connect both PHP and Python to a MySQL/MariaDB database and perform the four fundamental data operations: SELECT, INSERT, UPDATE, and DELETE — collectively called CRUD (Create, Read, Update, Delete).

Setting Up the Database

Before writing application code, you need a running MySQL or MariaDB server, a database, and a table. Log in to the MySQL shell with a privileged account and run statements similar to these:

```sql

CREATE DATABASE store_db;

USE store_db;

CREATE TABLE products (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,

price DECIMAL(10,2) NOT NULL,

quantity INT NOT NULL DEFAULT 0

);

```

Create a dedicated application user with only the permissions it needs — this principle of least privilege limits damage if credentials are ever exposed:

```sql

CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'StrongPassword!';

GRANT SELECT, INSERT, UPDATE, DELETE ON store_db.* TO 'app_user'@'localhost';

FLUSH PRIVILEGES;

```

Never connect your application with the root database account.

Connecting from PHP Using PDO

PHP Data Objects (PDO) is a database-abstraction layer built into PHP. It provides a consistent interface regardless of which database you use and — critically — supports prepared statements natively.

A basic PDO connection looks like this:

```php

<?php

$dsn = 'mysql:host=localhost;dbname=store_db;charset=utf8mb4';

$username = 'app_user';

$password = 'StrongPassword!';

$options = [

PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,

PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,

];

try {

$pdo = new PDO($dsn, $username, $password, $options);

} catch (PDOException $e) {

// Log the real error privately; show a generic message to users

error_log($e->getMessage());

die('Database connection failed.');

}

```

Setting `ERRMODE_EXCEPTION` causes PDO to throw a `PDOException` on errors, which you can catch and handle without exposing internal details to the browser.

Connecting from Python Using mysql-connector-python

Install the connector with pip:

```

pip install mysql-connector-python

```

A basic connection:

```python

import mysql.connector

from mysql.connector import Error

try:

conn = mysql.connector.connect(

host='localhost',

database='store_db',

user='app_user',

password='StrongPassword!'

)

except Error as e:

print(f'Connection error: {e}')

conn = None

```

Always check that `conn` is not `None` before proceeding, and close the connection when finished.

Parameterized Queries and SQL Injection

SQL injection is one of the most dangerous and common web vulnerabilities. It occurs when user-supplied input is concatenated directly into a SQL string. An attacker can craft input that alters the query's logic, dumps data, or destroys a database.

The defense is parameterized queries (also called prepared statements). The database driver sends the query structure to the server separately from the data. The server treats the data as plain values — never as executable SQL.

PHP PDO — parameterized INSERT:

```php

$sql = 'INSERT INTO products (name, price, quantity) VALUES (:name, :price, :quantity)';

$stmt = $pdo->prepare($sql);

$stmt->execute([':name' => $name, ':price' => $price, ':quantity' => $qty]);

```

Python — parameterized INSERT:

```python

cursor = conn.cursor()

sql = 'INSERT INTO products (name, price, quantity) VALUES (%s, %s, %s)'

values = (name, price, qty)

cursor.execute(sql, values)

conn.commit()

```

Note the syntax difference: PDO uses named placeholders (`:name`) or positional `?` placeholders; mysql-connector-python uses `%s` positional placeholders regardless of data type.

CRUD Operations

SELECT (Read): Use a prepared statement with any WHERE conditions parameterized. In PHP, call `$stmt->fetchAll()` or `$stmt->fetch()`. In Python, call `cursor.fetchall()` or `cursor.fetchone()`.

UPDATE: Prepare the UPDATE statement with placeholders for both the new values and the WHERE clause. Always include a WHERE clause — an UPDATE without one modifies every row.

DELETE: The same rule applies. Parameterize the identifier in the WHERE clause and double-check the logic before execution.

After INSERT, UPDATE, or DELETE in Python, call `conn.commit()` to persist changes. PDO auto-commits by default unless you start a transaction manually.

Security and Safe Practices

These practices align with standard secure-coding guidance and are tested in vendor-neutral credentials such as CompTIA ITF+.

Key terms9

PDO (PHP Data Objects)A PHP extension that provides a consistent, database-agnostic interface for connecting to relational databases and supports prepared statements natively.
mysql-connector-pythonThe official Python library provided by MySQL/Oracle for connecting Python applications to MySQL and MariaDB databases.
Parameterized queryA query in which placeholders replace user-supplied values; the database driver sends query structure and data separately so user input can never be interpreted as SQL commands.
SQL injectionA security attack in which malicious SQL is embedded in user input and executed by the database because the application concatenated input directly into a query string.
CRUDAn acronym for the four basic database operations: Create (INSERT), Read (SELECT), Update (UPDATE), and Delete (DELETE).
Prepared statementA pre-compiled SQL statement sent to the database server before data values are supplied; the server parses the structure once and executes it with bound parameters.
Principle of least privilegeA security principle stating that a user or process should be granted only the minimum permissions necessary to perform its function.
DSN (Data Source Name)A string passed to PDO that specifies the database driver, host, database name, and character set needed to establish a connection.
PDOExceptionThe PHP exception class thrown by PDO when a database error occurs and the error mode is set to ERRMODE_EXCEPTION; it should be caught and logged without exposing details to users.
In class: Guided setup lab: students install and configure a local MySQL/MariaDB instance (or use a provided VM), create a database and a products table, and connect to it from both a PHP PDO script and a Python connector script — they verify the connection and handle connection errors · CRUD lab: students build a PHP product-management page (list, add, edit, delete) and a matching Python CLI tool; both use parameterized queries exclusively — instructor demonstrates a SQL injection attack against a non-parameterized query before students write their own · Students read the PHP PDO documentation section on prepared statements and the mysql-connector-python documentation section on parameterized queries; they write a one-page comparison of how each language implements parameterization and why it matters for security
Materials: PHP PDO docs (php.net/manual/en/book.pdo.php), mysql-connector-python docs (dev.mysql.com), MySQL/MariaDB, VS Code, local server environment
Check: CRUD operations work correctly for all four operations in both PHP and Python; all queries use parameterization (instructor inspects code — no string concatenation in queries allowed); written comparison is accurate and complete — pass requires all criteria met

Practice check8

Answer each question, then check it. Nothing is recorded; this is your own practice.

CompTIA ITF+ — Software Development Concepts
1. Which PDO attribute setting causes PDO to throw a PDOException when a database error occurs?
PCEP Python — Python in Practice
2. In mysql-connector-python, which placeholder character is used in parameterized query strings?
CompTIA ITF+ — Security Concepts
3. A developer writes this PHP code to fetch a product: $sql = "SELECT * FROM products WHERE id = " . $_GET['id']; What is the primary security risk?
PCEP Python — Python in Practice
4. After executing an INSERT statement in Python with mysql-connector-python, what must the developer call to save the change to the database?
CompTIA ITF+ — Security Concepts
5. Which security principle is applied when the application's database user is granted only SELECT, INSERT, UPDATE, and DELETE — but not DROP or CREATE?
CompTIA Linux+ — Databases and Services
6. A student writes an UPDATE statement without a WHERE clause. What is the result?
CompTIA ITF+ — Security Concepts
7. Where should database credentials (username and password) be stored in a production web application?
CompTIA ITF+ — Software Development Concepts
8. Which of the following best describes what a prepared statement sends to the database server?
Record this lesson on my transcript. Sign in with your key and enrollment email to record lessons (enroll free if you have no key). This page stays open to read and practise.