In this tutorial, you’ll learn how to connect PHP to a MySQL database and insert data into it using XAMPP. This guide is ideal for beginners looking to build dynamic, data-driven websites. We’ll cover everything from setting up your environment to writing PHP code to perform database operations. Let’s dive in!
frontend.php code
<h1>Customer details form</h1>
<form action="backend.php" method="post">
Enter Customer Name :
<input type="text" name="c_name"><br><br>
Enter Customer Mobile :
<input type="number" name="c_mobile"><br><br>
Enter Customer email :
<input type="email" name="c_email"><br><br>
Enter Customer Password :
<input type="password" name="c_password"><br><br>
<button>Save Customer</button>
</form>
backend.php code
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
$conn = mysqli_connect("localhost", "root", "", "a2z41");
$c_name = $_POST['c_name'];
$c_mobile = $_POST['c_mobile'];
$c_email = $_POST['c_email'];
$c_password = $_POST['c_password'];
$sql = "insert into customer (customer_name,customer_mobile,customer_email,customer_password) values ('$c_name','$c_mobile','$c_email','$c_password')";
echo $sql;
echo "<br><br>";
$result = mysqli_query($conn, $sql);
if ($result) {
echo "data inserted";
} else {
echo "data not inserted";
}
Table of Contents
1. Introduction to PHP and MySQL <a name=”introduction”></a>
PHP is a popular server-side scripting language that is widely used for web development, while MySQL is a powerful relational database management system. When combined, PHP and MySQL enable developers to create dynamic websites and applications with backend databases.
2. Setting Up XAMPP <a name=”setting-up-xampp”></a>
XAMPP is a free, open-source software that includes Apache (for running a local server), MySQL (for managing databases), and PHP. Here’s how to install and configure XAMPP:
- Download XAMPP: Go to the XAMPP website and download the version that matches your operating system.
- Install XAMPP: Run the downloaded file and follow the installation instructions.
- Start Apache and MySQL: Open the XAMPP Control Panel and start the Apache and MySQL services. These services will allow you to run PHP scripts and access MySQL databases locally.
3. Creating a MySQL Database <a name=”creating-a-database”></a>
Once XAMPP is set up, it’s time to create a MySQL database where we’ll store our data.
- Open phpMyAdmin: Go to your browser and type
http://localhost/phpmyadmin/
to open phpMyAdmin, a web interface for managing MySQL databases. - Create a Database: Click on “Databases” at the top. In the “Create database” field, enter a name for your database (e.g.,
test_database
) and click “Create.” - Create a Table: Click on your new database, then click on the “SQL” tab or “Create table.” For this tutorial, let’s create a table called
users
with fields forid
,name
, andemail
.
4. Writing PHP Code to Connect to MySQL <a name=”writing-php-code”></a>
Now that we have a database, let’s write PHP code to connect to it.
- Open Your Code Editor: Open a code editor like VS Code or Sublime Text.
- Create a New PHP File: In your
htdocs
folder (located in the XAMPP installation directory), create a file calleddatabase_connection.php
. - Write Connection Code: Use the following code to connect to MySQL.phpCopy code
<?php $servername = "localhost"; $username = "root"; // Default username for XAMPP $password = ""; // Leave blank for XAMPP $dbname = "test_database"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>
This code establishes a connection to the MySQL database. If the connection is successful, it will display “Connected successfully” on the page.
5. Inserting Data into the Database <a name=”inserting-data”></a>
Let’s write a PHP script to insert data into the users
table.
- Create a New PHP File: In the same folder, create a file called
insert_data.php
. - Write Insertion Code: Use the following code to insert data.phpCopy code
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "test_database"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // SQL query to insert data $name = "John Doe"; $email = "john.doe@example.com"; $sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
This code inserts a new record into theusers
table with the name “John Doe” and the email “john.doe@example.com“.
6. Testing the Database Connection and Insertion <a name=”testing”></a>
To test if everything works as expected:
- Start Apache and MySQL in XAMPP: Make sure both services are running.
- Run the PHP Scripts: Open your browser and go to
http://localhost/database_connection.php
. If the connection is successful, you’ll see a confirmation message. - Test Data Insertion: Go to
http://localhost/insert_data.php
. If the data insertion is successful, you’ll see a confirmation message. - Check the Database: Go to phpMyAdmin, open the
test_database
, and view theusers
table. You should see the new record with John Doe’s information.
7. Best Practices for Database Security <a name=”security-tips”></a>
When working with databases, it’s important to follow best practices to ensure security and efficiency:
- Use Prepared Statements: Prevent SQL injection by using prepared statements with parameterized queries instead of directly inserting variables into SQL queries.
- Validate and Sanitize User Input: Always validate and sanitize input data to avoid security vulnerabilities.
- Encrypt Sensitive Data: For sensitive information like passwords, consider using encryption or hashing techniques.
8. Conclusion <a name=”conclusion”></a>
Congratulations! You’ve successfully learned how to connect PHP to a MySQL database using XAMPP and insert data into it. This skill is foundational for building database-driven applications. With this knowledge, you’re on your way to developing dynamic websites with robust backend systems.
Stay tuned for more tutorials, and don’t forget to practice to solidify your skills!