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

mysql

The document provides an overview of MySQL, an open-source relational database management system, detailing its history, advantages, key features, and security measures. It discusses SQL workhorses, privileges, data types, and methods for connecting to and querying MySQL databases using PHP. Additionally, it covers MySQL functions, including aggregate, string, mathematical, and date/time functions.

Uploaded by

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

mysql

The document provides an overview of MySQL, an open-source relational database management system, detailing its history, advantages, key features, and security measures. It discusses SQL workhorses, privileges, data types, and methods for connecting to and querying MySQL databases using PHP. Additionally, it covers MySQL functions, including aggregate, string, mathematical, and date/time functions.

Uploaded by

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

Unit 5 – Web Designing With PHP

MySQL was introduced by a Swedish company called MySQL AB. The development of
MySQL was led by Michael "Monty" Widenius, David Axmark, and Allan Larsson. They
released the first version of MySQL in 1995. In 2008, Sun Microsystems acquired MySQL
AB, and later, in 2010, Oracle Corporation acquired Sun Microsystems

About MySQL Database.


MySQL is an open-source relational database management system (RDBMS) that is
widely used for building and managing databases. It is a key component in the LAMP
(Linux, Apache, MySQL, PHP/Python/Perl) and MERN (MongoDB, Express.js, React,
Node.js) stacks, making it a popular choice for web development
Advantages of MySQL
MySQL has become so popular for several reasons.
1. MySQL is free (as in price), although the licensing has changed.
2. MySQL is also stable, meaning that it’s not prone to crashing even under load.
3. MySQL is lightweight, meaning that it doesn’t require many resources to install or run.
4. MySQL is fast and easy to use.
5. MySQL is powerful, with all of the features required for web applications.
Key Features of MySQL

Key features of MySQL


1. Open Source:
MySQL is released under the GNU General Public License (GPL), making it freely
available for use, modification, and distribution.

2. Relational Database Management System (RDBMS):


MySQL is designed to manage relational databases, which organize data into tables
with rows and columns. It supports SQL for defining, querying, and manipulating the
data.
3. Scalability:
MySQL can handle databases of various sizes, from small-scale applications to large-
scale enterprise systems. It supports both read and write-intensive workloads.

1
4. Multi-platform Support:
MySQL is compatible with various operating systems, including Linux, Windows,
macOS, and others. This cross-platform support makes it versatile for different
environments.

5. Performance:
MySQL is known for its fast performance, efficient handling of concurrent transactions,
and low-latency response times. It includes various storage engines, such as InnoDB
and MyISAM, each with its own characteristics.

6. High Availability:
MySQL provides features like replication and clustering to ensure high availability and
fault tolerance. These features allow for the creation of redundant database systems to
handle failover scenarios.

7. Security:
MySQL offers robust security features, including user authentication, access control,
and encryption of data during transmission. This helps protect sensitive information
stored in the database.

Discuss about Workhorses of SQL in detail.


The term "workhorses of SQL" typically refers to the fundamental and essential
components or features of the SQL (Structured Query Language) that are commonly
used in database management.
These are the core functionalities that developers, database administrators, and
analysts rely on to interact with and manipulate data in relational databases.
The following are different workhorses of SQL:
1. SELECT Statement
2. INSERT Statement
3. UPDATE Statement
4. DELETE Statement
5. WHERE Clause
6. JOIN Operations
7. GROUP BY Clause

2
8. ORDER BY Clause
9. Index
1. SELECT Statement:
The SELECT statement is the core of SQL and is used to retrieve data from one or
more tables. It allows you to specify the columns you want to retrieve, apply filters, and
define sorting orders.
Example:
SELECT * FROM employees WHERE department = 'IT';

2. INSERT Statement:
It is Used to add new records to a table by specifying the values for each column or
using a subquery.
Example:
INSERT INTO employees (first_name, last_name, department, salary) VALUES ('John',
'Doe', 'Marketing', 50000);

3. UPDATE Statement:
It Allows you to modify existing records in a table by specifying the new values for one
or more columns based on a specified condition.
Example:
UPDATE employees SET salary = 55000 WHERE employee_id = 101;

4. DELETE Statement:
It is Used to remove records from a table based on a specified condition.
Example:
DELETE FROM employees WHERE employee_id = 102;

5. WHERE Clause:
It enables you to filter data based on specific conditions when querying, updating, or
deleting records.
Example:

3
SELECT * FROM employees WHERE salary > 50000;
6. JOIN Operations:
SQL supports various types of joins (e.g., INNER JOIN, LEFT JOIN, RIGHT JOIN) to
combine rows from multiple tables based on related columns.
Example:
SELECT employees.employee_id, employees.first_name,
departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;

7. GROUP BY Clause:
It is Used to group rows that have the same values in specified columns and apply
aggregate functions (e.g., COUNT, SUM, AVG) to the grouped data.
Example:
SELECT department, AVG(salary) as avg_salary FROM employees GROUP BY
department;

8. ORDER BY Clause:
It Allows you to sort the result set based on one or more columns, either in ascending
or descending order.
Example:
SELECT * FROM employees ORDER BY last_name, first_name;

Discuss about the Privileges in detail.


 In MySQL, privileges refer to the rights or permissions granted to a MySQL user
account, specifying what actions the user is allowed to perform on various
database objects, such as databases, tables, or columns.

 The privilege system in MySQL is designed to control access and operations at


different levels, providing a flexible and secure way to manage user permissions.

4
 The GRANT statement is used to assign specific privileges to a user account,
specifying the level (global, database, table, etc.) and the actions allowed.

Types of Privileges:
i. Global Privileges
ii. Database-Level Privileges
iii. Common Privileges:
iv. Granting and Revoking Privileges

i. Global Privileges:
Apply to the entire MySQL server and include administrative tasks such as CREATE
USER or SHUTDOWN.

ii. Database-Level Privileges:


Apply to specific databases and include actions like CREATE, ALTER, and DROP.

iii. Table-Level Privileges:


Apply to individual tables within a database and include actions like SELECT, INSERT,
UPDATE, and DELETE.

iv. Column-Level Privileges:


Apply to specific columns within a table, controlling actions like SELECT and UPDATE
for particular columns.

iii. Common Privileges:


SELECT: Allows the user to retrieve data from tables.
INSERT: Permits the user to add new rows to tables.
UPDATE: Enables the user to modify existing data in tables.
DELETE: Allows the user to remove rows from tables.

5
ALL PRIVILEGES: Grants all available privileges for a specified database, table, or the
entire server.

iv. Granting and Revoking Privileges:


The GRANT statement is used to assign specific privileges to a user account, specifying
the level (global, database, table, etc.) and the actions allowed.

Discuss about Security in MySQL.


 Security in MySQL involves implementing measures to protect the confidentiality,
integrity, and availability of data stored in MySQL databases.
 MySQL provides the following features to enhance security in MySQL Database.

1. Authentication
2. Authorization and Privileges
3. Encryption
4. Firewall Rules
5. Audit Logging

1. Authentication:
MySQL supports various authentication methods, including native authentication, LDAP,
and PAM (Pluggable Authentication Modules).
Strong authentication mechanisms help ensure that only authorized users can ac cess
the database.

2. Authorization and Privileges


The privilege system in MySQL is designed to control access and operations at different
levels, providing a flexible and secure way to manage user permissions.

3. Encryption:
 MySQL supports encryption for data in transit (using SSL/TLS) and at rest (using
file-level or table-level encryption).
 Encrypting sensitive data helps protect it from unauthorized access, especially
during transmission over networks or when stored on disk.

6
4. Firewall Rules
Configuring firewall rules can restrict access to the MySQL server based on IP
addresses or ranges. By controlling network access, administrators can prevent
unauthorized users or malicious entities from connecting to the MySQL server.

5. Audit Logging
 MySQL provides an audit plugin that can be used to log various activities,
including login attempts, executed queries, and administrative actions. Audit logs
are valuable for security analysis, compliance, and identifying potential security
incidents.
 Regular security audits and reviews should be conducted to identify and address
potential vulnerabilities.

Discuss about MySQL Data Types in detail.


MySQL supports a variety of data types, allowing you to define the type of data that can
be stored in each column of a table.

Different Types of Data Types as follows:


i. Numeric Types:
INTEGER or INT:
A whole number without a fractional component.
Example: INT

ii. FLOAT
A floating-point number with a decimal component.
Example: FLOAT(10, 6) (10 total digits, 6 after the decimal point)
iii. DOUBLE:
A double-precision floating-point number.
Example: DOUBLE(15, 8) (15 total digits, 8 after the decimal point)

iv. DECIMAL or NUMERIC:


A fixed-point number.
7
Example: DECIMAL(10, 2) (10 total digits, 2 after the decimal point)

v. String Types:
CHAR: Fixed-length character string.
Example: CHAR(10)

vi. VARCHAR:
Variable-length character string.
Example: VARCHAR(255)
 TEXT: Variable-length text string.
 BINARY: Fixed-length binary string.
 VARBINARY: Variable-length binary string.
 BLOB: Binary large object, for storing large amounts of binary data.

vii. Date and Time Types:


 DATE: Date value in 'YYYY-MM-DD' format.
 TIME: Time value in 'HH:MM:SS' format.
 DATETIME: Date and time value in 'YYYY-MM-DD HH:MM:SS' format.
 TIMESTAMP: Automatic timestamp, updated on record modification.

These are some of the common MySQL data types. It's important to choose the
appropriate data type based on the nature of the data you intend to store, as it affects
storage efficiency and data integrity.

Connecting to MySQL
After you’ve installed and set up your MySQL database, you can begin to write PHP
scripts that interact with it.
The basic command to initiate a MySQL connection is
mysql_connect($hostname, $user, $password);
or
mysql_connect(‘localhost’, ‘root’, ‘password’);

8
Next, you’ll want to choose a database to work on:
mysql_select_db($database);
if you’re using variables,
or
mysql_select_db(‘phpbook’);
if you’re using a literal string.

You must select a database each time you make a connection, which means at least
once per page or every time you change databases. Otherwise, you’ll get a Database
not selected error.

Making MySQL Queries


 A database query from PHP is basically a MySQL command wrapped up in a tiny
PHP function called mysql_query().
 This is where you use the basic SQL workhorses of SELECT, INSERT,
UPDATE, and DELETE.
 The MySQL commands to CREATE or DROP a table can also be used with this
PHP function if you do not wish to make your databases using the MySQL client.
You could write a query in the simplest possible way, as follows:
mysql_query(“SELECT Surname FROM personal_info WHERE ID < 10”);
PHP would dutifully try to execute it. However, there are very good reasons to split up
this and similar commands into two lines with extra variables, like this:
$query = “SELECT Surname FROM personal_info WHERE ID < 10”;
$result = mysql_query($query);

Creating Multiple Connections:


 The function mysql_query takes as arguments the query string (which should not
have a semicolon within the double quotation marks) and optionally a link
identifier.
 Unless you have multiple connections, you don’t need the link identifier. It returns
TRUE (nonzero) integer values if the query was executed successfully even if no
rows were affected.

9
 It returns a FALSE integer if the query was illegal or not properly executed for
some other reason.

If you need to use multiple databases in your script, you can use code like this:
$query = “SELECT Surname FROM personal_info WHERE ID < 10”;
$result = mysql_query($query, $link_1);
$query = “SELECT * FROM orders WHERE date > 20030702”;
$result = mysql_query($query, $link_2);

Fetching Dataset
Fetching data sets in MySQL typically involves executing a SELECT query and then
retrieving the result set.
The fetching functions are as follows:
 mysql_fetch_row: Returns row as an enumerated array
 mysql_fetch_object: Returns row as an object
 mysql_fetch_array: Returns row as an associative array
 mysql_result: Returns one cell of data

The differences among the three main fetching functions is small. The most general one
is mysql_fetch_row, which can be used as follows:
$query = “SELECT ID, LastName, FirstName
FROM users WHERE Status = 1”;
$result = mysql_query($query);

while ($name_row = mysql_fetch_row($result))


{
print(“{$name_row[0]} {$name_row[1]} {$name_row[2]}<BR>\n”);
}

This code will output the specified rows from the database, each line containing one row
or the information associated with a unique ID.

10
Building in Error Checking
We can use die() or Built in Error for message for Error checking.

i. die() Function:
 This section could have been titled “Die, die, die!” because the main error-
checking function is actually called die().
 die() is not a MySQL-specific function — the PHP manual lists it in
“Miscellaneous Functions.”
 It simply terminates the script (or a delimited portion thereof) and returns a string
of your choice.

Example:
mysql_query(“SELECT * FROM mutual_funds
WHERE code = ‘$searchstring’“)
or die(“Please check your query and try again.”);

ii. Built in Error Message:


 Other built-in means of error-checking are error messages. These are particularly
helpful during the development and debugging phase, and they can be easily
commented out in the final edit before going live on a production server.

 As mentioned, MySQL error messages no longer appear by default. If you want


them, you have to ask for them by using the functions mysql_errno()

Example:
if (!mysql_select_db($bad_db))
{
print(mysql_error());
}

11
Creating MySQL Databases
1.Before we can access data in the MySQL database, we need to create the database
using the CREATE DATABASE SQL query and create the Table by using DDL and
update the table with DML queries.

MySQL Database Functions are:


i. mysql_create_db(): Creates a database on the designated host, with name
specified in
ii. arguments
iii. mysql_drop_db(): Deletes the specified database
iv. mysql_query(): Passes table definitions and drops in this function

Example : Using MySQL Database using above MySQL Functions in PHP:


<?php
$linkID = mysql_connect(‘localhost’, ‘root’, ‘password’);
mysql_create_db(‘new_db’, $linkID);
mysql_select_db(‘new_db’);
$query = “CREATE TABLE ename (name VARCHAR2(20), emp_id VARCHAR1(10))“;
$result = mysql_query($query);
$axe = mysql_drop_db(‘new_db’);
?>

To Create the Database using the syntax:


CREATE DATABASE db_name;
CREATE DATABASE students_2024;
students_2024 is the database name.

To Drop Database:
DROP DATABASE db_name;
DROP DATABASE students_2024:

12
Discuss about MySQL Functions
MySQL provides a rich set of functions that can be used for various purposes, including
data manipulation, string manipulation, mathematical operations, date and time
manipulation.

The following are the Four types of Functions in MySQL:

i. Aggregate Functions
ii. String Functions
iii. Mathematical Functions
iv. Date and Time Functions:

1. Aggregate Functions:
Aggregate functions perform a calculation on a set of values and return a single value.
i. COUNT(): Counts the number of rows in a result set.
ii. SUM(): Calculates the sum of values in a numeric column.
iii. AVG(): Computes the average of values in a numeric column.
iv. MIN(): Finds the minimum value in a column.
v. MAX(): Finds the maximum value in a column.

Example:
SELECT COUNT(*) FROM employees;

2. String Functions:
String functions in MySQL are a set of functions designed to manipulate and operate on
character string data. These functions allow you to perform various operations on
strings, such as concatenation, substring extraction, case conversion, and more.
i. CONCAT(): Concatenates two or more strings.
ii. SUBSTRING(): Extracts a substring from a string.
iii. UPPER() / LOWER(): Converts a string to uppercase or lowercase.
iv. LENGTH(): Returns the length of a string.
v. REPLACE(): Replaces occurrences of a substring within a string.

13
Example:
SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM employees;

3. Mathematical Functions:
Mathematical functions allow you to perform calculations, manipulate numbers, and
retrieve numeric results from your database.
i. ROUND(): Rounds a numeric value to a specified number of decimal places.
ii. ABS(): Returns the absolute value of a numeric expression.
iii. CEIL() / FLOOR(): Rounds a numeric value up or down to the nearest integer.

Example:
SELECT ROUND(salary, 2) FROM employees;

Date and Time Functions:


Date and time functions in MySQL allow you to manipulate and operate on date and
time values. These functions can be used to extract information from date and time
columns, perform calculations, format dates.
i. NOW(): Returns the current date and time.
ii. DATE_FORMAT(): Formats a date or time value.
iii. CURTIME() / CURRENT_TIME: Returns the current time.
iv. DATEDIFF(): Calculates the difference between two dates.

Example:
SELECT NOW() AS current_datetime FROM dual;
SELECT CURDATE() AS current_date;
SELECT CURTIME() AS current_time;
SELECT EXTRACT(YEAR FROM hire_date) AS hire_year FROM employees;

14
PHP Functions for MySQL

15

You might also like