What are common tasks that PHP developers need to perform when working with MySQL databases?
Common tasks that PHP developers need to perform when working with MySQL databases include connecting to the database, querying data, inserting, updating, and deleting records, handling errors, and closing the database connection.
// Connecting to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Querying data from the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Closing the database connection
$conn->close();