PHP can interact with MySQL databases to store and retrieve data. The mysqli
extension is used to connect to a MySQL database.
To connect to a MySQL database, use the mysqli_connect()
function:
<?php
$conn = mysqli_connect("localhost", "root", "", "my_database");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
To execute a query, use the mysqli_query()
function:
<?php
$result = mysqli_query($conn, "SELECT * FROM users");
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . "
";
}
?>
To close the database connection, use mysqli_close()
:
<?php
mysqli_close($conn); // Close connection
?>
Write a PHP script that connects to a MySQL database and fetches data from a "users" table.
Answers: Use mysqli_connect()
to connect. Use mysqli_fetch_assoc()
to fetch data.