How can one ensure that the MySQL connection is properly established when using mysql_fetch_assoc() in PHP?

When using mysql_fetch_assoc() in PHP, one must ensure that the MySQL connection is properly established before attempting to fetch data from the database. This can be done by first establishing the connection using mysqli_connect() or mysqli_init() functions. It is important to check if the connection is successful before proceeding with fetching data using mysql_fetch_assoc().

// Establish MySQL connection
$mysqli = mysqli_connect("localhost", "username", "password", "database");

// Check if connection is successful
if (!$mysqli) {
    die("Connection failed: " . mysqli_connect_error());
}

// Fetch data using mysql_fetch_assoc()
$result = mysqli_query($mysqli, "SELECT * FROM table");
while ($row = mysqli_fetch_assoc($result)) {
    // Process data here
}

// Close connection
mysqli_close($mysqli);