PHP can be used to interact with databases, allowing you to store and retrieve data from a database in your web application. To use a database with PHP, you will need to have a database management system (DBMS) installed on your server, such as MySQL, MariaDB, or PostgreSQL.
To connect to a database from a PHP script, you can use the mysqli
extension or the PDO
extension. Here is an example of how to connect to a MySQL database using the mysqli
extension:
$host = 'localhost';
$username = 'db_user';
$password = 'password';
$database = 'my_database';
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
In this example, we create a new mysqli
connection object and pass in the hostname, username, password, and database name as arguments. We then check if the connection was successful by checking the connect_error
property. If the connection was not successful, we output an error message and exit the script. If the connection was successful, we output a success message.
Once you have established a database connection, you can execute SQL queries and retrieve the results using the mysqli
extension. Here is an example of how to execute a SELECT query and retrieve the results:
$sql = "SELECT * FROM users WHERE age > 25";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. " - Age: " . $row["age"] . "<br>";
}
} else {
echo "No results";
}
In this example, we execute a SELECT query that retrieves all rows from the users
table where the age
column is greater than 25. We then use the num_rows
property to check if there are any results, and if there are, we use the fetch_assoc
method to retrieve the rows one at a time and output their values.
The mysqli
extension and the PDO
extension provide many other functions and methods for working with databases in PHP. You can find more information about these extensions and how to use them in the PHP documentation.