What are some best practices for creating a database for a website using PHP?

When creating a database for a website using PHP, it is important to follow best practices to ensure security and efficiency. Some key practices include using parameterized queries to prevent SQL injection attacks, validating user input to avoid potential errors, and properly sanitizing data before inserting it into the database.

// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Prepare a parameterized query to prevent SQL injection
$stmt = $conn->prepare("INSERT INTO users (username, email) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $email);

// Validate user input
$username = $_POST['username'];
$email = $_POST['email'];

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
} else {
    // Sanitize data before inserting into the database
    $username = mysqli_real_escape_string($conn, $username);
    $email = mysqli_real_escape_string($conn, $email);
    
    // Execute the query
    $stmt->execute();
    echo "New record created successfully";
}

// Close the connection
$stmt->close();
$conn->close();