How can beginners improve their code by transitioning from mysql_*() functions to more secure options like MySQLi or PDO in PHP?

Using mysql_*() functions in PHP is deprecated and poses security risks due to potential SQL injection vulnerabilities. Beginners can improve their code by transitioning to more secure options like MySQLi or PDO, which offer prepared statements to prevent SQL injection attacks.

// Using MySQLi to connect to a database and execute a query
$mysqli = new mysqli('localhost', 'username', 'password', 'database');

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

// Using prepared statements to prevent SQL injection
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Execute the query
$stmt->execute();

// Bind the result
$stmt->bind_result($result);

// Fetch the result
$stmt->fetch();

// Close the statement
$stmt->close();

// Close the connection
$mysqli->close();