Step 1: Install PHP and MySQL
Ensure that PHP and MySQL are installed on your system. If you're using XAMPP, MAMP, or WAMP, they come bundled together.
Step 2: Create a MySQL Database
-
Open MySQL (via phpMyAdmin, command line, or MySQL Workbench).
-
Create a database using the following SQL command:
-
Create a table inside the database:
Step 3: Connect to MySQL Database Using PHP
PHP provides two main ways to connect to MySQL:
-
MySQLi (Improved)
-
PDO (PHP Data Objects)
Method 1: Using MySQLi (Procedural)
Method 2: Using MySQLi (Object-Oriented)
Method 3: Using PDO (Recommended for Security)
Step 4: Insert Data into MySQL Table
After connecting, you can insert data using SQL queries.
Using MySQLi (Procedural)
Using PDO
Step 5: Retrieve Data from MySQL Table
Using MySQLi (Procedural)
Using PDO
Step 6: Close the Database Connection
For MySQLi, use:
For PDO, the connection closes automatically when the script ends, or you can explicitly set it to null:
Conclusion
-
Use MySQLi if you are working with a simple project.
-
Use PDO if you need a secure and flexible approach (especially for prepared statements).
-
Always validate user input to prevent SQL injection.
-
Consider using environment variables for database credentials instead of hard coding them in the script.