Docsity

Networking - UNIXNET COMMANDS, Lecture notes of Network Programming

Toggle sidebar
bg1
For educational purposes only
Mater Dei College
Tubigon, Bohol
1st Semester, A.Y. 2021-2022
IM 2 (INFORMATION MANAGEMENT 2)
Topic 7- Connecting to MYSQL using PDO
Study Guide
CONNECTING TO MYSQL
Prerequisites
Before connecting to a MySQL database server, you need to have:
• A MySQL database server, a database, and an account that has access to the database.
• PDO MySQL driver enabled in the php.ini file
1) Setting MySQL database parameters
Suppose you have a local MySQL database server that has the following information:
• The host is localhost.
• The bookdb database on the local database server.
• The account with the user root and password 'S@cr@t1!' that can access the bookdb database.
In PHP, you can create a config.php file and place the database parameters:
<?php
$host = 'localhost';
$db = 'bookdb';
$user = 'root';
$password = 'S@cr@t1!';
Code language: HTML, XML (xml)
To use the database parameters, you can include the config.php file using the require construct:
<?php
require 'config.php';
Code language: HTML, XML (xml)
2) Enable PDO_MySQL Driver
PDO_MYSQL is a driver that implements the PDO interface. PDO uses the PDO_MYSQL driver to connect
to a MySQL database.
To check if the PDO_MYSQL driver is enabled, you open the php.ini file. The php.ini file is often located
under the php directory. For example, you can find the php.ini file under the C:\xampp\php directory if
you use XAMPP on Windows.
The following shows the extension line in the php.ini file:
;extension=php_pdo_mysql.dll
To enable the extension, you need to uncomment it by removing the semicolon (;) from the beginning of
the line like this:
extension=php_pdo_mysql.dll
After that, you need to restart the web server for the change to take effect.
MySQL data source name
PDO uses a data source name (DSN) that contains the following information:
• The database server host
• The database name
• The user
• The password
• and other parameters such as character sets, etc.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e

Partial preview of the text

Download Networking - UNIXNET COMMANDS and more Lecture notes Network Programming in PDF only on Docsity!

For educational purposes only Mater Dei College Tubigon, Bohol 1st Semester, A.Y. 2021- 2022 IM 2 (INFORMATION MANAGEMENT 2) Topic 7 - Connecting to MYSQL using PDO Study Guide CONNECTING TO MYSQL Prerequisites Before connecting to a MySQL database server, you need to have:

  • A MySQL database server, a database, and an account that has access to the database.
  • PDO MySQL driver enabled in the php.ini file 1 ) Setting MySQL database parameters Suppose you have a local MySQL database server that has the following information:
  • The host is localhost.
  • The bookdb database on the local database server.
  • The account with the user root and password 'S@cr@t1!' that can access the bookdb database. In PHP, you can create a config.php file and place the database parameters:
For educational purposes only PDO uses this information to make a connection to the database server. To connect to the MySQL database server, you use the following data source name format: "mysql:host=host_name;dbname=db_name;charset=UTF8" Code language: JSON / JSON with Comments (json) For example: $dsn = "mysql:host=localhost;dbname=bookdb;charset=UTF8"; Code language: PHP (php) Note that the charset UTF-8 sets the character set of the database connection to UTF-8. Connecting to MySQL The following index.php script illustrates how to connect to the bookdb database on the MySQL database server with the root account:

getMessage(); } Code language: HTML, XML (xml) How it works.
  • First, create a new PDO object with the data source name, user, and password. The PDO object is an instance of the PDO class.
  • Second, show the success message if the connection is established successfully or an error message if an error occurs. If you have everything set up correctly, you will see the following message: Connected to the bookdb database successfully! Error handling strategies PDO supports three different error handling strategies:
  • PDO::ERROR_SILENT – PDO sets an error code for inspecting using the PDO::errorCode() and PDO::errorInfo() methods. The PDO::ERROR_SILENT is the default mode.
  • PDO::ERRMODE_WARNING – Besides setting the error code, PDO will issue an E_WARNING message.
  • PDO::ERRMODE_EXCEPTION – Besides setting the error code, PDO will raise a PDOException. To set the error handling strategy, you can pass an associative array to the PDO constructor like this: $pdo = new PDO($dsn, $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); Code language: PHP (php) Or you can use the setAttribute() method of the PDO instance: $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Code language: PHP (php) Troubleshooting There are some common issues when you connect to a MySQL database: If the MySQL driver is not enabled in the php.ini file, you will get the error message: could not find driver Code language: plaintext (plaintext)

Mater Dei College Tubigon, Bohol 1st Semester, A.Y. 2021- 2022 IM 2 (INFORMATION MANAGEMENT 2) Topic 7 - Types of Databases Study Guide A DBMS can support many different types of databases. Databases can be classified according to the number of users, the database location(s), and the expected type and the extent of use.

  1. The Number of users determines whether the database is classified as single-user or multiuser. a. Single-user database supports only one user at a time b. Multiuser database supports multiple users at the same time i. Workgroup supports relatively small number of users usually fewer than 50. ii. Enterprise supports many users more than 50 or usually hundreds across many departments. 2. Database location might also be used to classify the database a. Centralized database is a database that supports data located at a single site. b. Distributed database is a database that supports data distributed across several different sites 3. The Extent of use (data usage) of the database is the most popular way of classifying databases today of how they will be used. a. Operational database is a database that is designed primarily to support a company’s day-to- day operations. Sometimes referred to as a transactional or production database. For example, transactions such as product or service sales, payments, and supply purchases reflect critical day- to-day operation. b. Data warehouse focuses primarily on storing data used to generate information required to make tactical or strategic decisions. Such decisions typically require extensive “data massaging” (data manipulation) to extract information to formulate pricing decisions, sales forecasts, market positioning, and others. To make it easier retrieve such data, the data warehouse structure is quite different from that of a transaction-oriented database. **DIFFERENT DB TECHNOLOGIES
  2. Web database** exists on a Web server that can be accessed by website scripts. It is a wide term for managing data online and gives you the ability to build your own database/ data storage without a technical person or database guru. 2. Mobile database resides on a mobile device such as laptops and cellular phones. Recent advances in portable and wireless technology led to mobile computing , a new dimension in data communication and processing. Portable computing devices coupled with wireless communications allow clients to access data from virtually anywhere and at any time. 3. Multimedia database stores images, audio streams, and video clips. In the years ahead multimedia information systems are expected to dominate our daily lives. Our houses will be wired for bandwidth to handle interactive multimedia applications. Our high-definition TV/computer workstations will have access to a large number of databases, including digital libraries, image and video databases that will distribute vast amounts of multisource multimedia content. DBMSs have been constantly adding to the types of data they support. Today the following types of multimedia data are available in current systems. ⚫ Text : May be formatted or unformatted. For ease of parsing structured documents, standards like SGML and variations such as HTML are being used. ⚫ Graphics : Examples include drawings and illustrations that are encoded using some descriptive standards (e.g. CGM, PICT, postscript). ⚫ Images : Includes drawings, photographs, and so forth, encoded in standard formats such as bitmap, JPEG, and MPEG. Compression is built into JPEG and MPEG. These images are not subdivided into components. Hence querying them by content (e.g., find all images containing circles) is nontrivial. ⚫ Animations : Temporal sequences of image or graphic data. ⚫ Video : A set of temporally sequenced photographic data for presentation at specified rates– for example, 30 frames per second.

⚫ Structured audio : A sequence of audio components comprising note, tone, duration, and so forth. ⚫ Audio : Sample data generated from aural recordings in a string of bits in digitized form. Analog recordings are typically converted into digital form before storage. ⚫ Composite or mixed multimedia data : A combination of multimedia data types such as audio and video which may be physically mixed to yield a new storage format or logically mixed while retaining original types and formats. Composite data also contains additional control information describing how the information should be rendered. ⚫ Presentation applications : A large amount of applications involve delivery of multimedia data subject to temporal constraints; simple multimedia viewing of video data, for example, requires a system to simulate VCR-like functionality. Complex and interactive multimedia presentations involve orchestration directions to control the retrieval order of components in a series or in parallel. Interactive environments must support capabilities such as real-time editing analysis or annotating of video and audio data. ⚫ Collaborative work using multimedia information : This is a new category of applications in which engineers may execute a complex design task by merging drawings, fitting subjects to design constraints, and generating new documentation, change notifications, and so forth. Intelligent healthcare networks as well as telemedicine will involve doctors collaborating among themselves, analyzing multimedia patient data and information in real time as it is generated. Multimedia Database Applications Large-scale applications of multimedia databases can be expected encompasses a large number of disciplines and enhance existing capabilities. ⚫ Documents and records management ⚫ Knowledge dissemination ⚫ Education and training ⚫ Marketing, advertising, retailing, entertainment, and travel ⚫ Real-time control and monitoring

4. Geographic Information System Geographic information systems (GIS) are used to collect, model, and analyze information describing physical properties of the geographical world and designed to captures, stores, manipulates, analyze, manage, and present all types of geographical data. The scope of GIS broadly encompasses two types of data:

  1. spatial data, originating from maps, digital images, administrative and political boundaries, roads, transportation networks, physical data, such as rivers, soil characteristics, climatic regions, land elevations, and
  2. nonspatial data, such as socio-economic data (like census counts), economic data, and sales or marketing information. GIS is a rapidly developing domain that offers highly innovative approaches to meet some challenging technical demands. GIS Applications It is possible to divide GISs into three categories: ⚫ cartographic applications, ⚫ digital terrain modeling applications, and ⚫ geographic objects applications 5. Genome Data Management

8. OLAP enable users o interactively analyze multidimensional data from multiple perspective. It is a tool or approach to answer multidimensional analytical queries. Ex. App. - business reporting for sales - marketing and management report - budget forecasting 9. Real-time database is a processing system designed to handle workloads whose state is very dynamic or in a rapid change. It is a processing which means that a transaction is processed fast enough for the result to come back and be acted on right away. ex. Stock market 10. Data warehouse ( DW or DWH ) is a database used for reporting and analysis. The data stored in the warehouse are uploaded from the operational systems (such as marketing, sales etc.) may pass through an operational data store for additional operations before they are used in the DW for reporting. 11. Data Mining also known as data or knowledge discovery. It is the computer-assisted process of digging through and analyzing enormous sets of data and then extracting the meaning of the data. - Data mining tools predict behaviors and future trends, allowing businesses to make proactive, knowledge-driven decisions. Data mining tools can answer business questions that traditionally were too time consuming to resolve. - For businesses, data mining is used to discover patterns and relationships in the data in order to help make better business decisions. Data mining can help spot sales trends, develop smarter marketing campaigns, and accurately predict customer loyalty. Specific uses of data mining include: - Market segmentation - Identify the common characteristics of customers who buy the same products from your company. - Trend analysis - Reveal the difference between a typical customer this month and last.

Mater Dei College

Tubigon, Bohol

1st Semester, A.Y. 202 1 - 2022

IM 2 (INFORMATION MANAGEMENT 2 )

Topic 6 - Retrieving Data from Multiple Tables

Laboratory Hands-on Activity

  • Use the hotel database that you created for this activity
  • Create the queries based on the given requirements
  • Let the query run into the terminal and capture the image of the

output

  • Put the image into a word processing software and convert it into a

pdf file.

  • Submit your work into our subject portal

Hotel (hotelNo, hotelName, city)

Room (roomNo, hotelNo, type, price)

Booking (hotelNo, guestNo, dateFrom, dateTo, roomNo)

Guest (guestNo, guestName, guestAddress)

1. List the room number, type, and price from a specific hotel (Choose

one hotel available into your database).

2. List the name of the guest, address, room number that he/she booked,

room type, room price and the hotel name that the room belong.

3. List all the information of hotels and the rooms information available for

each hotel.

4. List the details of the bookings for each of the customer and also

display the customer details.

Ex. Select Cust_id as “customer id”, Lname as Lastname, address from customer; Eliminating duplicate rows with DISTINCT Columns often contain duplicate values, and it’s common to want a result tjat list each duplicate only once. Ex. Select DISTINCT address from customer; Sorting rows with ORDER BY Rows in query result are unordered. Use the order by clause to sort rows by a specified columns or columns in ascending (asc) or descending (desc). Ex. Select * from customer order by age asc; Filtering rows with WHERE Use the WHERE clause to filter unwanted rows from the result. WHERE clause- specifies a search condition that comprises one or more conditions that need to be satisfied by the rows of a table. A condition , or predicate, is a logical expression that evaluates to true, false or unknown. The unknown result arises from nulls. Rows for which the condition is true are included in the result; rows for which the condition is false or unknown are excluded. SQL provides operators that express different types of conditions. Operators are symbols or keywords that specify actions to be performed in values or other elements. You can combine and negate conditions by using the logical operators AND, OR,NOT Types of Condition and Their corresponding operators Comparison – with the following operators =, <>, <, <=, >, >= Pattern Matching – LIKE Range Filtering – BETWEEN List Filtering – IN Null Test – IS NULL Comparison EXAMPLE

  1. select * from employee_tbl where age >= 35;
  2. Select name, department From employee_tbl Where age>= 35; Pattern Matching Use LIKE to retrieve rows based on partial information. Like is useful if you don’t know an exact value. Like works with only characters strings, it uses pattern that values are matched against. A pattern is a quoted string that contains the literals characters to match and any combination of wildcards. Wildcards are special characters used to match parts of a value. You can negate like condition with not like, can combine like conditions and other conditions with AND and OR. Wildcards operators % a percent sign matches any string of zero or more characters _ an underscore matches any one character. Ex. Select fname, lname from customer where fname like ‘%Ke’; Select fname, lname from customer where fname not like ‘Ke%’; Examples of % and _ patterns PATTERN MATCHES ‘a%’ - matches a string value of length >= 1 that begins with a , including single letter A. ‘%s’ - matches a string value of length >= 1 that ends with s, including single letter s. ‘%in% - matches a string value of length >= 1 that contains in anywhere. ‘____’ - matches any four characters string value. ‘Qua__’ - matches any five characters string value that begins with Qua. ‘re’ - matches any four characters string value that has re as its second and third characters.

‘re%’ - matches a string values of length >= 3 that begins with any character and has re as its second and third characters. ‘%re’ - matches a string value of length >=3 that has re as the second and third characters from its end, and ends with any character. Range Filtering with BETWEEN Use between to determine whether a given value falls within a specified range. Important characteristics of between conditions are: ➢ Between works with character strings, numbers, and datetimes. ➢ The between range contains a low value and a high value, separated by AND. The low value must be less than of equal to the high value. ➢ Between is a convenient shorthand clause, you can replicate its behavior by using AND; o Where test_column BETWEEN low_value and high_value Is equivalent to Where (test_column>= low_value) and (test_column<= high_value) ➢ Between specifies an inclusive range, in which the high value and low value are included in the result/search. To specify an exclusisve range, which excludes endpoints, use > and < comparisons operator instead of between operator. ➢ You can negate a between conditions with not between operator. ➢ You can combine BETWEEN conditions and other conditions with AND and OR. List Filtering with IN Use IN to determine whether a given value matches any value in a specified list. ➢ IN works with character strings, numbers, and datetimes ➢ The IN list is a parenthesized listing of one or more comma-separated values. ➢ IN is a convenient, shorthand clause. You can replicate its behavior by using OR: Where test_columnIN(value1, value2, value3) Is equivalent to Where (test_column = value1) OR (test_column = value2) OR (test_column = value3) ➢ You can negate an IN condition with NOT IN. ➢ You can combine IN conditions and other conditions with AND and OR. Testing for Nulls with IS NULL Null represent missing or unknown values. This situation causes a problem: LIKE, BETWEEN, IN, and other WHERE clause options can’t find nulls because unknown values don’t satisfy specific conditions. Nulls match no value. IS NULL determines whether a given value is null. ➢ Works for columns of any data type ➢ You can negate an IS NULL condition with IS NOT NULL ➢ You can combine IS NULL conditions and other conditions with AND and OR. EX. SELECT columns from table where test_column IS [NOT] NULL; OPERATORS AND FUNCTIONS Operators and functions permit you to calculate results derived from column data, system-determined values, and constant expressions. Where in you can perform the following:

  • Arithmetic operators like cut everyone’s salary by 10 percent
  • String operators like concatenate personal information into a mailing address
  • Datetime operations – find out what time your DBMS thinks it is. Operator is a symbol or keyword indicating an operation that acts on one or more elements. The elements, called operands, are SQL expressions which is any legal combination of symbols and tokens that evaluates to a single value (or null). For example price * 2, * is the operator, and price and 2 is the operands. Function is a built-in, named routine that performs a specialized task. Most functions take parenthesized arguments, which are values you pass to the function then uses to perform its task. Arguments can be column names, constants, nested functions, or more complex expressions. For example UPPER (last_name). Upper is the function name, last_name is the argument.

➢ CASE has two formats: simple and searched. The simple case expression compares an expression to a set of simple expressions to determine the result. The searched case expression evaluates a set of logical (Boolean) expressions to determine the result ➢ CASE returns an optional ELSE result as the default value if no test condition is true ➢ Ex. Simple case expression Select title_id, type, price, Case type When ‘history’ then price * 1. When ‘psychology’ then price * 1. Else price End as “new price” from book; Ex: Searched CASE expression Select title_id, case when sales is null then “unknown’ When sales <= 1000 then “sale is low” When sales <= 50000 then “sale is high” Else ‘sale is high’ end as ‘sales category’ From book Order by sales asc; SUMMARIZING AND GROUPING DATA The preceding chapter described scalar functions, which operate on individual row values. This topic introduces SQL’s aggregate functions, or set functions, which operate on a group of values to produce a single, summarizing value. You apply an aggregate to a set of rows, which may be: ➢ All the rows in a table ➢ Only those rows specified by a where clause ➢ those rows created by a group by clause No matter how many rows the set contains, an aggregate function returns a single statistic: a sum, minimum, or average. USING AGGREGATE FUNCTIONS Function Returns MIN(expr) Minimum value in expr MAX(expr) Maximum value in expr SUM(expr) Sum of the values in expr AVG(expr) Average(arithmetic mean) of the values in expr COUNT(expr) The number of non-null values in expr COUNT() The number of rows in a table or set The characteristics of the aggregate functions are: ➢ Expression often is a column name. ➢ SUM () and AVG() work with only numeric data type. MIN() AND MAX() work with characters, numeric, and date time data types. COUNT(expr) and COUNT() work with all data types. ➢ All aggregate functions except COUNT() ignore nulls ➢ Often use with the group by clause ➢ Use WHERE clause to restrict the rows used in aggregate calculations ➢ Default column headings for aggregate vary by DBMS use: use column alias to name the result column Ex. Select sum(sales), min(price), max(price) from item group by description; Select count() as ‘total number of items’ from item; Select count(description) as ‘total’ from item group by description order by description asc;

Database

Normalization

A Quick Review

Database Anomalies ● Insert Anomalies ● Update Anomalies ● Delete Anomalies

Insert Anomaly delivery _id item_name date branch 11234 Item 1 8/24/2019 Cebu 11235 Item 5 8/30/2019 Bohol 11236 Item 3 9/5/2019 Cebu 11237 Item 9 9/8/2019 Leyte Considering this table, we cannot add a new branch until a delivery for the new branch will be recorded.

Delete Anomaly If we are to close one branch and delete that branch from our database, all the deliveries to that branch will also be deleted. delivery _id item_name date branch 11234 Item 1 8/24/2019 Cebu 11235 Item 5 8/30/2019 Bohol 11236 Item 3 9/5/2019 Cebu 11237 Item 9 9/8/2019 Leyte

Source Table (not normalized)