Powering Web Apps with PHP and MySQL
PHP and MySQL are a powerful combination for building dynamic web applications. This guide shows how to connect PHP to MySQL and perform basic CRUD operations.
1. Connecting to MySQL
Use PDO for secure database connections:
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
2. Creating Records
Insert data using prepared statements:
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute(["John Doe", "john@example.com"]);
3. Reading Data
Fetch records from the database:
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
4. Updating and Deleting
Update or delete records with similar prepared statements for security.
Conclusion
PHP and MySQL together enable dynamic, data-driven applications. Use PDO and prepared statements to ensure security and scalability.
