Integrating PHP with MySQL allows developers to create dynamic, data-driven web applications. This article will guide you through the process of combining PHP’s processing capabilities with MySQL’s data storage and retrieval functions to build a simple yet powerful user management system.
Step 1: Database Connection
First, establish a connection to your MySQL database:
<?php
$host = 'localhost';
$user = 'your_username';
$pass = 'your_password';
$dbname = 'user_management';
$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
PHPStep 2: Creating a User Registration Form
Create an HTML form for user registration:
<!DOCTYPE html>
<html>
<body>
<h2>User Registration</h2>
<form action="register.php" method="post">
Username: <input type="text" name="username"><br>
Email: <input type="email" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Register">
</form>
</body>
</html>
HTMLStep 3: Processing Registration (register.php)
Handle the form submission and insert data into the database:
<?php
include 'db_connection.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $conn->real_escape_string($_POST['username']);
$email = $conn->real_escape_string($_POST['email']);
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
if ($conn->query($sql) === TRUE) {
echo "New user registered successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
PHPStep 4: Retrieving and Displaying Users
Create a page to display all registered users:
<?php
include 'db_connection.php';
$sql = "SELECT id, username, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Username</th><th>Email</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["username"]."</td><td>".$row["email"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
PHPStep 5: Implementing User Authentication
Create a login system:
<?php
session_start();
include 'db_connection.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $conn->real_escape_string($_POST['username']);
$password = $_POST['password'];
$sql = "SELECT id, username, password FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if (password_verify($password, $row['password'])) {
$_SESSION['user_id'] = $row['id'];
$_SESSION['username'] = $row['username'];
echo "Login successful!";
} else {
echo "Invalid password";
}
} else {
echo "User not found";
}
}
$conn->close();
?>
PHPBest Practices:
- Use prepared statements to prevent SQL injection attacks.
- Implement proper error handling and user feedback.
- Sanitize and validate all user inputs.
- Use secure password hashing techniques.
- Implement CSRF protection for forms.
Conclusion:
Integrating PHP with MySQL allows for the creation of dynamic, data-driven web applications. This example demonstrates basic user management functionality, including registration, data retrieval, and authentication. As you continue to develop your skills, explore more advanced topics such as prepared statements, transactions, and optimizing database queries for improved performance and security.