Topics Covered in This PHP & MySQL Tutorial:
The INSERT Statement, Using PhpMyAdmin, Inserting Information from a Form
Tutorial Learning Objectives
INSERT Statement Mastery
Learn the fundamental SQL INSERT syntax and prepared statement implementation for secure database operations.
PhpMyAdmin Navigation
Master database management interface for viewing tables, structures, and inserted records in real-time.
Form Data Integration
Connect HTML forms to MySQL databases with proper validation and sanitization techniques.
Exercise Overview
Database interaction without the ability to add data would be fundamentally limiting. In this comprehensive tutorial, we'll master inserting records into a MySQL database using prepared statements—a secure approach that protects against SQL injection attacks while maintaining code efficiency. Even when dealing with static data, prepared statements represent the professional standard and should become second nature in your development workflow.
Open insert-easy.php from the phpclass folder.
We'll begin with a straightforward INSERT statement to add data to the users table using prepared statements. While this simple example doesn't involve user input, developing muscle memory with prepared statements is crucial—they're the foundation of secure database operations and a non-negotiable skill in professional PHP development.
First, establish the database connection by adding the connection script at the top of the page:
<?php require_once('inc/dbConnect.php'); ?>Next, we'll construct the INSERT statement with parameter placeholders. Add the following code:
require_once('inc/dbConnect.php'); $SQL = "INSERT INTO users (firstName, lastName, email) VALUES (?, ?, ?) ";This demonstrates the fundamental syntax of a SQL INSERT statement: specify the target table and columns, then define the values. The question mark placeholders (?) are essential for prepared statements, creating a template that separates the SQL structure from the actual data—a critical security measure.
Create variables to store the data parameters. This step is mandatory because the
bind_param()function requires variable references, not literal strings:$SQL = "INSERT INTO users (firstName, lastName, email) VALUES (?, ?, ?) "; $firstName = 'George'; $lastName = 'Washington'; $email = 'george@foundingfathers.gov';Initialize and prepare the statement object for execution:
$firstName = 'George'; $lastName = 'Washington'; $email = 'george@foundingfathers.gov'; $stmt = $conn->stmt_init(); $stmt->prepare($SQL);The preparation phase compiles the SQL statement and optimizes it for execution, while maintaining the separation between code and data that makes prepared statements so secure.
Bind the parameters to their respective placeholders:
$firstName = 'George'; $lastName = 'Washington'; $email = 'george@foundingfathers.gov'; $stmt = $conn->stmt_init(); $stmt->prepare($SQL); $stmt->bind_param('sss', $firstName, $lastName, $email);The first parameter
'sss'specifies data types: each s represents a string. This type specification allows MySQL to optimize storage and validates data integrity. Match the number of type specifiers to your parameters—three variables require three type indicators.Execute the prepared statement and implement error handling:
$stmt = $conn->stmt_init(); $stmt->prepare($SQL); $stmt->bind_param('sss', $firstName, $lastName, $email); $stmt->execute(); if ($stmt->error) { echo $stmt->errno. ": ". $stmt->error; }This executes the query and implements basic error detection. If an error occurs, the code outputs both the error number (
$stmt->errno) and a human-readable description ($stmt->error). A typical error might read: "2031: No data supplied for parameters in prepared statement"—invaluable for debugging during development.Save the file and test it in your browser:
- Mac: localhost:8888/phpclass/insert-easy.php
- Windows: localhost/phpclass/insert-easy.php
A successful execution displays a blank page with no error messages. While visually unremarkable, this represents successful database manipulation—your INSERT statement has executed and added the record to the users table.
Even for simple examples without user input, using prepared statements builds good security habits and protects against future vulnerabilities when scaling applications.
Basic INSERT Implementation Process
Include Database Connection
Add the dbConnect.php file to establish MySQL connection with proper error handling
Define INSERT Statement
Create SQL string with placeholder question marks for prepared statement parameters
Initialize Variables
Set up firstName, lastName, and email variables since bind_param only accepts variables, not strings
Prepare and Execute
Initialize statement, bind parameters with data types, execute query, and implement error checking
Viewing the Table in PhpMyAdmin
Now let's verify our database operations using phpMyAdmin, the web-based MySQL administration tool that provides a visual interface for database management.
Access phpMyAdmin through your development environment:
Mac Users:- Switch to MAMP PRO
- Click the WebStart button
- In the control panel, navigate to Tools and select phpMyAdmin
- Open your browser and navigate to http://localhost
- In the XAMPP control panel, locate the Tools section and click phpMyAdmin
In the phpMyAdmin interface, click phpclass_yourname in the left sidebar to access your database.
Locate the users table and click the Browse icon
to view all records:
You should see all existing database records, including the George Washington entry you just inserted. This visual confirmation validates that your INSERT operation executed successfully.
PhpMyAdmin Access Methods
| Feature | Mac (MAMP PRO) | Windows (XAMPP) |
|---|---|---|
| Initial Step | Switch to MAMP PRO | Open browser to localhost |
| Access Method | Click WebStart button | Navigate to start page |
| Tool Selection | Tools > phpMyAdmin | Tools section > phpMyAdmin |
Database Record Verification Steps
Locate your specific database instance in the left sidebar
View all existing records including newly inserted data
Confirm the INSERT operation successfully added the test record
Inserting Information from a Form
Now we'll tackle a more realistic scenario: processing user-submitted form data and inserting it into the database. This represents the typical workflow in web applications where users provide information through HTML forms. We'll work with a pre-built form that includes validation and input sanitization—essential security measures for production applications.
In phpMyAdmin, click phpclass_yourname to return to your database overview.
Access the table structure by clicking the Structure icon
next to the users table:
We need to expand the table structure to accommodate additional form fields. In the Add field, enter 3 and click Go:

Configure the new fields with the following specifications:
Name Type Length/Values null publications VARCHAR 255 checked comments TEXT checked subscribe TINYINT 1 checked Understanding these field types is crucial for efficient database design:
- publications: A VARCHAR(255) field suitable for storing publication names or short lists. VARCHAR is ideal for variable-length strings up to the specified limit.
- comments: A TEXT field designed for longer content blocks. TEXT columns can store up to 65,535 bytes (approximately 64KB)—sufficient for substantial user comments. For applications requiring larger storage capacity, consider MEDIUMTEXT (16MB) or LONGTEXT (4GB).
- subscribe: A TINYINT(1) field perfect for boolean values. TINYINT uses minimal storage while providing reliable true (1) or false (0) functionality.
- NULL values: All fields allow NULL to distinguish between "no response" and "empty response"—an important data integrity concept. For instance, NULL in publications means the user skipped the question entirely, while an empty string means they answered but selected no publications.
Click Save to add the new columns to your table structure.
New Database Fields Added
NULL represents unanswered questions, while empty strings or zero values indicate answered questions with no selection. This distinction is crucial for proper data interpretation and application logic.
MySQL Text Field Types
| Feature | Field Type | Storage Capacity |
|---|---|---|
| TEXT | TEXT | 65,535 bytes (~64KB) |
| MEDIUMTEXT | MEDIUMTEXT | 16,777,215 bytes (~16MB) |
| LONGTEXT | LONGTEXT | 4,294,967,295 bytes (~4GB) |
Setting up the PHP
With our database structure updated, let's implement the PHP code to handle form submission and data insertion. This process demonstrates real-world form processing techniques used in professional web applications.
Return to your code editor to begin the implementation.
Open form.php from the form-insert folder.
Preview the form in your browser:
- Mac: localhost:8888/phpclass/form-insert/form.php
- Windows: localhost/phpclass/form-insert/form.php
Complete the form with sample data and click Sign me Up!
This form includes pre-built validation and input sanitization—critical security measures that clean user input before database insertion. Our task is to add the database insertion functionality to this existing, secure foundation.
Open form-action.php from the form-insert folder.
This file contains the validation logic that processes and sanitizes form submissions. We'll integrate our database insertion code here.
Navigate to approximately line 66 and locate the comment:
//insert into databaseBelow this comment, add the include statement:
//insert into database require_once('form-insertUser.php');This modular approach separates concerns—keeping validation logic separate from database operations for better code organization and maintainability.
Save and close form-action.php.
Create a new file and save it as form-insertUser.php in the form-insert folder.
Begin the file with the database connection requirement:
<?php require_once('../inc/dbConnect.php'); ?>Note the relative path (
../) since we're in a subdirectory relative to the database connection file.Define the INSERT statement for all form fields:
require_once('../inc/dbConnect.php'); $SQL = "INSERT INTO users (firstName, lastName, email, publications, comments, subscribe) VALUES (?, ?, ?, ?, ?, ?) ";This expanded INSERT statement handles all six fields from our form. The question mark placeholders maintain the prepared statement security model while accommodating the additional data fields.
Initialize the statement object:
require_once('../inc/dbConnect.php'); $SQL = "INSERT INTO users (firstName, lastName, email, publications, comments, subscribe) VALUES (?, ?, ?, ?, ?, ?) "; $stmt = $conn->stmt_init(); $stmt->prepare($SQL);Bind the parameters with appropriate data type specifications:
require_once('../inc/dbConnect.php'); $SQL = "INSERT INTO users (firstName, lastName, email, publications, comments, subscribe) VALUES (?, ?, ?, ?, ?, ?) "; $stmt = $conn->stmt_init(); $stmt->prepare($SQL); $stmt->bind_param('sssssi', $firstName, $lastName, $email, $publications, $comments, $subscribe);The type string
'sssssi'specifies five strings followed by one integer. The variables referenced here are created by the validation script in form-action.php, which sanitizes the original$_POSTdata and assigns it to clean variable names.Execute the statement with comprehensive error handling:
$stmt->prepare($SQL); $stmt->bind_param('sssssi', $firstName, $lastName, $email, $publications, $comments, $subscribe); $stmt->execute(); if ($stmt->error) { echo $stmt->error; exit(); }This error handling approach immediately displays any SQL errors and halts script execution—essential for identifying and resolving database issues during development.
Save the file and test the complete workflow:
- Mac: localhost:8888/phpclass/form-insert/form.php
- Windows: localhost/phpclass/form-insert/form.php
Complete all form fields and submit. You'll see the thank you page, but notice a PHP notice at the top:
Notice: Array to string conversion in /Applications/MAMP/htdocs/phpclass/form-insert/form-insertUser.php on line 12This notice indicates we're attempting to insert an array where a string is expected. The checkbox field "What do you read?" returns an array of selected values, but our database expects a string. The page continues executing because this is a notice (warning) rather than a fatal error.
Let's examine what's being stored in the database. Return to phpMyAdmin:
Mac:- Switch to MAMP PRO
- Click WebStart
- Navigate to Tools → phpMyAdmin
- Go to http://localhost
- Click phpMyAdmin in the Tools section
Click phpclass_yourname to access your database.
Click the Browse icon
for the users table.Examine the most recent entry's publications column—it displays "Array" instead of the actual publication names. We need to convert the array into a readable, comma-separated string.
Return to your code editor and open form-insertUser.php.
Add array processing logic at the beginning of the file. The form-action.php script provides an
$expectedarray containing all form field names, which we'll use to process potential arrays:<?php foreach ($expected as $value) { } require_once('../inc/dbConnect.php');This loop iterates through each expected form field name.
To understand the loop's output, temporarily add debugging code:
foreach ($expected as $value) { echo $value; echo '<br>'; }Test this debug output:
- Mac: localhost:8888/phpclass/form-insert/form.php
- Windows: localhost/phpclass/form-insert/form.php
Submit the form to see the field names displayed:
firstName lastName email publications comments subscribeThis confirms our loop is accessing each form field name correctly.
Replace the debug code with array detection logic:
<?php foreach ($expected as $value) { if ( is_array(${$value}) ) { } } require_once('../inc/dbConnect.php');The
${$value}syntax uses variable variables—it converts the string value (e.g., "publications") into a variable name (e.g.,$publications) for evaluation.Implement array-to-string conversion using PHP's
implode()function:foreach ($expected as $value) { if ( is_array(${$value}) ) { ${$value} = implode(", ", ${$value}); } }The
implode()function converts arrays into strings using a specified delimiter. Here, we're creating comma-separated lists that are database-friendly and human-readable.Test the complete implementation:
- Mac: localhost:8888/phpclass/form-insert/form.php
- Windows: localhost/phpclass/form-insert/form.php
Complete the form, selecting multiple options under "What do you read?" The submission should now display only the thank you page without errors or notices.
Verify the results in phpMyAdmin:
Mac:- Open MAMP PRO
- Click WebStart
- Navigate to Tools → phpMyAdmin
- Go to http://localhost
- Access phpMyAdmin from Tools
Navigate to phpclass_yourname and browse the users table.
The publications column should now display properly formatted, comma-separated values such as:
Daily Racing Form, ElleThis demonstrates successful array processing and database insertion.
Return to your code editor and close all files—you've successfully implemented secure form processing with database insertion.
You've now mastered the essential skills of database insertion using prepared statements, from simple static data to complex form processing with array handling. These techniques form the foundation of secure, professional web application development and represent industry-standard practices for database interaction in modern PHP applications.
Form Integration Implementation
Link Database Connection
Include the dbConnect.php file with proper relative path from form-insert folder
Create Extended INSERT Statement
Add new columns (publications, comments, subscribe) to the SQL INSERT with six parameter placeholders
Configure Parameter Binding
Use 'sssssi' format specifying five strings and one integer for the bind_param function
Implement Error Handling
Execute statement with proper error checking and script termination on failure
Checkbox arrays cannot be directly inserted as strings into database fields. The implode function converts arrays to comma-delimited strings for proper storage.
Array Processing Solution
Loop Through Expected Values
Iterate through the $expected array containing all form field names
Check for Array Type
Use is_array() function with variable variables (${$value}) to identify array fields
Convert Arrays to Lists
Apply implode() function with comma-space delimiter to create readable string lists
Verify Database Storage
Check phpMyAdmin to confirm proper comma-delimited list storage instead of 'Array' text