Presentation is loading. Please wait.

Presentation is loading. Please wait.

Mysql Mohammed M. Hassoun 2012. Introducing Databases and SQL In the Internet age, information is no longer represented in filing cabinets; instead, it’s.

Similar presentations


Presentation on theme: "Mysql Mohammed M. Hassoun 2012. Introducing Databases and SQL In the Internet age, information is no longer represented in filing cabinets; instead, it’s."— Presentation transcript:

1 Mysql Mohammed M. Hassoun 2012

2 Introducing Databases and SQL In the Internet age, information is no longer represented in filing cabinets; instead, it’s stored as digital ones and zeros in electronic databases, which are data storage “containers” that impose a certain structure on information. Not only do these electronic databases take up less physical space than their wood-and- metal counterparts, but they also come packed with tools to help users quickly filter and retrieve information using different criteria. In particular, most electronic databases today are relational databases, which allow users to define relationships between different database tables for more effective search and analysis. There are a large number of database management systems currently available, some commercial and some free. You’ve probably already heard of some of them: Oracle, Microsoft Access, MySQL, and PostgreSQL. These database systems are powerful, feature-rich software applications, capable of organizing and searching millions of records at very high speeds; as such, they’re widely used by businesses and government offices, often for mission-critical purposes.

3 Understanding Databases, Records, and Primary Keys Every database is composed of one or more tables. These tables, which structure data into rows and columns, impose organization on the data. Figure 7-1 illustrates a typical table. This table contains sales figures for various locations, with each row, or record, holding information for a different location and year. Each record is itself subdivided into columns, or fields, with each field holding a different fragment of information. This tabular structure makes it easy to search the table for records matching particular criteria: for example, all locations with sales greater than $10,000, or sales for all locations in the year 2008. The records in a table are not arranged in any particular order—they can be sorted alphabetically, by year, by sales total, by location, or by any other criteria you choose to specify. To make it easy to identify a specific record, therefore, it becomes necessary

4 to add a unique identifying attribute to each record, such as a serial number or sequence code. In the preceding example, each record is identified by a unique “record ID” field; this field is referred to as the primary key for that table. Understanding Relationships and Foreign Keys You already know that a single database can hold multiple tables. In a relational database system, these tables can be linked to each other by one or more common fields, called foreign keys. These foreign keys make it possible to create one-to-one or one-to-many relationships between different tables, and combine data from multiple tables to create more comprehensive result sets. To illustrate, consider Figure 7-2, which shows three linked tables.

5 Table relationships

6 Figure 7-2 shows three tables, containing information on authors (Table A), genres (Table G), and books (Table B) respectively. Tables G and B are fairly straightforward: they contain a list of genre and author names respectively, with each record identified by a unique primary key. Table B is a little more complex: each book in the table is linked to a specific genre by means of the genre’s primary key (from Table G) and to a specific author via the author’s primary key (from Table A). By following these keys to their respective source tables, it’s easy to identify the author and genre for a specific book. For example, it can be seen that the title “The Shining” is written by “Stephen King” and belongs to the genre “Horror.” Similarly, starting from the other end, it can be seen that the author “Michael Connelly” has written two books, “The Overlook” and “Trunk Music.” Relationships such as the ones seen in Figure 7-2 form the foundations of a relational database system. Linking tables using foreign keys is also more efficient than the alternative: while creating a single everything-but-the-kitchen- sink table to hold all your information might appear convenient at first glance, updating such a table is always a manual (and error-prone) process of finding

7 every occurrence of a particular value and replacing it with a new value. Breaking information up into independent tables and linking these tables with foreign keys ensures that a particular piece of information appears once, and only once, in your database; this eliminates redundancies, simplifies changes (by localizing them to a single location), and makes the database more compact and manageable. The process of streamlining a database by defining and implementing one-to-one and one-to-many relationships between its component tables is known as database normalization, and it’s a key task faced by any database engineer when creating a new database. In the normalization process, the database engineer also identifies cross-relationships and incorrect dependencies between tables, and optimizes data organization so that SQL queries perform at their maximum efficiency. A number of normal forms are available to help you test the extent to which your database is normalized; these normal forms provide useful guidelines to help ensure that your database design is both structurally consistent and efficient.

8

9 WEB SERVER The Web server has what seems to be a fairly straightforward job. It sits there, running on top of your operating system, listening for requests that somebody on the Web might make, responds to those requests, and serves out the appropriate Web pages. In reality, it is a bit more complicated than that, and because of the 24/7 nature of the Web, stability of the Web server is a major issue. There are many Web servers out there, but two Web servers dominate the market. They are Apache and Microsoft’s Internet Information Server (IIS). INTERNET INFORMATION SERVER IIS is deeply tied to the Windows environment and is a key component of Microsoft’s Active Server Pages. If you’ve chosen to go the Microsoft way, you’ll almost certainly end up using IIS. There is a certain amount of integration between the programming language and Web server. At this point, PHP 4 integrates well with IIS. As of this writing, there is some concern about the stability of PHP/IIS under heavy load, but PHP is improving all the time, and by the time you read this there may no longer be a problem.

10 APACHE The Apache Web server is the most popular Web server there is. It, like Linux, PHP, and MySQL, is an open-source project. Not surprisingly, Apache works best in Unix environments, but also runs just fine under Windows. Apache makes use of third-party modules. Because it is open source, anyone with the skill can write code that extends the functionality of Apache. PHP will most often run as an Apache extension, known as an Apache module. Apache is a great Web server. It is extremely quick and amazingly stable. The most frequently stated complaint about Apache is that, like many pieces of Unix software, there are limited graphical tools with which you can manipulate the application. You alter Apache by specifying options on the command line or by altering text files. When you come to Apache for the first time, all this can be a bit opaque. Though Apache works best on Unix systems, there are also versions that run on Windows operating systems. Nobody, not even the Apache developers, recommends that Apache be run on a busy server under Windows. If you have decided to use theWindows platform for serving Web pages, you’re better off using IIS.

11 But there are conditions under which you’ll be glad Apache does run under Windows. You can run Apache, PHP, and MySQL on a Windows 98 machine and then transfer those applications to Linux with practically no changes to the scripts. This is the easiest way to go if you need to develop locally on Windows but to serve off a Unix/Apache server. MIDDLEWARE PHP belongs to a class of languages known as middleware. These languages work closely with the Web server to interpret the requests made from the World Wide Web, process these requests, interact with other programs on the server to fulfill the requests, and then indicate to the Web server exactly what to serve to the client’s browser. The middleware is where you’ll be doing the vast majority of your work. With a little luck, you can have your Web server up and running without a whole lot of effort. And once it is up and running, you won’t need to fool with it a whole lot. But as you are developing your applications, you’ll spend a lot of time writing code that makes your applications work. In addition to PHP, there are several languages that perform similar functions. Some of the more popular choices are ASP,Perl, and ColdFusion.

12 RELATIONAL DATABASES Relational Database Management Systems (RDBMSs) provide a great way to store and access complex information. They have been around for quite a while. In fact, they predate the Web, Linux, and Windows NT, so it should be no surprise that there are many RDBMSs to choose from. All of the major databases make use of the Structured Query Language (SQL). Some of the more popular commercial RDBMSs are Oracle, Sybase, Informix, Microsoft’s SQL Server, and IBM’s db2. In addition to MySQL, there are now two major open-source relational databases. Postgres has been the major alternative to MySQL in the open-source arena for some time. In August 1999, Borland released its Interbase product under an open-source license and allowed free download and use.

13 Understanding SQL Statements Structured Query Language, or SQL, is the standard language used to communicate with a database, add or change records and user privileges, and perform queries. The language, which became an ANSI standard in 1989, is currently used by almost all of today’s commercial RDBMSs. SQL statements fall into one of three categories: ● Data Definition Language (DDL) DDL consists of statements that define the structure and relationships of a database and its tables. Typically, these statements are used to create, delete, and modify databases and tables; specify field names and types; and set indexes. ● Data Manipulation Language (DML) DML statements are related to altering and extracting data from a database. These statements are used to add records to, and delete records from, a database; perform queries; retrieve table records matching one or more user-specified criteria; and join tables together using their common fields. ● Data Control Language (DCL) DCL statements are used to define access levels and security privileges for a database. You would use these statements to grant or deny user privileges; assign roles; change passwords; view permissions; and create rulesets to protect access to data.

14 SQL commands resemble spoken English, which makes the language easy to learn. The syntax is quite intuitive as well: every SQL statement begins with an “action word,” like DELETE, INSERT, ALTER, or DESCRIBE, and ends with a semicolon. Whitespace, tabs, and carriage returns are ignored. Here are a few examples of valid SQL statements: CREATE DATABASE library; SELECT movie FROM movies WHERE rating > 4; DELETE FROM cars WHERE year_of_manufacture < 1980; Table 7-1 lists the syntax for some common SQL statements, with explanations.

15

16

17 Using PHP’s MySQLi Extension As explained previously, PHP allows developers to interact with databases in two ways: by using a customized database-specific extension, or by using the database-neutral PHP Data Objects (PDO) extension. While the PDO extension is more portable, many developers still find it preferable to use the native database extension, especially when the native extension offers better performance or more features than the PDO version. Of the various database engines supported by PHP, the most popular one by far is MySQL. It’s not difficult to understand why: both PHP and MySQL are open-source projects, and by using them together, developers can benefit from huge savings on the licensing costs of commercial alternatives. Historically, too, PHP has offered out-of-the-box support for MySQL since PHP 3, and it only makes sense to leverage off the tremendous amount of thought PHP and MySQL developers have put into making sure that the two packages work together seamlessly and smoothly. In addition to supporting MySQL through the PHP Data Objects extension (discussed in the next section), PHP also includes a custom MySQL extension named MySQL Improved (MySQLi). This extension provides both speed and feature benefits over the PDO version and is a good choice for MySQL-specific development projects. The following sections discuss this extension in greater detail.

18 What is SQL? Structured Query Language Allows database operations Retrieve data Modify data Insert new data Remove data Create and modify tables English type syntax

19 SQL Standards ANSI (American National Standards Institute) SQL is available on many platforms and products Many products implement specific features that are exclusive A product must meet the requirements of ANSI SQL to be considered ANSI SQL compliant Assists programmers by using a common syntax

20 MySQL Available as both a commercial and open-source product Implements the SQL standards Available on many platforms Windows Linux Mac Unix Available from http://www.mysql.com/

21 MySQL - Database A MySQL server is capable of storing many databases A database is generally made of a collection of related tables Each student will get one database for use with the module Every database will be accessible by the student that owns it

22 MySQL - Tables A database is generally made up of related tables Each table will have a name that is unique within the database A table contains records with data StudentIDForenameSurnameLevel AK123900TrevorAdamsM AB340948BobbyRatchet3 AC234887JohanDoex2

23 MySQL - Queries A query performed on a database can result in data or some kind of status A returned list of required records Whether a deletion was successful SELECT StudentID FROM Student Returns a result set StudentID AK123900 AB340948 AC234887

24 MySQL - Queries Queries can come in the following forms: SELECT – extracting data UPDATE – updates data DELETE – deletes data INSERT – inserts data All of these queries can be used on the MySQL database software

25 Data Manipulation Language Consists of the queries that enable the developer to modify the data contained The SQL server processes these queries and returns a result set or a status notification

26 Data Definition Language Defines a set of queries that can be used by the developer to modify the data structure CREATE TABLE ALTER TABLE DROP TABLE We shall not be covering these commands to a great extent Use a management tool to generate these commands automatically

27 PHP and MySQL PHP contains all of the functionality required to interact with MySQL servers Most PHP MySQL functions are prefixed with ‘mysql_’ Use the PHP homepage to search for mysql_ and examine the results MySQL is a client-server based DBMS Database management system One (or few) server(s) caters for many clients Possible for web server and DBMS server to be on the same system

28 Connecting to MySQL with PHP Use the MySQL connect routine mysql_connect($host, $user, $password) $user and $password will be your account details mysql_connect will return a link ID $link = mysql_connect($host, $user, $password) if(!$link) { echo “Unable to connect”; } Always check the link to ensure that the database connection was successful

29 Selecting a database Once a link has been established, select a database mysql_select_db($dbname, [$link]) [] optional – uses last created $link if not given((Specifies the MySQL connection. If not specified, the last connection opened by mysql_connect() or mysql_pconnect() is used)) mysql_select_db returns a Boolean indicating status $result = mysql_select_db(“students”) If(!$result) { echo “No database”; }

30 Using a Connection Once a connection has been established it is possible to execute queries Queries always return a result Success status Result Set Use mysql_query($query_string) to execute $query = “SELECT * FROM Students”; $result = mysql_query($query); $result will contain the desired result set or false if not available

31 Using a Connection Use functions mysql_fetch_row($result) to obtain a row from the result set Returns false when no rows left Example: $query = “SELECT * FROM Students”; $result = mysql_query($query); While($row = mysql_fetch_row($result)){ // $row will be an array index at 0 per column } $row will be equal to false (ending the while loop) when there are no more rows left

32 SQL Query Types SELECT SELECT [fields,…] FROM [table] WHERE [criteria] ORDER BY [field] [asc,desc] [fields] can be * for all or field names separated by commas [table] is the name of the table to use [criteria] is a collection of Boolean expressions that limits returned rows E.g. Forename=‘Trevor’ AND Surname=‘Adams’ [field] denotes which field to sort by

33 SQL Query Types INSERT INTO INSERT INTO [table]([fields,…] VALUES([newvalues,…]) [table] indicates which table to insert into [fields] is a comma separated list of fields that are being used [newvalues] is comma separated list of values that directly correspond to the [fields] E.g. INSERT INTO students(StudentID, Surname, Forename, Level) VALUES(‘AK301390’, Adams, Trevor, M)

34 SQL Query Types UPDATE UPDATE [table] SET [field=value,…] WHERE [criteria] [table] denotes the table to update [field=value,…] is a comma separated list of values for fields [criteria] – a Boolean expression that specifies which records to update If no criteria is given, all records would be updated UPDATE students SET forename=‘Trevor’ WHERE StudentID=‘AK301390’ With no where clause every record in the table would be updated with forename=‘Trevor’

35 SQL Query Types DELETE DELETE FROM [table] WHERE [criteria] Simple and dangerous statements [table] to delete from [criteria] specifying records to delete No criteria deletes all records DELETE FROM students Removes all student records with no warning and no sympathy for mistakes. E.g. DELETE FROM students WHERE StudentID=‘AK301390’ Deletes the student with StudentID of ‘AK301390’

36 Quick Example $query = “INSERT INTO students (StudentID, Forename, Surname, Level) VALUES (‘AK301390’, ‘Trevor’, ‘Addams’, ‘M’) $result = mysql_query($query); if(!$result) { Echo “Insertion failed”; } else { Echo “Record inserted”; }

37 Quick Example $query = “UPDATE students SET Surname=‘Adams’ WHERE StudentID=‘AK301390’ $result = mysql_query($query); If(!$result) { echo “Update failed!”; } else { echo “Update successful!”; }

38 Quick Example $query = “SELECT * FROM student”; $result = mysql_query($query); If(!$result) { echo “No result set”; } else { while ($row = mysql_fetch_row($result)){ foreach($row as $value){ echo “$value, ”; }

39 Create and Insert $sql = CREATE TABLE staff2 (id INT(5) NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20) NOT NULL,dob DATE NOT NULL,update_time TIME NOT NULL,full_description TEXT NOT NULL,average FLOAT(6) NOT NULL) mysql_query("INSERT INTO Persons (id, name, dob, update_time, full_description, average) VALUES (‘’, ‘’Mohammed,’ 2012-03-14’,’ 12:30:00’,’full text’,’91.5’)");

40 Delete: mysql_query("DELETE FROM table_name WHERE attribute_name=‘’check_value'"); while($row = mysql_fetch_array($result)) { echo $row['FirstName']. " ". $row['LastName']; echo " "; } Select: $result = mysql_query("SELECT * FROM table_name"); while($row = mysql_fetch_array($result)) { echo $row[‘attribute_1']. " ". $row[‘attribute_2']; echo " "; }

41


Download ppt "Mysql Mohammed M. Hassoun 2012. Introducing Databases and SQL In the Internet age, information is no longer represented in filing cabinets; instead, it’s."

Similar presentations


Ads by Google