What is the difference between JavaScript and PHP in the context of creating a quiz game?
JavaScript is a client-side scripting language that runs in the browser, while PHP is a server-side scripting language that runs on the web server. When creating a quiz game, JavaScript would be used to handle the interactive elements and user input on the client side, such as displaying questions and checking answers. PHP would be used to handle the backend logic, such as retrieving questions from a database, processing user responses, and calculating scores.
<?php
// PHP code to retrieve quiz questions from a database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "quiz_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL query to retrieve quiz questions
$sql = "SELECT question, answer FROM quiz_questions";
$result = $conn->query($sql);
// Display quiz questions
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Question: " . $row["question"] . "<br>";
echo "<input type='text' name='answer'><br>";
}
} else {
echo "No questions found";
}
$conn->close();
?>