How does PHP access the correct table in a database and what are the potential pitfalls when defining table names in PHP code?

When accessing a table in a database using PHP, it is important to ensure that the table name is correctly specified in the SQL query. One common pitfall is hardcoding the table name directly in the PHP code, which can lead to errors if the table name is changed in the database. To avoid this issue, it is recommended to define the table name as a constant or variable in the PHP code, making it easier to update if needed.

// Define the table name as a constant
define('TABLE_NAME', 'users');

// Use the constant in the SQL query
$sql = "SELECT * FROM " . TABLE_NAME;
$result = mysqli_query($conn, $sql);

// Fetch data from the result set
while ($row = mysqli_fetch_assoc($result)) {
    // Process the data
}

// Remember to close the database connection
mysqli_close($conn);