What are common errors when accessing MySQL databases in PHP and how can they be resolved?

Common errors when accessing MySQL databases in PHP include using incorrect database credentials, not selecting a database before querying, and not properly handling errors. These issues can be resolved by double-checking the database connection details, ensuring the database is selected with the correct name, and implementing error handling to catch any potential issues.

// Correcting common errors when accessing MySQL databases in PHP

// Correct database credentials
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'my_database';

// Establish database connection
$connection = mysqli_connect($host, $username, $password, $database);

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

// Select the database
mysqli_select_db($connection, $database);

// Perform database query
$query = "SELECT * FROM my_table";
$result = mysqli_query($connection, $query);

// Check for errors
if (!$result) {
    die("Query failed: " . mysqli_error($connection));
}

// Process the query result
while ($row = mysqli_fetch_assoc($result)) {
    // Process each row
}

// Close the connection
mysqli_close($connection);