What are the potential pitfalls of trying to directly access MySQL from JavaScript?

Directly accessing MySQL from JavaScript can expose your database credentials and sensitive information to users, leading to security risks such as SQL injection attacks. To mitigate this risk, it is recommended to use a server-side language like PHP to handle database operations securely. By creating an API in PHP that interacts with the database and then making AJAX requests from JavaScript to this API, you can ensure that sensitive information is not exposed to the client side.

<?php

// 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);
}

// Perform database operations
// For example, fetching data from a table
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();

?>