Skip to content
PHP Logo

How can using a database for language translation in PHP be a better approach compared to using constants or arrays?

Using a database for language translation in PHP can be a better approach compared to using constants or arrays because it allows for easier management and updating of translations. Storing translations in a database also provides more flexibility in terms of adding new languages or modifying existing translations without needing to modify the code. Additionally, using a database allows for dynamic loading of translations based on user preferences or other criteria.

php
// Example of using a database for language translation in PHP

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "translations";
$conn = new mysqli($servername, $username, $password, $dbname);

// Query the database for the translation
$lang = "en"; // Language code
$key = "hello"; // Translation key
$sql = "SELECT translation FROM translations WHERE lang = '$lang' AND key = '$key'";
$result = $conn->query($sql);

// Fetch and display the translation
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo $row["translation"];
} else {
    echo "Translation not found";
}

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