Database Programming in PHP
The development of PHP has focused heavily on database access, and as a result, it provides driver support for 15 distinct databases systems.
You may connect to and work with different databases using PHP. Among them, MySQL is the most widely used database platform for PHP.
Establishing a connection to the database :
We require four parameters to connect to the database.
- Hostname (By default "localhost")
- Username (By default "root")
- Password (By default "No Password")
- Database Name
☞ mysqli_connect()
One built-in function in PHP allows us to establish a connection to a database (MySQL) .i.e. mysqli_connect()
format:mysqli_connect("hostname","username","password","databasename")The above function creates a successful connection with Database if you provide valid information. When the connection is not well, we can kill that connection by using die()
format:
die("Can't create connection");
☞ mysqli_close()
mysqli_close() function is used to close or terminate the connection with MySQL database.
format:
mysqli_close(Connection);
☞ An example program to create a connection with the database.
Example: "DbConnection.php"
Output :
Executing simple queries :
Once you've established a connection to the database, you can run/perform a variety of actions on it.
☞ mysqli_query()
PHP includes a built-in function to carry out many database operations, including create, insert, update, and delete. i.e. mysqli_query()
format:
mysqli_query(Connection,Query);
The above function has two parameters, those are
- Connection : Specifies the name of the connection
- Query: Specifies the query
☞ An example program to create to table in the database.
Example: "TblCreation.php"
Output :
The "students" table structure in database :
☞ An example program to insert data into table.
Example: "InsertRecord.php"
Output :
The data in the "students" table :
☞ An example program to delete data from the table.
Example: "DeleteRecord.php"
Output :
Retrieve data from Table
In PHP, mysqli_query() function is used to retrieve data from table. There are two other MySQLi functions used in select query. those are,
- mysqli_num_rows(mysqli_result $result): returns number of rows.
- mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each key of the array represents the name of column. It return NULL if there are no more rows.
☞ An example program to Select/retrive data from the table.
Example: "SelectRecord.php"