How can the use of mysql_query() in PHP lead to errors and how can they be handled effectively?

Using mysql_query() in PHP can lead to errors such as SQL injection vulnerabilities and deprecated function warnings. To handle these effectively, it is recommended to use prepared statements with mysqli or PDO to prevent SQL injection attacks and switch to mysqli_query() or PDO functions for improved security and compatibility.

// Connect to database using mysqli
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

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

// Prepare and execute a query using prepared statements
$stmt = $mysqli->prepare("SELECT * FROM table WHERE id = ?");
$stmt->bind_param("i", $id);
$id = 1;
$stmt->execute();
$result = $stmt->get_result();

// Fetch data from result set
while ($row = $result->fetch_assoc()) {
    // Process data
}

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