0% found this document useful (0 votes)
6 views17 pages

UNIT5 PHP

The document provides an overview of MySQL and its integration with PHP, detailing how to connect to a MySQL database, select a database, and perform basic operations such as inserting, selecting, updating, and deleting data. It includes code examples demonstrating the use of PHP functions like mysqli_connect(), mysqli_select_db(), and various SQL statements. The document serves as a study guide for MGSU exams, focusing on practical applications of PHP with MySQL.

Uploaded by

mafiatitan946
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views17 pages

UNIT5 PHP

The document provides an overview of MySQL and its integration with PHP, detailing how to connect to a MySQL database, select a database, and perform basic operations such as inserting, selecting, updating, and deleting data. It includes code examples demonstrating the use of PHP functions like mysqli_connect(), mysqli_select_db(), and various SQL statements. The document serves as a study guide for MGSU exams, focusing on practical applications of PHP with MySQL.

Uploaded by

mafiatitan946
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

PHP NOTES FOR MGSU EXAMS

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 a database system that runs on a server.

MySQL is ideal for both small and large applications.

MySQL is very fast, reliable, and easy to use database system.It uses standard SQL

MySQL compiles on a number of platforms.

Open a Connection to MySQL

PHP provides mysqli_connect() function to open a database connection. MySQLi extension (the

"i" stands for improved)

This function takes four parameters and returns a MySQL link identifier on success or FALSE

on failure.

1. Provide parameters to function

To establish a connection between PHP and MYSQL, an in-built function mysqli_connect() is

used, which takes four parameters, fisrt one is name of server, username, password and
database

name. Databse name is optional.

2. create connection

After getting all the parameters, we will create connection using a variable $conn.

$conn= mysqli_connect($servername, $username, $password);

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


2

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().

4. Close the connection

Mysqli_close($conn);

After completing the task close the opened connection using mysqli_close().

<?php

$servername = "localhost";

$username = "username";

$password = "password";

// Create connection

$conn = mysqli_connect($servername, $username, $password);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

echo "Connected successfully";

?>

mysqli_close($conn)

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


3

Selecting MySQL Database

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

mysqli_select_db ( mysqli $link , string $dbname ) : bool

Sr.No. Parameter & Description

1
$link
Required - A link identifier returned by mysqli_connect() or mysqli_init().

2
$dbname
Required - Name of the database to be connected.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


4

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

Database TUTORIALS selected successfully

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


5

Insert or add Data into MySQL Table using PHP(fill the


table with data)
After a database and a table have been created, we can start adding data in them. Here are
some syntax rules to follow:

• The SQL query must be quoted in PHP

• String values inside the SQL query must be quoted

• Numeric values must not be quoted

• The word NULL must not be quoted

The INSERT INTO statement is used to add new records to a MySQL table:

INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2,


value3,...

<?php

$servername = "localhost";

$database = "u123456789_mydatabase";

$username = "u123456789_myuser";

$password = "PasSw0rd123@";

// Create a connection

$conn = mysqli_connect($servername, $username, $password, $database);

// Check the connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

echo "Connected successfully";


PHP NOTES FOR MGSU EXAMS GORISH MITTAL
6

$sql = "INSERT INTO Students (name, lastName, email) VALUES ('Tom', 'Jackson',
'[email protected]')";

if (mysqli_query($conn, $sql)) {

echo "New record created successfully";

} else {

echo "Error: " . $sql . "<br>" . mysqli_error($conn);

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].

Additionally, users must set SQL queries between quotes. In our


example, everything written in quotes after $sql = is an SQL query.
PHP NOTES FOR MGSU EXAMS GORISH MITTAL
7

Select or display Data From a MySQL Database

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

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


8

SELECT column_name(s) FROM table_name

or we can use the * character to select ALL columns from a table

SELECT * FROM table_name

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

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

$sql = "SELECT id, firstname, lastname FROM MyGuests";

$result = mysqli_query($conn, $sql);

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


9

if (mysqli_num_rows($result) > 0) {

// output data of each row

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

Select and Filter Data From a MySQL Database


The WHERE clause is used to filter records.

The WHERE clause is used to extract only those records that fulfill a specified condition.

SELECT column_name(s) FROM table_name WHERE column_name operator value

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.

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


10

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

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

$sql = "SELECT id, firstname, lastname FROM MyGuests WHERE lastname='Doe'";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

// output data of each row

while($row = mysqli_fetch_assoc($result)) {

echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";

} else {

echo "0 results";

mysqli_close($conn);

?>

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


11

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 selected column data from database the SQL query is

DELETE FROM table_name WHERE some_column=some_value;

To delete all the column data from a table the SQL query is

DELETE FROM table_name;

or
DELETE * FROM table_name;

Let's look at the "MyGuests" table:

Id firstname lastname email reg_date


1 John Doe [email protected] 2014-10-22 14:26:15
2 Mary Moe [email protected] 2014-10-23 10:22:30

3 Julie Dooley [email protected] 2014-10-26 10:48:2

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

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());

// sql to delete a record


$sql = "DELETE FROM MyGuests WHERE id=3";

if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";

} else {

echo "Error deleting record: " . mysqli_error($conn);


}

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.

The basic syntax of the UPDATE statement can be given with:

UPDATE table_name SET column1=value, column2=value2,... WHERE column_name=some_value

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 NOTES FOR MGSU EXAMS GORISH MITTAL


13

+----+------------+-----------+----------------------+

| id | first_name | last_name | email |

+----+------------+-----------+----------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | John | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

+----+------------+-----------+----------------------+

<?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());

$sql = "UPDATE MyGuests SET last_name='Doe' WHERE id=2";

if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {

echo "Error updating record: " . mysqli_error($conn);


}

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


14

mysqli_close($conn);

?>

After update the persons table will look something like this:
+----+------------+-----------+--------------------------+

| id | first_name | last_name | email |

+----+------------+-----------+--------------------------+

| 1 | Peter | Parker | [email protected] |

| 2 | Doe | Rambo | [email protected] |

| 3 | Clark | Kent | [email protected] |

| 4 | John | Carter | [email protected] |

| 5 | Harry | Potter | [email protected] |

Executing multiple SQL queries in one


statement with PHP
In PHP, you can execute multiple SQL queries in one statement by using the
mysqli_multi_query() function. This function allows you to pass in a string containing
multiple SQL queries separated by a semicolon. Each query will be executed in the
order they are written.

Syntax

bool mysqli_multi_query ( mysqli $link , string $query );

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


15

Return Values
It returns true on success or false on failure.

Parameters

Sr.No Parameters & Description

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();
}

$sql = "SELECT Lastname FROM Persons;SELECT Country FROM Customers";

if (mysqli_multi_query($connection_mysql,$sql)){

echo “data fached successfully”;

}
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

PHP NOTES FOR MGSU EXAMS GORISH MITTAL


16

And using mysqli_multi_query() function to execute the query

PHP NOTES FOR MGSU EXAMS GORISH MITTAL

You might also like