Database connectivity is a crucial aspect of developing web applications. It enables web applications to store, retrieve, and manage data from databases, allowing for the creation of dynamic web pages. In PHP programming language, we can establish a connection with databases and utilize SQL queries to modify data effectively. This document provides an overview of database connectivity in PHP and its fundamental concepts.
Connecting to a Database
Connecting to a database in PHP is a simple process that starts with defining the server name, username, password, and database name. We can then create a new mysqli
object and pass these parameters into it. Afterward, we check if the connection is successful and print a message accordingly.
Here is an example code snippet that demonstrates how to establish a database connection:
<?php
$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);
}
echo "Connected successfully";
?>
SQL Queries
Once we have established a database connection, we can use SQL queries to manipulate data. SQL stands for Structured Query Language, and it is a standard language used to manage relational databases.
In PHP, we can use the mysqli
extension to execute SQL queries. Here is an example code snippet that demonstrates how to use SQL queries in PHP:
<?php
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "
";
}
} else {
echo "0 results";
}
$conn->close();
?>
In the above code, we use the SQL SELECT
statement to retrieve all data from the users
table. We then use a while
loop to iterate through each row of the result set and print the id
and name
columns.
Furthermore, we can use other SQL statements like INSERT
, UPDATE
, DELETE
, and JOIN
to manipulate data in the database. For example, INSERT
can add new data to the database, while UPDATE
can modify existing data.
Conclusion
In conclusion, this document provided an overview of database connectivity in PHP. We learned how to connect to a database using the mysqli
extension, how to use SQL queries to manipulate data, and the importance of database connectivity in web application development. With this knowledge, you can start building dynamic web applications that interact with databases. As you continue to develop your skills, you will be able to create more complex applications and use more advanced SQL queries.