In what ways can JavaScript be used to interact with a database like MySQL for website statistics tracking?

JavaScript alone cannot directly interact with a MySQL database due to security restrictions. To track website statistics using MySQL, you can use JavaScript to send data to a server-side script (like PHP) which then interacts with the database. This can be achieved by making AJAX requests from JavaScript to the PHP script, which can then insert or retrieve data from the MySQL database.

// PHP script to handle AJAX requests and interact with MySQL database

// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

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

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

// Handle AJAX request to insert data into database
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $data = json_decode(file_get_contents("php://input"));

    $sql = "INSERT INTO website_statistics (page, visitors) VALUES ('$data->page', $data->visitors)";

    if ($conn->query($sql) === TRUE) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// Handle AJAX request to retrieve data from database
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    $sql = "SELECT * FROM website_statistics";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "Page: " . $row["page"]. " - Visitors: " . $row["visitors"]. "<br>";
        }
    } else {
        echo "0 results";
    }
}

$conn->close();