UNIT 4 Open Source Operating System (SHELL PROGRAMMING)
UNIT 4 Open Source Operating System (SHELL PROGRAMMING)
Unit 5
Open Source Database and Application
Content of Unit 5 :
✓ MySQL: Configuring MySQL Server
✓ working with MySQL Databases
✓ MySQL Tables
✓ SQL Commands INSERT, SELECT, UPDATE, REPLACE, DELETE. Date and Time
functions in MySQL
✓ PHP MySQL Application Development: Connecting to MySQL with PHP
✓ Inserting data with PHP, Retrieving data with PHP.
➢ While MySQL is a specific database system accessible for free and supports various
programming languages.
What is MySQL?
➢ MySQL is an open-source relational database management system (RDBMS) developed by
Oracle Corporation.
➢ It uses Structured Query Language (SQL) for database management and is known for its
reliability, speed and ease of use.
➢ MySQL supports large databases, up to 50 million rows or more in a table.
➢ It is known for its reliability, ease of use, and performance.
➢ MySQL is widely used for various applications, from small websites to large-scale enterprise
systems.
Key Features of MySQL
1) Open Source: Free to use, with a strong community and enterprise versions
available.
2) Platform Independent: Runs on various platforms such as Windows, Linux, and
macOS.
3) High Performance: Capable of handling large databases efficiently.
4) Scalability: Can be scaled from small projects to enterprise-level applications.
5) Security: Provides strong data protection with user-level security features.
6) Replication and Clustering: Supports master-slave replication for redundancy and
scalability.
Basic MySQL Terminologies
✓ Database: A structured collection of data.
✓ Table: A collection of related data entries consisting of rows and columns.
✓ Row/Record: A single, structured data item in a table.
✓ Column/Field: A vertical entity in a table that contains specific information about all
records.
✓ Primary Key: A unique identifier for records in a table.
✓ Foreign Key: A column used to link two tables.
Introduction to MySQL Server Configuration
➢ Configuring MySQL Server properly ensures optimal performance, security, and reliability.
➢ This process involves installing the server, modifying its configuration files, setting up user
authentication, and fine-tuning settings based on specific use cases.
Installation of MySQL Server
1. For Windows:
• Download MySQL Installer: Go to the MySQL official website
(https://dev.mysql.com/downloads/installer/ ) and download the MySQL Installer.
• Run the Installer: Double-click the installer file and choose the setup type (e.g.,
Developer Default or Custom).
• Install MySQL Server: Follow the prompts to install MySQL Server, along with
optional components like Workbench.
2. For Linux (Ubuntu/Debian)
a) Update the Package List :
MySQL Tables
Introduction to Tables in MySQL
➢ A table in MySQL is a collection of related data, organized in rows and columns.
➢ Tables are used to store data in a structured format, facilitating easy data manipulation and
retrieval.
Understanding Table Structure
✓ Columns: Represent the attributes or fields of the data (e.g., id, name, email).
1) INSERT Command
✓ INSERT statement in the SQL is used to add the new records or rows of data into the
table.
✓ It allows you to specify the table name, columns where the data will be inserted and the
corresponding values to be inserted into the columns.
✓ Syntax for INSERT Statement
Explanation:
✓ table_name is the name of the table, which we want to insert the data.
✓ (column1, column2, ....) are optional lists of the columns in table. If specified, you
need to be provide the values for those columns in the same order.
✓ VALUES (value1, value2, ...) are values to be inserted into specified columns. These
values must match the data types of the provided columns.
Example: Adding Data to the students Table
✓ Let' insert some data into the students table.
Output
2) UPDATE Statement
✓ UPDATE statement in the SQL is used to the modify the existing records in table.
✓ It is allowed us to specify the table name, columns to updated new values for these
columns and an optional conditional to the filter which rows are to be updated.
Syntax for UPDATE Statement
Explanation:
✓ table_name is the name of the table, which we want to update.
✓ SET column1 = value1, column2 = value2, ... are specified the columns to the updated
with their new values.
✓ WHERE condition is specify which rows are to be update. if we not use where
condition all rows in the table will be update.
Examples on UPDATE Statement
• Example: Let's update the last name of the students as Anderson whose student_id is 3.
Output
3) DELETE Statement
✓ DELETE statement in the SQL is used to remove the one or more records from the
table.
✓ It is allowed you to the specify the table name and optional condition to the filter
which rows are to be deleted.
Syntax for DELETE Statement
• table_name is the name of the table, which we want to delete the rows of the table.
• WHERE condition is specify which rows are to be delete. if we not use where
condition all rows in the table will be delete.
✓ Examples on DELETE Statement
Output
4) SELECT Statement
✓ SELECT statement in the SQL is used to the retrieve the data from one or more
tables.
✓ It is allowed you to the specify the columns you want to be retrieve, table from the
which you want to be retrieve the data and optional condition to filter rows retrieved.
Syntax for SELECT Statement
Explanation:
✓ column1, column2, ... are the columns you want to retrieve the data.
✓ table_name is the name of the table, which we want to retrieve the data of the
table.
✓ WHERE condition is specify which rows are to be retrieve. if we not use
where condition all rows in the table will be retrieve.
Example on SELECT statements
Explanation:
✓ SELECT student_id and first_name specified that the columns you want to be
retrieve the data from the students table.
✓ FROM students specified that the name of the table from the which want to be
retrieve the data.
Output
5) REPLACE
✓ Replaces an existing record or inserts a new one if the record does not exist. Primarily
used when you need to insert data but update it if it already exists.
Syntax:
Example
REPLACE deletes the existing row before inserting the new one if a duplicate key is
found, which can trigger DELETE and INSERT operations internally.
Introduction to Functions
✓ In MySQL, functions play a crucial role in performing various operations on data, such
as calculations, string manipulations, and date handling.
✓ These built-in functions simplify complex queries and data transformations, making it
easier to manage and analyze data within a database.
Functions in MySQL
✓ In MySQL, functions are a fundamental part of the SQL language, enabling us to
perform calculations, manipulate data and retrieve information.
✓ The functions in MySQL can edit rows and tables, alter strings, and help us to manage
organized and easy-to-navigate databases.
✓ A function is a special type of predefined command set that performs some operation
and returns a value. Functions operate on zero, one, two, or more values that are
provided to them.
✓ The values that are provided to functions are called parameters or arguments.
✓ The MySQL functions have been categorized into various categories, such as String
functions, Mathematical functions, Date and Time functions, etc.
• String Functions
• Numeric Functions
• Date and Time Functions
Introduction to Date and Time Functions
✓ MySQL provides a rich set of built-in functions to work with date and time data types.
✓ These functions help in performing operations such as extracting parts of dates, formatting
dates, calculating time differences, and modifying date values.
Commonly Used MySQL Date and Time Data Types
• DATE: Stores dates in the format YYYY-MM-DD.
• TIME: Stores time in the format HH:MM:SS.
• DATETIME: Stores both date and time in the format YYYY-MM-DD HH:MM:SS.
• TIMESTAMP: Stores date and time values, often used for recording the time of data
modifications.
• YEAR: Stores year values in YYYY format.
Functions Description
DATE() MySQL DATE() takes the date part out from a datetime
expression.
DAY() MySQL DAY() returns the day of the month for a specified date.
DAY OF MONTH() MySQL DAYOFMONTH() returns the day of the month for a
given date.
DAY OF WEEK() MySQL DAYOFWEEK() returns the week day number (1 for
Sunday,2 for Monday …… 7 for Saturday ) for a date specified
as an argument.
DAY OF YEAR() MySQL DAYOFYEAR() returns day of the year for a date. The
return value is within the range of 1 to 366.
LOCALTIME() MySQL LOCALTIME returns the value of current date and time
in ‘YYYY-MM-DD HH:MM:SS’ format or
YYYYMMDDHHMMSS.uuuuuu format depending on the
context (numeric or string) of the function.
MONTH() MySQL MONTH() returns the month for the date within a range
of 1 to 12 ( January to December).
NOW() MySQL NOW() returns the value of current date and time in
‘YYYY-MM-DD HH:MM:SS’ format or
YYYYMMDDHHMMSS.uuuuuu format depending on the
context (numeric or string) of the function.
QUARTER() MySQL QUARTER() returns the quarter of the year for a date.
WEEK() MySQL WEEK() returns the week number for a given date.
WEEKDAY() MySQL WEEKDAY() returns the index of the day in a week for
a given date (0 for Monday, 1 for Tuesday and ......6 for Sunday).
// Create connection
$conn = mysqli_connect($server, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
Open Source Technology (OST) TY (E&TC) Page 21
Shree Siddheshwar Women’s College of Engineering, Solapur
}
echo "Connected successfully";
?>
Here point to be noted is
▪ mysqli_connect() establishes a connection to MySQL.
• die() terminates the script if the connection fails.
• mysqli_connect_error() provides error details.
b) Object-Oriented Method
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";
// Create connection
$conn = new mysqli($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Point to be remember is
try {
$conn = new PDO("mysql:host=$server;dbname=$database",
$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
Point to be remember is
▪ new PDO(...)------- creates a new database connection.
• setAttribute() ---------is used to enable error handling.
• The try-catch block handles exceptions -------(PDOException).
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";
// Create connection
$conn = mysqli_connect($server, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (mysqli_query($conn, $sql)) {
echo "New record inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Close connection
mysqli_close($conn);
?>
2) Object-Oriented Method
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";
// Create connection
$conn = new mysqli($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Close connection
$conn->close();
?>
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";
// Create connection
$conn = new mysqli($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare statement
$stmt = $conn->prepare("INSERT INTO users (name, email, age) VALUES (?,
?, ?)");
$stmt->bind_param("ssi", $name, $email, $age);
$age = 28;
$stmt->execute();
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";
try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (name, email, age) VALUES ('Jane Doe',
'jane@example.com', 22)";
$conn->exec($sql);
// Close connection
$conn = null;
?>
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";
try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
// Insert values
$name = "Sophia Brown";
$email = "sophia@example.com";
$age = 26;
$stmt->execute();
// Close connection
$conn = null;
?>
Here the meaning of different terms are ,
• prepare() --------------prepares the SQL statement.
• bindParam()----------- binds values safely.
• execute() ---------------runs the statement.
$username = "root";
$password = "";
$database = "test_db";
// Create connection
$conn = mysqli_connect($server, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Close connection
mysqli_close($conn);
?>
Here meaning of different terms are as below
• mysqli_query($conn, $sql) ------executes the SELECT query.
b) Object-Oriented Method
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";
// Create connection
$conn = new mysqli($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Close connection
$conn->close();
?>
Here meaning of different terms are as below
• $conn->query($sql) executes the SELECT query.
• $result->num_rows checks if records exist.
• $result->fetch_assoc() fetches each row as an associative array.
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";
// Create connection
$conn = new mysqli($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Prepare statement
$stmt = $conn->prepare("SELECT id, name, email, age FROM users WHERE
age > ?");
$stmt->bind_param("i", $age);
// Fetch values
while ($stmt->fetch()) {
echo "ID: $id - Name: $name - Email: $email - Age: $age <br>";
}
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";
try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
// Close connection
$conn = null;
?>
b) Using Prepared Statements in PDO
<?php
$server = "localhost";
$username = "root";
$password = "";
$database = "test_db";
try {
$conn = new PDO("mysql:host=$server;dbname=$database", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
// Prepare statement
$stmt = $conn->prepare("SELECT id, name, email, age FROM users
WHERE age > :age");
$stmt->bindParam(':age', $age);
// Fetch results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "ID: " . $row["id"] . " - Name: " . $row["name"] .
" - Email: " . $row["email"] . " - Age: " . $row["age"] . "<br>";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Close connection
$conn = null;
?>