How can the PHP script be improved in terms of database normalization and code structure?
The PHP script can be improved by normalizing the database structure to reduce redundancy and improve data integrity. Additionally, the code structure can be improved by separating concerns and using functions for repetitive tasks.
// Normalize the database structure by creating separate tables for related data
// Refactor the code to separate concerns and use functions for repetitive tasks
// Function to connect to the database
function connectDB() {
$host = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'dbname';
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
// Function to retrieve user data from the database
function getUserData($userId) {
$conn = connectDB();
$sql = "SELECT * FROM users WHERE user_id = $userId";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
return $row;
} else {
return false;
}
$conn->close();
}
// Function to retrieve user posts from the database
function getUserPosts($userId) {
$conn = connectDB();
$sql = "SELECT * FROM posts WHERE user_id = $userId";
$result = $conn->query($sql);
$posts = array();
while ($row = $result->fetch_assoc()) {
$posts[] = $row;
}
return $posts;
$conn->close();
}
// Example usage
$userData = getUserData(1);
$userPosts = getUserPosts(1);