Integrating Databases with Websites
1. Set up the Database
First, create a MySQL database and a table
SQL Script to create the database and table
CREATE DATABASE mywebsite_db;
USE mywebsite_db;
CREATE TABLE items (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
2. PHP and HTML Code to Integrate the Database
A. Database Configuration ([Link])
<?php
$servername = "localhost"; // Your database host
$username = "root"; // Your database username
$password = ""; // Your database password
$dbname = "mywebsite_db"; // Your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
?>
B. HTML Form to Submit Data ([Link])
<!DOCTYPE html>
<html lang="en">
<head><title>Add Item</title></head>
<body>
<h1>Add an Item to the Database</h1>
<form action="[Link]" method="POST">
<input type="text" name="name" placeholder="Enter item name" required>
<button type="submit">Add Item</button>
</form> <h2>Items in Database</h2><ul>
<?php
include '[Link]';
$sql = "SELECT * FROM items";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<li>" . $row['name'] . "</li>"; }
} else {
echo "<li>No items found</li>"; }
// Close the database connection
$conn->close();
?>
</ul>
</body>
</html>
C. PHP Script to Handle Form Submission ([Link])
<?php
// Include the database connection
include '[Link]';
// Check if form data is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
// Insert data into the database
$sql = "INSERT INTO items (name) VALUES ('$name')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
// Redirect back to the form page
header("Location: [Link]");
exit();
// Close the connection
$conn->close();
?>