TY CO PHP Unit 05
TY CO PHP Unit 05
5.0 INTRODUCTION
A database is a structured collection of related data that is organized to facilitate easy access,
management, and updating. In modern computing, databases play a crucial role in storing and
retrieving data efficiently.
PHP, a widely used server-side scripting language, can connect to and interact with various
database management systems. While PHP supports multiple databases such as Oracle,
PostgreSQL, and Sybase, the most commonly used database with PHP is MySQL, which is
open-source, reliable, and widely supported.
By integrating PHP with an RDBMS, developers can create dynamic, data-driven web
applications that allow users to store, update, and retrieve information seamlessly.
Nowadays, MySQL is the most popular open-source Relational Database Management System
(RDBMS). In MySQL, data is stored in the form of tables. MySQL works well with various
programming languages such as PERL, C, C++, Java, and PHP. Among these, PHP is the most
widely used because of its powerful web application development capabilities.
PHP provides various functions to access and manipulate data within a MySQL database.
MySQL is a web-based database system that operates on a server and is published under an
open-source license agreement. It handles large-scale databases efficiently and supports
multiple programming environments, including C, C++, PHP, and Java.
Advantages of MySQL with PHP
PHP provides various functions to interact with MySQL databases. These functions follow a
general syntax:
General Syntax:
mysql_function(value, value,...);
The function name is specific to the action being performed. Below are two commonly used
MySQL functions in PHP:
mysqli_connect($connect);
mysqli_query($connect, "SQL statement");
Example:
<html>
<head>
<title>PHP with MySQL</title>
</head>
<body>
<?php
$retval = mysql_function(value, [value,...]);
if (!$retval) {
die("Error: a related error message");
}
// MySQL or PHP Statements
?>
</body>
</html>
A database stores information in an organized manner. For example, a company database may
include tables such as Employees, Products, Customers, and Orders.
A database is a structured collection of data. MySQL allows us to store and retrieve data
efficiently. We can create a database using the CREATE DATABASE statement. However, if the
database already exists, an error will occur. To prevent this, we use the IF NOT EXISTS clause.
1. Open the MySQL console and enter the password (if set during installation).
2. Execute the following command:
Syntax:
CREATE DATABASE database_name;
Example:
CREATE DATABASE employees;
Checking the Created Database:
SHOW DATABASES;
Syntax:
bool mysql_query(sql, connection);
PHP also provides the mysql_select_db() function to select a database, which returns True on
success or False on failure.
Syntax:
bool mysql_select_db(db_name, connection);
PHP supports various database systems, including Oracle and Sybase, but the most commonly
used is MySQL, which is freely available.
In PHP 5 and later, there are two main ways to connect to a MySQL database:
mysqli_connect()
PDO::__construct()
The mysqli_connect() function is used to establish a connection with a MySQL database. If the
connection is successful, it returns a connection resource; otherwise, it returns false.
Syntax:
mysqli_connect(server, username, password, database);
Example:
<?php
$host = 'localhost'; // Change this to your server name if needed
$user = 'root'; // Your database username
$pass = ''; // Your database password
$dbname = 'test_db'; // Your database name
// Establish connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
if (!$conn) {
die("Could not connect: " . mysqli_connect_error());
}
// Close connection
mysqli_close($conn);
?>
Output:
Connected successfully
The PDO extension provides a flexible and secure way to connect to multiple database systems,
including MySQL, PostgreSQL, SQLite, and more. It allows switching databases with minimal
changes in the code.
Syntax:
public PDO::__construct (string $dsn [, string $username [, string $password [, array $options
]]])
Example:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
try {
// Create a PDO connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Establish connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Close connection
mysqli_close($conn);
?>
Example using PDO:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
try {
// Create a PDO connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Execute query
$conn->exec($sql);
echo "Table 'users' created successfully";
} catch (PDOException $e) {
echo "Error creating table: " . $e->getMessage();
}
// Close connection
$conn = null;
?>
5.3 DATABASE OPERATIONS
PHP provides built-in functions to interact with MySQL databases. The most commonly used
operations include:
Inserting data
Retrieving data
Updating data
Deleting data
// Create connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully...<br/>";
if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully...";
} else {
echo "Error inserting record: " . mysqli_error($conn);
}
To retrieve data from a MySQL table, use the SELECT statement with mysqli_query().
// Create connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully...<br/>";
if (mysqli_num_rows($result) > 0) {
// Output data for each row
while ($row = mysqli_fetch_assoc($result)) {
echo "EMP ID : {$row['id']} <br> " .
"EMP NAME: {$row['name']} <br> " .
"EMP SALARY: {$row['salary']} <br> " .
"<br>";
}
} else {
echo "No results found.";
}
EMP ID : 2
EMP NAME: Karan
EMP SALARY: 40000
EMP ID : 3
EMP NAME: Jai
EMP SALARY: 90000
To modify existing records in a MySQL table, the SQL UPDATE statement is used. In PHP,
we execute this statement using the mysqli_query() or PDO function.
Example:
<?php
$host = 'localhost:3306';
$user = 'root'; // Change as needed
$pass = ''; // Change as needed
$dbname = 'test';
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo "Connected successfully...<br/>";
$id = 2;
$name = "Rahul";
$salary = 80000;
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully..";
} else {
echo "Could not update record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Connected successfully...
Record updated successfully..
5.4.2 Delete Data
PHP mysql_query() function is used to delete record in a table.
Example:
<?php
$host = "localhost:3306";
$user = "root"; // Replace with your database username
$pass = ""; // Replace with your database password
$dbname = "test";
if (!$conn) {
die("Could not connect: " . mysqli_connect_error());
}
$id = 2;
$sql = "DELETE FROM emp4 WHERE id = $id";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully...";
} else {
echo "Could not delete record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Connected successfully...
Record deleted successfully...
Practise Questions:
1. What is a database?
2. What is DBMS?
3. What is MySQL? How is it used in PHP?
4. Explain how to create and delete a database in MySQL.
5. Explain the mysqli_connect() function with an example.
6. Explain the PDO::__construct() function with an example.
7. How do you connect a database to MySQL? Explain with an example.
8. How do you insert a record into a table in MySQL using PHP?
9. How do you update a record in a table in MySQL using PHP?
10. How do you retrieve a record from a table in MySQL using PHP?
11. Compare mysqli_connect() and PDO::__construct() for database connection in PHP.
12. Analyze different ways to perform insert, update, and delete operations in MySQL
using PHP.
13. Evaluate the advantages and disadvantages of using MySQLi vs. PDO for database
operations in PHP.
14. Assess the security risks involved in database connections and operations in PHP.
15. Write a PHP program to create an employee table and perform insert, delete, and update
operations.
16. Develop a secure and optimized database connection method using MySQL in PHP.