What are the common mistakes to watch out for when using MySQL functions in PHP scripts, and how can they be rectified?

One common mistake when using MySQL functions in PHP scripts is not properly sanitizing user input, which can lead to SQL injection vulnerabilities. To rectify this, always use prepared statements or parameterized queries to prevent malicious SQL queries from being executed.

// Incorrect way without sanitizing user input
$user_input = $_POST['username'];
$query = "SELECT * FROM users WHERE username = '$user_input'";
$result = mysqli_query($connection, $query);

// Correct way using prepared statements
$user_input = $_POST['username'];
$query = "SELECT * FROM users WHERE username = ?";
$stmt = mysqli_prepare($connection, $query);
mysqli_stmt_bind_param($stmt, "s", $user_input);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);