Making a Reusable Connection Script
Build Efficient Database Connections with Reusable PHP Scripts
Core Concepts You'll Master
Error Checking
Implement robust error handling for database connections. Learn to catch connection failures and display meaningful error messages.
Making an Include
Create reusable connection scripts that can be included across multiple pages. Eliminate code duplication and improve maintainability.
Sorting Results
Master SQL ORDER BY clauses to sort query results. Learn ascending, descending, and multi-column sorting techniques.
Benefits of Reusable Connection Scripts
Creating Your Reusable Connection Script
Extract Connection Code
Cut the mysqli connection line from your existing MySQL.php file to prepare it for reuse.
Create Include File
Create a new dbConnect.php file in the inc folder and wrap the connection code in PHP tags.
Add Error Checking
Implement connect_errno checking to catch connection failures and display appropriate error messages.
Include in Main File
Use require_once to include the connection script at the top of your MySQL.php file.
Always use exit() after displaying connection errors. Without a database connection, the rest of your page will likely fail to work properly.
require_once('inc/dbConnect.php');
SQL Sorting Options
| Feature | Ascending (Default) | Descending |
|---|---|---|
| Syntax | ORDER BY lastName | ORDER BY lastName DESC |
| Result Order | A to Z | Z to A |
| Use Case | Alphabetical lists | Reverse chronological |
Advanced Sorting Techniques
Single Column Sort
ORDER BY lastName sorts all records by a single field. This is the most basic and commonly used sorting method.
Reverse Order Sort
ORDER BY lastName DESC reverses the sort order. Essential for displaying newest items first or reverse alphabetical order.
Multi-Column Sort
ORDER BY lastName, firstName creates hierarchical sorting. Records are sorted by last name, then by first name for matching last names.
When using multiple ORDER BY columns, list them in order of priority. The first column has the highest sorting priority, with subsequent columns used for tie-breaking.
Testing Your Implementation
Ensure cross-platform compatibility for your development environment
Confirm that connection errors are properly caught and displayed
Validate ascending, descending, and multi-column sorting functionality
Ensure the dbConnect.php file is properly located in the inc folder
Key Takeaways