php unit 5
php unit 5
Unit Notes
For
“MySQL”
Session 2024-25
BCA 2nd
UNIT-(5)
Lecturer
PHP: Introduction to PHP, Server side scripting, Role of Web Server software, including
files, comments, variables and scope, echo and print, Operators: Logical, Comparison and
Conditional operators, Branching statements, Loops, break and continue PHP functions.
Passing information between pages, HTTP GET and POST method, String functions: strlen,
strops, strstr, strcmp, substr, str_replace, string case, Array constructs: array(), list() and
foreach(), PHP advanced functions: Header, Session, Cookie, Object Oriented
Programming using PHP: class, object, constructor, destructor and inheritance.
UNIT-V
MySQL is a popular relational database management system (RDBMS) used with PHP to
store, retrieve, and manage data. MySQL stores data in tables and uses SQL (Structured
Query Language) to perform database operations.
When PHP is combined with MySQL, it allows developers to create web applications that store
data (like user accounts, product information, etc.), retrieve it, and present it dynamically to
users.
Features of MySQL
1. Open-Source: MySQL is free to use and open-source, making it accessible for developers
and organizations of any size.
2. High Performance: MySQL is optimized for speed and performance, making it suitable
for high-demand applications.
3. Scalability: It supports large databases and can handle large amounts of data, making it
suitable for small applications as well as high-traffic websites.
4. Data Security: MySQL provides strong data security with access control, data
encryption, and support for secure connections (SSL).
5. Supports Multiple Platforms: MySQL works across many operating systems, such as
Windows, Linux, and macOS.
6. ACID Compliance: MySQL supports ACID (Atomicity, Consistency, Isolation, Durability)
properties, which are essential for transaction reliability and data integrity, especially in
financial applications.
7. Multi-User Support: MySQL supports multiple users with permissions, allowing many
users to work on the same data simultaneously.
8. Replications and Backups: MySQL supports replication (copying databases across
servers) and backup features for data redundancy and disaster recovery.
9. Built-In Functions and Tools: It includes built-in functions for mathematical calculations,
string manipulation, date formatting, and other operations, along with tools like MySQL
Workbench for database design and management.
10. Community and Support: MySQL has a large community, providing ample
documentation, tutorials, and support forums, as well as enterprise support options
from Oracle.
In MySQL, data types are categorized into different types to store various kinds of data. Each
column in a table must have a data type that defines the kind of data it can hold, such as
numbers, text, dates, etc.
Here’s an example of how you might define data types for columns in a MySQL table:
In this table:
SQL (Structured Query Language) is a language used to manage and manipulate data in
relational databases like MySQL, PostgreSQL, Oracle, and SQL Server. SQL commands allow
users to retrieve, insert, update, and delete data, as well as manage database structures and
control access. Here’s an introduction to some of the core SQL commands:
1. SELECT Command
The SELECT command is used to retrieve data from a database. It specifies which columns you
want to see and allows for filtering and sorting data.
Syntax:
Example:
This query retrieves the first_name and last_name of employees in the "Sales" department.
2. INSERT Command
The INSERT command adds new records to a table. It can specify values for each column or just
certain columns if others are allowed to be null or have default values.
Syntax:
Example:
3. UPDATE Command
The UPDATE command modifies existing records in a table. It requires a WHERE clause to
specify which records to update; without it, all rows will be updated.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example:
UPDATE Employees
SET salary = 55000
WHERE first_name = 'John' AND last_name = 'Doe';
Note: Use the WHERE clause carefully; without it, all rows in the table will be updated.
4. DELETE Command
The DELETE command removes records from a table. Like UPDATE, it requires a WHERE clause
to specify which records to delete; otherwise, all rows in the table will be deleted.
Syntax:
Example:
This query deletes the employee with the last name "Doe" from the "Marketing" department.
Warning: Be cautious with the DELETE command, as omitting the WHERE clause will
delete all records in the table.
Summary Table of Basic SQL Commands
Command Description Example
Retrieves data from one or
SELECT SELECT first_name, last_name FROM Employees;
more tables
INSERT INTO Employees (first_name, last_name)
INSERT Adds new records to a table
VALUES ('John', 'Doe');
Modifies existing records in a UPDATE Employees SET salary = 55000 WHERE
UPDATE
table first_name = 'John';
DELETE Removes records from a table DELETE FROM Employees WHERE last_name = 'Doe';
These four commands are the foundation of SQL and allow you to perform essential data
manipulation tasks in a database.
MySQLi functions
PHP provides a set of MySQLi functions to work with MySQL databases. Here’s an overview of
some commonly used MySQLi functions and examples to illustrate each function’s purpose:
1. mysqli_connect()
Syntax:
Example:
if (!$connection)
{
die("Connection failed: " . mysqli_connect_error());
}
2. mysqli_select_db()
mysqli_select_db($connection, "database_name");
Example:
3. mysqli_query()
Syntax:
Example:
if (!$result)
{
echo "Error: " . mysqli_error($connection);
}
4. mysqli_fetch_row()
Syntax:
$row = mysqli_fetch_row($result);
Example:
Syntax:
Example:
6. mysqli_fetch_object()
Syntax:
$row = mysqli_fetch_object($result);
Example:
MySQLi doesn’t directly use mysqli_result, but this term is often used to refer to the
resource returned by mysqli_query() when used in a SELECT query.
You can navigate the result set with mysqli_fetch_row(), mysqli_fetch_assoc(), etc., to
extract data row-by-row.
<?php
// Connect to the database
$connection = mysqli_connect("localhost", "root", "123456", "test_db");
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
if ($result) {
// Fetch rows as associative arrays
while ($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row['id'] . " - Name: " . $row['name'] . " - Email: " . $row['email'] . "<br>";
}
} else {
echo "Error: " . mysqli_error($connection);
}
Summary
These functions are essential for performing operations on a MySQL database through PHP.
Here’s a simple example to demonstrate how to insert and delete data in a MySQL database
using PHP with a connection and result set variable $rs on the same page.
Requirements
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// INSERT operation
if (isset($_POST['insert'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$insert_query = "INSERT INTO employees (name, email) VALUES ('$name', '$email')";
if ($rs) {
echo "Data inserted successfully!";
} else {
echo "Error inserting data: " . mysqli_error($connection);
}
}
// DELETE operation
if (isset($_POST['delete'])) {
$id = $_POST['id'];
$delete_query = "DELETE FROM employees WHERE id = $id";
if ($rs) {
echo "Data deleted successfully!";
} else {
echo "Error deleting data: " . mysqli_error($connection);
}
} ?>
<!DOCTYPE html>
<html>
<head>
<title>Insert and Delete Data</title>
</head>
<body>
<h2>Insert Data</h2>
<form method="post">
Name: <input type="text" name="name" required>
Email: <input type="email" name="email" required>
<input type="submit" name="insert" value="Insert">
</form>
<h2>Delete Data</h2>
<form method="post">
ID to delete: <input type="number" name="id" required>
<input type="submit" name="delete" value="Delete">
</form>
</body>
</html>
<?php
// Close the database connection
mysqli_close($connection);
?>
Explanation
Here’s a simple PHP script to display data from a MySQL database on a webpage. This example
uses a table called employees with columns id, name, and email.
?>
Explanation
This code will output an HTML table showing all entries in the employees table. If there are no
records, it displays a "No data found" message.