What are the potential security risks associated with using MySQL functions like mysql_query in PHP?

Using functions like mysql_query in PHP can lead to SQL injection attacks if user input is not properly sanitized. To prevent this, it is important to use parameterized queries or prepared statements to securely interact with the database. This helps to prevent malicious users from injecting SQL code into queries.

// Using prepared statements to prevent SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Prepare a SQL statement
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");

// Bind parameters
$stmt->bind_param("s", $username);

// Set parameters and execute
$username = "example_user";
$stmt->execute();

// Get result
$result = $stmt->get_result();

// Fetch data
while ($row = $result->fetch_assoc()) {
    // Do something with the data
}

// Close statement and connection
$stmt->close();
$mysqli->close();