0% found this document useful (0 votes)
0 views

php unit 5

This document provides unit notes for a MySQL course, covering PHP and MySQL integration, SQL commands, and MySQLi functions. It details MySQL features, data types, and basic SQL commands such as SELECT, INSERT, UPDATE, and DELETE. Additionally, it includes examples of using PHP to interact with a MySQL database for data insertion and deletion.

Uploaded by

antra150906
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

php unit 5

This document provides unit notes for a MySQL course, covering PHP and MySQL integration, SQL commands, and MySQLi functions. It details MySQL features, data types, and basic SQL commands such as SELECT, INSERT, UPDATE, and DELETE. Additionally, it includes examples of using PHP to interact with a MySQL database for data insertion and deletion.

Uploaded by

antra150906
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

A

Unit Notes

For

“MySQL”

Session 2024-25

BCA 2nd

UNIT-(5)

Mr. Manish Sao

Lecturer

Department of Computer Science & Engineering

RSR Rungta College of Engineering & Technology Bhilai

Rungta Knowledge City Kohka Kurud Road


Bhilai (C.G.)
1
UNIT-IV

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: Features of MySQL, data types, Introduction to SQL commands-SELECT. DELETE,


UPDATE, INSERT, PHP functions for MySQL operations: mysql_connect, mysql_select_db,
mysql_query,mysql_fetch_row, mysql_fetch_array, mysql_fetch_object, mysql_result,
Insertion and Deletion of data using PHP, Displaying data from MYSQL in webpage.
MySQL

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.

MySQL Data Types

1. Numeric Data Types


o Used to store numbers.
o Can be either integers, decimals, or floating-point numbers.

Data Type Description


TINYINT Very small integer (-128 to 127 or 0 to 255 for unsigned).
SMALLINT Small integer (-32,768 to 32,767 or 0 to 65,535 for unsigned).
MEDIUMINT Medium integer (-8,388,608 to 8,388,607 or 0 to 16,777,215 for unsigned).
INT or Standard integer (-2,147,483,648 to 2,147,483,647 or 0 to 4,294,967,295 for
INTEGER unsigned).
BIGINT Large integer (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807).
FLOAT Small floating-point number.
DOUBLE Large floating-point number.
DECIMAL Stores exact numeric data (e.g., monetary values).

2. String Data Types


o Used to store text or string data.

Data Type Description


CHAR Fixed-length string (0-255 characters).
VARCHAR Variable-length string (0-65,535 characters).
TEXT Large amount of text data (up to 65,535 characters).
TINYTEXT Small amount of text data (up to 255 characters).
MEDIUMTEXT Medium amount of text data (up to 16,777,215 characters).
Very large amount of text data (up to 4,294,967,295
LONGTEXT
characters).
BLOB Binary large object for storing binary data, like images or files.
TINYBLOB, MEDIUMBLOB,
Similar to BLOB but with different storage capacities.
LONGBLOB
Stores one value from a list of possible values (e.g., 'small',
ENUM
'medium', 'large').
Stores multiple values from a list of possible values (e.g., 'red',
SET
'blue', 'green').
3. Date and Time Data Types
o Used to store dates, times, or both.

Data Type Description


DATE Stores date values in YYYY-MM-DD format.
TIME Stores time values in HH:MM:SS format.
DATETIME Stores date and time in YYYY-MM-DD HH:MM:SS format.
Stores date and time as a Unix timestamp (automatically updated on
TIMESTAMP
insert/update).
YEAR Stores year values in a 4-digit format (e.g., 2023).

4. Spatial Data Types


o Used to store geographical data.

Data Type Description


GEOMETRY Stores any type of geometric data.
POINT Stores a point in a 2D space (X, Y coordinates).
LINESTRING Stores a line, which is a series of points.
POLYGON Stores a polygon shape, which is a closed area defined by points.

Examples of Data Types in a MySQL Table

Here’s an example of how you might define data types for columns in a MySQL table:

CREATE TABLE Employees (


id INT PRIMARY KEY AUTO_INCREMENT,
first_name VARCHAR(50),
last_name VARCHAR(50),
salary DECIMAL(10, 2),
hire_date DATE,
is_active TINYINT(1)
);

In this table:

 id is an integer and auto-incrementing primary key.


 first_name and last_name are variable-length strings with a maximum of 50 characters
each.
 salary is a decimal number that can hold 10 digits, with 2 digits after the decimal.
 hire_date is a date in YYYY-MM-DD format.
 is_active is a tiny integer (often used to store boolean values like 0 for inactive and 1 for
active).
SQL (Structured Query Language)

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:

SELECT column1, column2, ...


FROM table_name
WHERE condition;

Example:

SELECT first_name, last_name


FROM Employees
WHERE department = 'Sales';

This query retrieves the first_name and last_name of employees in the "Sales" department.

 WHERE clause: Used to filter records based on conditions.


 ORDER BY clause: Sorts the result (e.g., ORDER BY last_name ASC;).

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:

INSERT INTO table_name (column1, column2, ...)


VALUES (value1, value2, ...);

Example:

INSERT INTO Employees (first_name, last_name, department, salary)


VALUES ('John', 'Doe', 'Marketing', 50000);
This query adds a new employee with the name "John Doe" to the "Marketing" department
with a salary of 50,000.

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

This query updates the salary of "John Doe" to 55,000.

 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:

DELETE FROM table_name


WHERE condition;

Example:

DELETE FROM Employees


WHERE department = 'Marketing' AND last_name = 'Doe';

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

 This function opens a new connection to the MySQL database.


 Returns a connection object on success, or false on failure.

Syntax:

$connection = mysqli_connect("hostname", "username", "password", "database");

Example:

$connection = mysqli_connect("localhost", "root", "123456", "test_db");

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

2. mysqli_select_db()

 This function selects a specific database for the connection.


 In MySQLi’s procedural style, this function is usually not necessary since
mysqli_connect() can select the database directly.
Syntax:

mysqli_select_db($connection, "database_name");

Example:

// Select the database (optional if specified in mysqli_connect)


mysqli_select_db($connection, "test_db");

3. mysqli_query()

 This function performs a query against the database.


 Used for both SELECT and INSERT, UPDATE, or DELETE operations.
 Returns a result set for SELECT queries or true/false for data modification queries.

Syntax:

$result = mysqli_query($connection, "SQL_QUERY");

Example:

$sql = "SELECT * FROM employees";


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

if (!$result)
{
echo "Error: " . mysqli_error($connection);
}

4. mysqli_fetch_row()

 Fetches a result row as a numerical array (indexed by column numbers).


 Returns null if no more rows are available.

Syntax:

$row = mysqli_fetch_row($result);

Example:

while ($row = mysqli_fetch_row($result))


{
echo "ID: " . $row[0] . " Name: " . $row[1] . "<br>";
}
5. mysqli_fetch_array()

 Fetches a result row as an associative and/or numerical array.


 You can specify MYSQLI_ASSOC (associative), MYSQLI_NUM (numerical), or
MYSQLI_BOTH (default).

Syntax:

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

Example:

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))


{
echo "ID: " . $row['id'] . " Name: " . $row['name'] . "<br>";
}

6. mysqli_fetch_object()

 Fetches a result row as an object, where columns can be accessed as properties.

Syntax:

$row = mysqli_fetch_object($result);

Example:

while ($row = mysqli_fetch_object($result))


{
echo "ID: " . $row->id . " Name: " . $row->name . "<br>";
}

7. mysqli_result (for mysqli_fetch_* result manipulation)

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

Full Example of Using These Functions Together:

<?php
// Connect to the database
$connection = mysqli_connect("localhost", "root", "123456", "test_db");
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}

// Query to fetch data


$sql = "SELECT id, name, email FROM employees";
$result = mysqli_query($connection, $sql);

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

// Close the connection


mysqli_close($connection);
?>

Summary

 mysqli_connect(): Establishes a connection to the database.


 mysqli_select_db(): Selects a database (optional if included in mysqli_connect).
 mysqli_query(): Executes a SQL query.
 mysqli_fetch_row(): Fetches a row as a numeric array.
 mysqli_fetch_array(): Fetches a row as an associative or numeric array.
 mysqli_fetch_object(): Fetches a row as an object with properties.

These functions are essential for performing operations on a MySQL database through PHP.

insert and delete data in a MySQL

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

 Make sure you have a MySQL database with a table created.


 For this example, we’ll assume a database called test_db and a table employees with
columns id, name, and email.
Code Example
<?php
// Database connection details
$host = "localhost";
$username = "root";
$password = "123456";
$dbname = "test_db";

// Connect to MySQL database


$connection = mysqli_connect($host, $username, $password, $dbname);

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

$rs = mysqli_query($connection, $insert_query);

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

$rs = mysqli_query($connection, $delete_query);

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

1. Database Connection: Establishes a connection to the MySQL database using


mysqli_connect.
2. Insert Operation:
o If the "Insert" button is clicked, PHP gets the values from the form and uses
INSERT INTO SQL statement.
o mysqli_query executes the query, and the result is stored in $rs.
3. Delete Operation:
o If the "Delete" button is clicked, PHP gets the id from the form to delete that
particular record.
o mysqli_query executes the DELETE statement, and the result is stored in $rs.
4. Forms: Two simple forms are created to insert and delete data.
5. Close Connection: After the operations, the database connection is closed using
mysqli_close.

Display data from mysql in webpages

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.

PHP Code to Fetch and Display Data


<?php
// Database connection details
$host = "localhost";
$username = "root";
$password = "123456";
$dbname = "test_db";

// Connect to MySQL database


$connection = mysqli_connect($host, $username, $password, $dbname);

// Check if connection is successful


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

// SQL query to fetch data from the table


$sql = "SELECT id, name, email FROM employees";
$result = mysqli_query($connection, $sql);

// Start the HTML table


echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>";

// Loop through and display each row


while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>
<td>" . $row['id'] . "</td>
<td>" . $row['name'] . "</td>
<td>" . $row['email'] . "</td>
</tr>";
}
echo "</table>";

?>

Explanation

1. Database Connection: Connects to the MySQL database using mysqli_connect.


2. SQL Query: Executes a SELECT query to fetch id, name, and email columns from the
employees table.
3. Check and Display Results:
o If there are rows returned, the code starts an HTML table and loops through
each row.
o mysqli_fetch_assoc($result) retrieves each row as an associative array.
o Each row is displayed in a table row with the id, name, and email fields.
4. Close Connection: After displaying the data, the script closes the connection to the
database.

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.

You might also like