PHP
Learn how to connect to MySQL databases in Sealos DevBox using PHP
This guide will walk you through the process of connecting to a MySQL database using PHP within your Sealos DevBox project.
Prerequisites
- A Sealos DevBox project with PHP environment
- A MySQL database created using the Database app in Sealos
Install Required Extensions
In your Cursor terminal, ensure that the MySQL extension for PHP is installed:
Connection Setup
Create a Configuration File
First, let's create a configuration file to store our database connection parameters. Create a file named config.php in your project directory with the following content:
Replace the placeholders with your actual MySQL credentials from the Database app in Sealos.
Create a Database Connection Function
Next, let's create a PHP file that will handle the database connection. Create a file named db_connect.php with the following content:
This function reads the configuration from config.php and establishes a connection to the MySQL database using PDO (PHP Data Objects).
Create a Test Script
Now, let's create a test script to verify our connection and perform some basic database operations. Create a file named test_db.php with the following content:
This script demonstrates creating a table, inserting a record, and querying the table.
Usage
To run the test script, use the following command in your Cursor terminal:
This will execute the script, demonstrating the connection to the database, table creation, data insertion, and querying.
Best Practices
- Use environment variables or a separate configuration file for database credentials.
- Always use prepared statements to prevent SQL injection.
- Handle potential errors using try-catch blocks.
- Close the database connection after operations are complete.
- Use connection pooling for better performance in production environments.
Troubleshooting
If you encounter connection issues:
- Verify your database credentials in the
config.phpfile. - Ensure your MySQL database is running and accessible.
- Check for any network restrictions in your DevBox environment.
- Confirm that the
php-mysqlextension is correctly installed.
For more detailed information on using MySQL with PHP, refer to the official PHP MySQL documentation.
Explore with AI
Get AI insights on this article
Share this article
Last updated on