How does PHP interact with MySQL databases?
PHP interacts with MySQL databases using the MySQLi (MySQL Improved) extension or PDO (PHP Data Objects) extension. These extensions provide functions and classes to connect to MySQL databases, execute queries, fetch results, and manage transactions. By using these extensions, PHP can communicate with MySQL databases to retrieve, insert, update, and delete data.
// Connect to MySQL database using MySQLi extension
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform SQL query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Fetch results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
// Close connection
$conn->close();
Keywords
Related Questions
- How can PHP developers handle cases where certain data fields may be empty or null in database queries, ensuring accurate results?
- What are the best practices for efficiently retrieving data from multiple tables in PHP?
- How can PHP developers ensure that their code is structured efficiently when incorporating images alongside text output based on specific conditions, such as the current day of the week?