How can you properly handle database connections and selections in PHP when working with MySQL?
When working with MySQL databases in PHP, it is important to properly handle database connections and selections to ensure efficient and secure operations. To do this, you should establish a connection to the database using mysqli or PDO, execute queries to select data, and handle any errors that may occur during the process.
// Establish a connection to the MySQL database using mysqli
$host = 'localhost';
$user = 'username';
$password = 'password';
$database = 'dbname';
$mysqli = new mysqli($host, $user, $password, $database);
// Check for connection errors
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Select data from a table
$query = "SELECT * FROM table_name";
$result = $mysqli->query($query);
// Handle errors during selection
if (!$result) {
die("Error selecting data: " . $mysqli->error);
}
// Process the selected data
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the database connection
$mysqli->close();