0% found this document useful (0 votes)
17 views12 pages

TY CO PHP Unit 05

The document provides an overview of database operations using PHP and MySQL, including creating, inserting, updating, and deleting records. It explains how to connect to a MySQL database using MySQLi and PDO, and outlines the syntax for various database operations. Additionally, it includes practical examples and practice questions to reinforce the concepts discussed.

Uploaded by

Geetanjali Patil
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)
17 views12 pages

TY CO PHP Unit 05

The document provides an overview of database operations using PHP and MySQL, including creating, inserting, updating, and deleting records. It explains how to connect to a MySQL database using MySQLi and PDO, and outlines the syntax for various database operations. Additionally, it includes practical examples and practice questions to reinforce the concepts discussed.

Uploaded by

Geetanjali Patil
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/ 12

Unit-V Database Operations

5a Create database for the given problem using PHP script.


5b Insert data in the given database using PHP script.
5c Apply the specified update operation in database record
Topics and Sub-topics
5.1 Introduction to MySQL - Create a database.
5.2 Connecting to a MySQL, database: MySQL database server from PHP
5.3 Database operations: Insert data, retrieving the Query result
5.4 Update and delete operations on table

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.

A Database Management System (DBMS) is system software designed to create, manage,


and manipulate databases. It provides users and programmers with a structured approach to
data storage, retrieval, modification, and administration.

Today, most applications rely on Relational Database Management Systems (RDBMS) to


handle large volumes of data. RDBMSs use structured tables with predefined relationships,
allowing for efficient organization and retrieval of data. Some popular RDBMSs include
MySQL, PostgreSQL, Oracle, and Microsoft SQL Server.

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.

5.1 Introduction to MySQL


PHP is highly flexible when working with MySQL databases compared to other database
systems. The data transfer between PHP scripts and MySQL databases is smooth and efficient.

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

 MySQL processes queries quickly and handles large datasets efficiently.


 It is highly compatible with PHP, making it ideal for web development.
 MySQL uses standard SQL statements, ensuring consistency across platforms.

5.1.1 MySQL and PHP Syntax

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.

5.1.2 Creating a Database in MySQL

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.

Steps to Create a Database:

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:

To verify the creation of the database, use:

SHOW DATABASES;

Creating a Database Using PHP


PHP provides the mysql_query() function to create a MySQL database. This function takes
parameters and returns True on success or False on failure.

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

5.2 CONNECTING TO A MYSQL DATABASE

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:

1. MySQLi (MySQL Improved) extension


2. PDO (PHP Data Objects)
5.2.1 Connecting to MySQL Database from PHP

PHP provides two primary methods for connecting to a MySQL database:

 mysqli_connect()
 PDO::__construct()

5.2.1.1 Using mysqli_connect() Function

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

echo "Connected successfully";

// Close connection
mysqli_close($conn);
?>
Output:
Connected successfully

5.2.1.2 Using PDO::_ _construct () Function

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

// Set error mode to exception


$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

echo "Connected successfully";


} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Output:
Connected successfully

Creating a Table in MySQL


The CREATE TABLE statement is used to create a table in MySQL. To create tables in a database,
follow these steps:

1. Write an SQL query to create the table.


2. Execute the query using mysqli_query() (for MySQLi) or $conn->exec() (for PDO).

Example using MySQLi:


<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'test_db';

// Establish connection
$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// SQL query to create table


$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table 'users' created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}

// 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);

// Set error mode to exception


$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// SQL query to create table


$sql = "CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

// 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

Note: The mysql_query() function is deprecated. Instead, we use mysqli_query() or PDO.

5.3.1 Insert Data

The mysqli_query() function executes SQL queries, including INSERT statements.

Example: Insert Data into MySQL Table


<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'test';

// Create connection
$conn = mysqli_connect($host, $user, $pass, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully...<br/>";

// SQL Insert Query


$sql = "INSERT INTO emp4 (name, salary) VALUES ('Sonco', 9000)";

if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully...";
} else {
echo "Error inserting record: " . mysqli_error($conn);
}

// Close the connection


mysqli_close($conn);
?>
Expected Output:
Connected successfully...
Record inserted successfully...
5.3.2 Retrieving Data

To retrieve data from a MySQL table, use the SELECT statement with mysqli_query().

Example: Retrieve Data from MySQL Table


<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'test';

// Create connection
$conn = mysqli_connect($host, $user, $pass, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully...<br/>";

// SQL Select Query


$sql = "SELECT id, name, salary FROM emp4";
$result = mysqli_query($conn, $sql);

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.";
}

// Close the connection


mysqli_close($conn);
?>
Expected Output:
Connected successfully...
EMP ID : 1
EMP NAME: Ratan
EMP SALARY: 9000

EMP ID : 2
EMP NAME: Karan
EMP SALARY: 40000
EMP ID : 3
EMP NAME: Jai
EMP SALARY: 90000

5.4 UPDATE AND DELETE OPERATIONS ON TABLE DATA

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.

5.4.1 Update Data


PHP mysql query() function is used to update record in a table.

Example:
<?php
$host = 'localhost:3306';
$user = 'root'; // Change as needed
$pass = ''; // Change as needed
$dbname = 'test';

$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo "Connected successfully...<br/>";

$id = 2;
$name = "Rahul";
$salary = 80000;

$sql = "UPDATE emp4 SET name='$name', salary=$salary WHERE id=$id";

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";

$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
die("Could not connect: " . mysqli_connect_error());
}

echo "Connected successfully...<br/>";

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

You might also like