mysql
mysql
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
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.
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;
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.
5
ALL PRIVILEGES: Grants all available privileges for a specified database, table, or the
entire server.
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.
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.
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)
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.
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.
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);
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.”);
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.
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.
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;
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