What are the best practices for creating and maintaining a database in PHP for storing player stats like goals scored?
To create and maintain a database in PHP for storing player stats like goals scored, it is important to properly design the database schema, establish a connection to the database, and use secure SQL queries to insert and retrieve data. Additionally, regular maintenance tasks such as backing up the database and optimizing queries should be performed to ensure data integrity and performance.
// Establish a connection to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "player_stats";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create a table to store player stats
$sql = "CREATE TABLE player_stats (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
player_name VARCHAR(30) NOT NULL,
goals_scored INT(3) NOT NULL
)";
if ($conn->query($sql) === TRUE) {
echo "Table player_stats created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
// Insert data into the player_stats table
$sql = "INSERT INTO player_stats (player_name, goals_scored) VALUES ('Player A', 10)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Retrieve player stats from the database
$sql = "SELECT * FROM player_stats";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Player: " . $row["player_name"]. " - Goals Scored: " . $row["goals_scored"]. "<br>";
}
} else {
echo "0 results";
}
// Close the database connection
$conn->close();
Related questions
-
array_merge array_combine array_merge_recursive
-
security input validation code injection
-
PHP version local development environment server