UNIT5 PHP
UNIT5 PHP
UNIT-5
1
What is MySQL?
MySQL is an open-source relational database management system (RDBMS). It is the most
popular database system used with PHP. MySQL is developed, distributed, and supported by
Oracle Corporation.
The data in a MySQL database are stored in tables which consists of columns and rows.
MySQL is very fast, reliable, and easy to use database system.It uses standard SQL
PHP provides mysqli_connect() function to open a database connection. MySQLi extension (the
This function takes four parameters and returns a MySQL link identifier on success or FALSE
on failure.
used, which takes four parameters, fisrt one is name of server, username, password and
database
2. create connection
After getting all the parameters, we will create connection using a variable $conn.
3. Check connection
After establishing the connection we must check the connection whether properly connected or
not. If not connected then display the connection related error by mysqli_connect_error().
Mysqli_close($conn);
After completing the task close the opened connection using mysqli_close().
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
// Check connection
if (!$conn) {
?>
mysqli_close($conn)
Once you get connected with the MySQL server, it is required to select a
database to work with. This is because there might be more than one database
available with the MySQL Server.
PHP uses mysqli_select_db function to select the database on which queries are
to be performed. This function takes two parameters and returns TRUE on
success or FALSE on failure.
Syntax
1
$link
Required - A link identifier returned by mysqli_connect() or mysqli_init().
2
$dbname
Required - Name of the database to be connected.
Example
<html>
<head>
<title>Selecting MySQL Database</title>
</head>
<body>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root@123';
$conn = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysqli_error($conn));
}
echo 'Connected successfully<br />';
$retval = mysqli_select_db( $conn, 'TUTORIALS' );
if(! $retval ) {
die('Could not select database: ' . mysqli_error($conn));
}
echo "Database TUTORIALS selected successfully\n";
mysqli_close($conn);
?>
</body>
</html>
Output
The INSERT INTO statement is used to add new records to a MySQL table:
<?php
$servername = "localhost";
$database = "u123456789_mydatabase";
$username = "u123456789_myuser";
$password = "PasSw0rd123@";
// Create a connection
if (!$conn) {
$sql = "INSERT INTO Students (name, lastName, email) VALUES ('Tom', 'Jackson',
'[email protected]')";
if (mysqli_query($conn, $sql)) {
} else {
mysqli_close($conn);
?>
$sql = "INSERT INTO Students (name, lastName, email) VALUES ('Tom', 'Jackson',
'[email protected]')";
The INSERT INTO is a statement that adds data to the specified MySQL
database table. In the example above, we are adding data to the
table Students.
Between the parenthesis, the table column names specify where we want
to add the values (name, lastName, email). The script will add the data
in the specified order. If we write (email, lastName, name), the script will
add the values in the wrong order.
The next part is the VALUES statement. Here, we specify values in the
previously selected columns. Our example would be name = Tom,
lastName = Jackson, email = [email protected].
For displaying data on the web page we have to fetch data from the MySQL database. As we
can se in the above diagram
• The visitor’s web browser requests the web page from your web server.
• The web server software (typically Apache or NGINX) recognizes that the requested file is
a PHP script, so the server fires up the PHP interpreter to execute the code contained in
the file.
• Php scrip execute the sql query for selecting the data form the database
• from this query we request the database for the data if the data according to the query is
present The MySQL database responds by sending the requested content to the PHP
script.
• The PHP script stores the content into one or more PHP variables, then uses echo
statements to output the content as part of the web page.
The SELECT statement is used to select or display the data from one or more tables
First, we set up an SQL query that selects the id, firstname and lastname columns from the
MyGuests table. The next line of code runs the query and puts the resulting data into a variable
called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.
The following example shows the same as the example above, in the MySQLi procedural way:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
// Check connection
if (!$conn) {
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
} else {
Output
echo "0 results";
}
id: 1- Name: John Doe
mysqli_close($conn);
id: 2- Name: May Moe
?> id: 3- Name- Julie Doely
The WHERE clause is used to extract only those records that fulfill a specified condition.
we set up the SQL query that selects the id, firstname and lastname columns from the
MyGuests table where the lastname is "Doe". The next line of code runs the query and puts the
resulting data into a variable called $result.
Then, the function num_rows() checks if there are more than zero rows returned.
If there are more than zero rows returned, the function fetch_assoc() puts all the results into an
associative array that we can loop through. The while() loop loops through the result set and
outputs the data from the id, firstname and lastname columns.
The following example shows the same as the example above, in the MySQLi procedural way:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
// Check connection
if (!$conn) {
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
} else {
mysqli_close($conn);
?>
Deleting Data
Just as you insert records into tables, you can delete records from a table using the
SQL DELETE statement. It is typically used in conjugation with the WHERE clause to
delete only those records that matches specific criteria or condition
To delete data from MySQL the DELETE statement is used. We can delete data from
specific column or all column of a table.
To delete all the column data from a table the SQL query is
or
DELETE * FROM table_name;
The following examples delete the record with id=3 in the "MyGuests" table
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
12
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
mysqli_close($conn);
?>
Update Data
The UPDATE statement is used to change or modify the existing records in a database
table. This statement is typically used in conjugation with the WHERE clause to apply
the changes to only those records that matches specific criteria.
Let's make a SQL query using the UPDATE statement and WHERE clause, after that we will
execute this query through passing it to the PHP mysqli_query() function to update the
tables records. Consider the following persons table inside the demo database:
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
+----+------------+-----------+----------------------+
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
mysqli_close($conn);
?>
After update the persons table will look something like this:
+----+------------+-----------+--------------------------+
+----+------------+-----------+--------------------------+
Syntax
Return Values
It returns true on success or false on failure.
Parameters
1
Connection
It specifies the mySql connection to use
2
Query
One or more queries separated by semicolons
<?php
$connection_mysql = mysqli_connect("localhost","user","pass","db");
if (mysqli_connect_errno($connection_mysql)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (mysqli_multi_query($connection_mysql,$sql)){
}
mysqli_close($connection_mysql);
?>
In the above example as we can se that we are passing two query one for fetching
lastname from person table and one for selecting country from customer table