1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu PHP and MySQL by Example- P12 doc

50 636 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Introduction to PHP and MySQL
Trường học University of Example
Chuyên ngành Computer Science
Thể loại Thesis
Thành phố Example City
Định dạng
Số trang 50
Dung lượng 1,59 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

two-Due to the popularity of relational databases, known as relational database management systems RDBMS, a number of relational databases are used today, among them, Oracle, Sybase, Pos

Trang 1

Figure 12.22 Using a regular expression to find a zip code

Trang 2

12.3 Chapter Summary

Because PHP is tightly integrated with HTML and receives input from forms, regular expressions provide an excellent tool for validating incoming data They are also useful for finding patterns in data coming from files or databases This chapter was designed to teach you how to use regular expressions and the PHP functions that handle them, and to provide short examples to show you how to use the often mysterious regular expression metacharacters

12.3.1 What You Should Know

Now that you have finished this chapter you should be able to answer the following questions:

Trang 3

Chapter 12 Lab

Open the datebook file (found on the CD) to perform the following exercises Each exercise requires a separate open and close of the file

1 • Print all lines containing the pattern Street (case insensitive)

• Print firsts and last names in which the first name starts with letter B

• Print last names that match Ker

• Print phones in the 408 area code

• Print Lori Gortz’s name and address

• Print Ephram’s name in capital letters

• Print lines that do not contain a number 4

• Change William’s name to Siegfried

• Print Tommy Savage’s birthday

• Print lines that end in exactly five digits

• Print the file with the first and last names reversed

2 • Print the city and state where Norma lives

• Give everyone a $250.00 raise

• Calculate Lori’s age (just by year, not month and day)

• Print lines 2 through 6

• Print names and phone numbers of those in the 408 area code

• Print names and salaries in lines 3, 4, and 5

• Print a row of asterisks after line 3

• Change CA to California

• Print the file with a row of asterisks after the last line

• Print the names of the people born in March

• Print all lines that don’t contain Karen

• Print all cities in California and the first names of those people who live there

Trang 4

Chapter 13 Introduction to MySQL

in a big table, but this type is difficult to modify and really best suited for simple applications Another type of database

is one in which the data is organized in a hierarchy or network, much like the structure of a directory tree, a parent–child model, but these kinds of databases are hard for end users to grasp Then in the 1980s relational databases became the “in” thing because the relational model made data manipulation easier and faster for the end user and easier to maintain by the administrator At the core of this model is the concept of a table (also called a relation) in which all data

is stored Each table is made up of records consisting of horizontal rows and vertical columns or fields, like a dimensional array Unlike the hierarchical model, the relational model made it easy for the user to retrieve, insert, update, and delete data without having to understand the underlying structure of the data in the database

two-Due to the popularity of relational databases, known as relational database management systems (RDBMS), a number

of relational databases are used today, among them, Oracle, Sybase, PostgreSQL Informix, DB2, SQL Server, and MySQL

MySQL is the most commonly used database program for developing database-driven Web sites with PHP As we mentioned in Chapter 1, “Introduction,” MySQL is an open source database (it is free[1]) that runs on a majority of operating systems, such as UNIX, Linux, Macintosh, and Windows PHP and MySQL fit very well together They are both reasonably easy to use, fairly scalable and reliable and have a good set of features for small- and medium-sized Web applications Although PHP can be used with any database through its set of ODBC functions, it comes loaded with MySQL specific functions This set of specific functions makes for a tight integration between the PHP language and the MySQL database

[1] Although maintained by MySQL AB, a commercial company, MySQL comes with a GPL (GNU Public License) open source license as well as a commercial license

13.1.1 Client/Server Databases

If your Web site is to be up and available to customers around the world, and you are using a database management system to manage the data, the type of relational database best suited for the task is a client/server database, where the database server runs around the clock to handle client requests as they come in, no matter what the time zone Today MySQL is one of the most popular client/server database systems in the open source community for serving Web pages Figure 13.1 shows the model for a client/server architecture The user requests a page from the browser (e.g., Internet Explorer, Netscape, Firefox), and an HTTP connection is made to the Web server (Apache, ISS) where the request is received and handled If the action is to start up a PHP program, the Web server starts up the PHP interpreter and PHP starts processing the script If the PHP script contains an instruction to connect to a database, in this case MySQL, then once the connection is made and a database selected, the PHP program has access to the database through the MySQL server The MySQL server receives requests, called queries, from the PHP program and sends back information

collected from the database Once PHP gets the information from the MySQL server, it can then format it into nice tables using HTML tags, and send it back to the Web server where it is then relayed to the browser where the whole process started In this example, we have a client/server relationship between the browser and Web server and a

client/server relationship between the PHP program and the MySQL database server

Trang 5

Figure 13.1 The client/server architecture

13.1.2 Talking to the Database

To communicate with the MySQL server, you will need a language, and SQL (Structured Query Language) is the language of choice for most modern multiuser, relational databases SQL provides the syntax and language constructs needed to talk to relational databases in a standardized, cross-platform structured way We discuss how to use the SQL language in the next chapter

Like the English language with a variety of dialects (British, American, Australian, etc.), there are many different versions of the SQL language The version of SQL used by MySQL follows the ANSI (American National Standards Institute) standard, meaning that it must support the major keywords (e.g., SELECT, UPDATE, DELETE,

INSERT,WHERE, etc.) as defined in the standard As you can see by the names of these keywords, SQL is the language that makes it possible to manipulate the data in a database

13.1.3 MySQL Strengths and Weaknesses

From www.mysq.com/why-mysql:

The MySQL ® database has become the world’s most popular open source database because of its consistent fast performance, high reliability, and ease of use It’s used in more than 8 million installations ranging from large

corporations to specialized embedded applications on every continent in the world (Yes, even Antarctica!)

Not only is MySQL the world’s most popular open source database, it’s also become the database of choice for a new generation of applications built on the LAMP stack (Linux, Apache, MySQL, PHP/Perl/Python) MySQL runs on more than 20 platforms including Linux, Windows, OS/X, HP-UX, AIX, Netware, giving you the kind of flexibility that puts you in control

Having said that, like any tool, MySQL is right for certain types of applications and not as suitable for others Let’s look

at what the strengths and weaknesses of MySQL are

Easy to Use

MySQL is a relatively easy to use and administer database system Large database systems with all the bells and whistles often require a knowledgable database administrator (DBA) to set up and administer it MySQL is a database built for programmers with very little overhead in terms of maintenance

Large Community of Developers

What makes MySQL so appealing is the large community of other developers who are building applications around it This makes it a relatively safe choice If you ever need anything, chances are that someone already experienced that issue and has it resolved You can often find the solutions with a little searching online

Open Source License

MySQL is free to use as long as you do not bundle it with your commercial product As an application provider, you can always tell your customers to download and set up their own MySQL database to which your application will connect This is a fairly easy procedure and there is no license cost involved, making it an attractive choice for

application developers

Commercial License

When in fact you want to ship your application with a copy of the MySQL database server built into it, then you must purchase the license from MySQL AB This might not be an attractive feature for true believers in open source and General Public License models, but for most of us, obtaining a license will not be an issue For Web applications, the database is rarely shipped as part of the application Because customers who install server-side applications usually have sufficient skills to perform the tasks of downloading and setting up databases, it is sufficient to document the setup process with your application and leave the rest to them

Scalability

Scalability refers to how well an application can support larger or smaller volumes of data and more or fewer users without degrading performance and costing more MySQL used to be regarded as a small database for small systems Over time, MySQL has become a serious RDBMS with its own way of managing scalability, claiming that it can handle from small (a megabyte) to large (several terabytes) volumes of data with ultimate scalability For example, there are

Trang 6

currently some very large sites in production with multiclusters of MySQL database servers Scalability is beyond the scope of this book but it is good to know that MySQL can handle your application as it grows in size

13.2 The Anatomy of a Relational Database

What makes up a database? The main components of an RDBMS are:

a The database server

Figure 13.2 The database server, the database, and a table

13.2.1 The Database Server

The database server is the actual server process running the databases It controls the storage of the data, grants access

to users, updates and deletes records, and communicates with other servers The database server is normally on a dedicated host computer, serving and managing multiple clients over a network, but can also be used as a standalone server on the local host machine to serve a single client (e.g., you might be the single client using MySQL on your local machine, often referred to as “localhost” without any network connection at all) This is probably the best way to learn how to use MySQL

If you are using MySQL, the server process is the MySQL service on Windows or the mysqld process on Linux/UNIX operating systems The database server typically follows the client/server model where the front end is the client, a user sitting at his or her workstation making database requests and waiting for results, and the back end is the database server that grants access to users, stores and manipulates the data, performs backups, even talks to other servers The requests to the database server can also be made from a program that acts on behalf of a user making requests from a Web page In the following chapters, you will learn how to make requests from the MySQL command line first, and then to connect to the database server from a PHP program using PHP built-in functions to make requests to the

MySQL database server

13.2.2 The Database

A database is a collection of related data elements, usually corresponding to a specific application A company might have one database for all its human resource needs, perhaps another one for its sales staff, a third one for e-commerce applications, and so on Figure 13.3 lists the databases installed on a particular version of MySQL The databases are

Trang 7

Figure 13.3 MySQL databases

13.2.3 Tables

Each database consists of two-dimensional tables In fact, a relational database stores all of its data in tables, and nothing more All operations are performed on the table, which can then produce other tables, and so on

One of the first decisions you will make when designing a database is what tables it will contain A typical database for

an organization might consist of tables for customers, orders, and products All these tables are related to one another in some way For example, customers have orders, and orders have items Although each table exists on its own,

collectively the tables comprise a database Figure 13.4 lists the tables in the database called “northwind,”[2] a fictional database provided by Microsoft to serve as a model for learning how to manipulate a database (This database is included on the CD provided with this book.)

[2] The Northwind Traders sample database typically comes as a free sample with Microsoft Access, but is available for MySQL at http://www.flash-remoting.com/examples/

Figure 13.4 Tables in the northwind database

13.2.4 Records and Fields

A table has a name and consists of a set of rows and columns It resembles a spreadsheet where each row, also called a record, is comprised of vertical columns, also called fields All rows from the same table have the same set of columns The “shippers” table from the “northwind” database has three columns and three rows, as shown in Figure 13.5

Trang 8

Figure 13.5 The rows (records) and columns (fields) from the “shippers” table in the “northwind” database

There are two basic operations you can perform on a relational table You can retrieve a subset of its columns and you can retrieve a subset of its rows Figures 13.6 and 13.7 are samples of the two operations

Figure 13.6 Retrieving a subset of columns

Figure 13.7 Retrieving a subset of rows

Remember, a relational database manipulates only tables and the result of all operations are also tables The tables are sets, which are themselves sets of rows and columns You can view the database itself as a set of tables

You can also perform a number of other operations between two tables, treating them as sets: You can join information from two tables, make cartesian products of the tables, get the intersection between two tables, add one table to another, and so on Later we show you how to perform operations on tables using the SQL language SQL allows you to “talk”

to a database Figures 13.6 and 13.7 use SQL commands to retrieve data

Columns/Fields

When discussing tables, we must talk about columns because they are an integral part of the table Columns are also

known as fields or attributes Fields describe the data Each field has a name For example, the “shippers” table has

fields named “ShipperID,” “CompanyName,” and “Phone” (see Figure 13.7) The field also describes the type of data it contains A data type can be a number, a character, a date, a time stamp, and so on In Figure 13.8 “ShipperID” is the

name of a field and the data type is an integer, and the shipper’s ID will not exceed 11 numbers There are many data types and sometimes they are specific to a particular database system; for example, MySQL might have different data types available than Oracle We will learn more about the MySQL data types in the next chapter

Figure 13.8 Each field has a name and a description of the data that can be stored there

Trang 9

Rows/Records

A record is a row in the table It could be a product in the product table, an employee record in the employee table, and

so on Each table in a database contains zero or more records Figure 13.9 shows us that there are three records in the

“shippers” table

Figure 13.9 There are three records in the “shippers” table

13.2.5 Primary Key and Indexes

A primary key is a unique identifier for each record For example, every employee in the United States has a Social Security number, every driver has a driver’s license, and every car has a license plate These identifiers are unique In the world of database tables, we call the unique identifier a primary key Although it is a good idea to have a primary key, not every table has one The primary key is determined when the table is created and is more in keeping with a discussion on database design In Figure 13.10, the “ShipperID” is the primary key for the “shippers” table in the

“northwest” database It is a unique ID that consists of a number that will automatically be incremented every time a new company (record) is added to the list of shippers

Figure 13.10 The “ShipperID” is the primary key in the “shippers” table

In addition to a primary key, one or more indexes are often used to enhance performance for finding rows in tables that are frequently accessed Indexes are like the indexes in the back of a book that help you find a specific topic more quickly than searching through the entire book When searching for a particular record in a table, MySQL must load all the records before it can execute the query An index, like the index of a book, is a reference to a particular record in a table

13.2.6 The Database Schema

Designing a very small database is not difficult, but designing one for a large Web-based application can be daunting Database design is both an art and a science and requires understanding how the relational model is implemented, a topic beyond the scope of this book When discussing the design of the database, you will encounter the term database schema, which refers to the structure of the database It describes the design of the database similar to a template or blueprint; it describes all the tables, and their layout, but does not contain the actual data in the database Figure 13.11 describes the schema for the tables in the “northwind” database

Trang 10

Figure 13.11 Database schema

13.3 Connecting to the Database

Here we assume you have installed a database server and it is running Downloading and installing MySQL is usually a straightforward process For details, see Appendix E

The MySQL database system uses the client/server model described in “Client/Server Databases” on page 568 There are a number of client applications available to connect to the database server, the most popular and most widely available being the mysql command-line client shown in Example 13.1

Example 13.1

$ mysql

Welcome to the MySQL monitor Commands end with ; or \g

Your MySQL connection id is 3 to server version: 4.1.8-nt-log

Type 'help;' or '\h' for help Type '\c' to clear the buffer

mysql>

Trang 11

Regardless of the type of client you choose, you will always need to specify the username, and the host you are connecting to Most configurations expect you to have a password, although if just working by yourself, it is not required You have the option to specify the default database as well

13.3.1 MySQL Command-Line Options

The mysql command-line client ships with the MySQL installation and is universally available It is a mysql.exe program located in the bin folder of your MySQL installation

To run this command-line application, you must start the command-line prompt In Windows, you go to the Start menu and choose the Run option, then type cmd in the Run window In Mac OS X, go to the Applications folder in your Finder and then navigate to Utilities You will find the Terminal application there You should navigate to the location where you installed MySQL and find the bin folder With UNIX, type commands at the shell prompt in a terminal window

The mysql client executable is normally located in the bin folder

To connect to a database using this client, you will enter information similar to the following line (see Figure 13.12): mysql user=root password=my_password host=localhost

Figure 13.12 The mysql client

Once you are successfully connected, you will get the mysql> prompt instead of your standard DOS/UNIX prompt This means you are now sending commands to the MySQL database server and not to your local computer’s operating system

There are many command-line options for the MySQL client The most common are shown in Table 13.1

Table 13.1 MySQL Command-Line Options

Trang 12

Table 13.1 MySQL Command-Line Options

Trang 13

Table 13.1 MySQL Command-Line Options

13.3.2 Graphical User Tools

The phpMyAdmin Tool

The phpMyAdmin tool (see Figures 13.13 and 13.14) is written in PHP to handle the administration of MySQL over the Web It is used to create and drop databases, manipulate tables and fields, execute SQL statements, manage keys on fields, manage privileges, and export data into various formats See http://www.phpmyadmin.net/home_page/index.php

Trang 14

Figure 13.13 The phpMyAdmin tool

Trang 15

Figure 13.14 After checking the “categories” box in the left frame, the structure of that table is displayed in the

phpMyAdmin main window

The MySQL Query Browser

The MySQL Query Browser is a graphical user interface (GUI) client available from mysql.com used to connect to the MySQL database server Once you download it and follow the simple installation wizard, you can start the application from the Start menu under Windows

The MySQL Query Browser then displays a connection dialog box You must specify the MySQL server where you want to connect, the credentials needed for authorization on that server, which machine that server runs on (and which port it listens to), and the default database (called the “Schema”) you will be using There are also a number of

additional options you can specify if necessary

You must choose a default database to issue queries Although it is possible to choose a default database after

connecting to the server, setting the default from the connection dialog box can save time on subsequent connections The information to enter is very similar to the command-line client: username, password, and the server host where the database server is running You can optionally enter the database name and port number (3306 is the default for MySQL) and save the connection information as a bookmark under the Stored Connection section (see Figure 13.15)

Trang 16

Figure 13.15 The MySQL Query Browser connection dialog box

By using the familiar tree-like navigation structure on the right side of the application window, you can also navigate through the various databases in the MySQL Query Browser (see Figure 13.16)

Trang 17

Figure 13.16 Navigating with the MySQL Query Browser

13.4 The MySQL Privilege System

With a drivers’ license, “authentication” means verifying that it is really you who owns the license by checking your picture and expiration date, and “authorization” means validating what type of vehicle you are authorized to drive, such

as a car, a large truck, or a school bus

Similarly, the primary purpose of the MySQL privilege system is to authenticate that the user and password are valid to connect to the specified host, as demonstrated in the previous examples in both the command-line and graphical client The second purpose of the privilege system is to specify what the user, once connected to the database, is authorized to

do For example, some users might be authorized to only select and view the data from a specific database, but not make any changes to it Some might be able to delete records, but not tables

Once you have installed MySQL, it is time to understand some basic guidelines of how to administer a MySQL database server, such as setting up the users and the privileges they have on certain databases You can use either the mysql command-line tool or the mysqladmin tool for performing administrative tasks Although there are some

Trang 18

graphical administrative tools avaialable, we use the command-line tools because they are always available and work the same way regardless of your operating system whether it is Windows, Macintosh, or Linux

The next section assumes you have basic SQL skills, such as familiarity with INSERT/ UPDATE/ DELETE/ SELECT statements If not, the SQL language is summarized in Chapter 14, “SQL Language Tutorial.”

13.4.1 Logging into the Database Server

When MySQL is installed, the mysql database is created with tables, called grant tables that define the initial user accounts and privileges The first account is that of a user named “root,” also called the superuser The superuser can do anything, meaning anyone logging onto the database as root is granted all privileges Initially the root account has no password, making it easy for anyone to log on as the superuser The other type of accounts created are anonymous user accounts, also without a password For both the root and anonymous accounts, Windows gets one each and UNIX gets two Either way, to avoid security problems, the first thing you should do, once the MySQL server starts, is to set a password on the root account and the anonymous accounts

MySQL keeps track of its own users and passwords separate from the operating system where it is running All the privileges for the MySQL database server are stored in the “mysql” database (the database with name “mysql”) For administration purposes, you should have root access rights to your server The mysqladmin utility is useful for creating passwords as well as performing other MySQL administrative tasks In the next example it is used to set the password for the root user

When working with MySQL, a number of like-name terms are used Table 13.2 is provided to help clarify the use of these terms

Table 13.2 MySQL Terminology

1 $ mysqladmin -u root -h localhost password quigley1

2 $ mysql -uroot -hlocalhost -pquigley1

Welcome to the MySQL monitor Commands end with ; or \g

Your MySQL connection id is 29 to server version:

Trang 19

quigley1

13.4.2 Finding the Databases

The database server keeps a list of available databases that can be displayed as a table by issuing the show command at the mysql prompt, as shown in Example 13.3 Typically when you install MySQL it comes with two databases: “test” and “mysql” The “test” database is used for testing various features or creating sample databases You normally do not need to have any special permissions to be able to do anything in that database The “mysql” database is a special database where the MySQL server stores various access permissions We look at the contents of the “mysql” database

in the next section

Example 13.3

C:\>mysql -uroot -ppassword

Welcome to the MySQL monitor Commands end with ; or \g

Your MySQL connection id is 5 to server version: 4.1.11-nt

Type 'help;' or '\h' for help Type '\c' to clear the buffer

mysql> show databases;

The show databases command gives us the list of all the databases on this server Typically, when you

install MySQL, you will be given the “mysql” database and the “test” database The “test” database is just

for testing purposes and is empty The “mysql” database contains all the MySQL server privilege

Trang 20

| columns_priv |

| db |

| func |

| help_category |

| help_keyword |

| help_relation |

| help_topic |

| host |

| tables_priv |

| time_zone |

| time_zone_leap_second |

| time_zone_name |

| time_zone_transition |

| time_zone_transition_type | | user |

+ -+

15 rows in set (0.19 sec) Explanation use mysql show tables 13.4.3 The “user” Table The “user” table specifies the users who are allowed to log into the database server and from what host It also holds their passwords and global access privileges Let’s look at the fields of the “user” table: mysql> describe user; + -+ -+

| Field | Type |

+ -+ -+

| Host | varchar(60) |

| User | varchar(16) |

| Password | varchar(41) |

| Select_priv | enum('N','Y') |

| Insert_priv | enum('N','Y') |

| Update_priv | enum('N','Y') |

| Delete_priv | enum('N','Y') |

| Create_priv | enum('N','Y') |

| Drop_priv | enum('N','Y') |

| Reload_priv | enum('N','Y') |

| Shutdown_priv | enum('N','Y') |

| Process_priv | enum('N','Y') |

| File_priv | enum('N','Y') |

Trang 21

| References_priv | enum('N','Y') |

| Index_priv | enum('N','Y') |

| Alter_priv | enum('N','Y') |

| Show_db_priv | enum('N','Y') |

| Super_priv | enum('N','Y') |

| Create_tmp_table_priv | enum('N','Y') |

| Lock_tables_priv | enum('N','Y') |

| Execute_priv | enum('N','Y') |

| Repl_slave_priv | enum('N','Y') |

| Repl_client_priv | enum('N','Y') |

| ssl_type | enum('','ANY','X509','SPECIFIED') | | ssl_cipher | blob |

| x509_issuer | blob |

| x509_subject | blob |

| max_questions | int(11) unsigned |

| max_updates | int(11) unsigned |

| max_connections | int(11) unsigned |

+ -+ -+

31 rows in set (0.00 sec) The key fields are Host, User, and Password All the other fields are used to fine-tune the privileges To log in, the user and password must match and the user must be from the given host The password field should be encoded so that it is not easily readable by someone looking over your shoulder MySQL provides a function called password() to do just that We see how to use it in the next example 13.4.4 The “db” Table The “db” table determines which databases a user is permitted to read, edit, and delete, limiting access to a certain host and user Its contents are described in the following table: mysql> describe db; + -+ -+

| Field | Type |

+ -+ -+

| Host | char(60) |

| Db | char(64) |

| User | char(16) |

| Select_priv | enum('N','Y') | | Insert_priv | enum('N','Y') | | Update_priv | enum('N','Y') | | Delete_priv | enum('N','Y') | | Create_priv | enum('N','Y') | | Drop_priv | enum('N','Y') | | Grant_priv | enum('N','Y') | | References_priv | enum('N','Y') | | Index_priv | enum('N','Y') | | Alter_priv | enum('N','Y') | | Create_tmp_table_priv | enum('N','Y') | | Lock_tables_priv | enum('N','Y') | + -+ -+

Trang 22

The key fields are the Host, Db, and User fields The other fields are used for fine-tuning the access rights The default

value is always “No” for the privileges, meaning that access rights must be explicitly granted ('N' is no and 'Y' is

yes.)

13.4.5 The “host” Table

The “host” table is an extension of the “db” table if the “db” table does not have a host entry It contains the hosts (IP

addresses), databases, and privileges that can connect to the MySQL database server Typically, your PHP script is

running on the same host computer as your database server The host is called “localhost,” which is simply an alias for

the current host machine located at IP address 127.0.0.1 For example, if you are on the server myserver.com, you can

refer to it to as the localhost If later you change the name of the server to yourhost.com, your database connection will

still be available because localhost always refers to the current host computer

The fields in the “host” table are shown in the following table:

mysql> describe host;

14 rows in set (0.31 sec)

The Db field contains all the users, databases, and hostnames for this MySQL server The other fields are switches with

Yes/No options to grant or revoke certain privileges and specify the level of that access right

Trang 23

Example 13.5

mysql> insert into host (host, db, Select_priv, Insert_priv,

-> Update_priv, Delete_priv, Create_priv, Drop_priv) -> values ('localhost',

'northwind','Y','Y','Y','Y','Y','Y');

Query OK, 1 row affected (0.53 sec)

Explanation

The insert into host command grants Select/Insert/Update/Delete/Create/Drop access to the

“northwind” database from the localhost, setting certain switches to Y for yes The ones that are not set will default to

no See Figure 13.17 for actual command and output

Figure 13.17 Output from the insert into host command

13.4.6 A Real-World Example

The following steps set privileges so that user bob can log into a MySQL database called “northwind” from the

localhost using the password guess After entering the mysql database with the use mysql command, the steps are:

mysql> insert into host(host, db, Select_priv, Insert_priv, -> Update_priv, Delete_priv, Create_priv, Drop_priv) -> values ('localhost', 'northwind','Y','Y','Y','Y','Y','Y');

mysql> insert into user(host,user,password) ->

Trang 24

bob guess localhostnorthwind

C:\>mysql -ubob -pguess -hlocalhost northwind Welcome to the MySQL monitor Commands end with ; or \g Your MySQL connection id is 8 to server version: 4.1.11-nt Type 'help;' or '\h' for help Type '\c' to clear the buffer

13.4.7 The Grant and Revoke Commands

MySQL access control involves two stages when you try to connect to the mysql server First the server checks to see if you are allowed to connect, and second, if you can connect, the server checks each statement you issue to determine whether or not you have sufficient privileges to execute the command For example, if you try to create or drop a table

in the database, or try to update a record, the server verifies that you have the correct privileges to execute those

commands To simplify all the steps required to set up the privileges on a database or a table, MySQL provides two commands: GRANT and REVOKE

The best way to illustrate how to use them is to see the following examples

1 GRANT ALL ON db_name.*

2 REVOKE ALL ON db_name.*

You can also specify the user for which you are granting or revoking the privileges by adding the TO

'user'@'host' and IDENTIFIED BY 'password' statement

Example 13.9

GRANT ALL PRIVILEGES ON db_name.tbl_name TO 'bob'@'localhost'

IDENTIFIED BY 'guess'

Trang 25

Explanation

This command will give user bob all the privileges when he logs in from the localhost and tries to access

database db_name and table tbl_name

13.4.8 Creating and Dropping a Database

Creating a database is simple Designing it is another story and depends on your requirements and the model you will use to organize your data With the smallest database, you will have to create at least one table The next chapter discusses how to create and drop both databases and tables Assuming you have been granted permission to create a database, you can do it at the mysql command line or with the mysqladmin tool as in Example 13.10

Example 13.10

1 mysql> create database my_sample_db;

Query OK, 1 row affected (0.00 sec)

2 mysql> use my_sample_db;

Database changed

3 mysql> show tables;

Empty set (0.00 sec)

4 mysql> create table test(

-> field1 INTEGER,

-> field2 VARCHAR(50)

-> );

Query OK, 0 rows affected (0.36 sec)

5 mysql> show tables;

1 row in set (0.00 sec)

6 mysql> drop table test;

Query OK, 0 rows affected (0.11 sec)

7 mysql> drop database my_sample_db;

Query OK, 0 rows affected (0.01 sec)

Explanation

my_sample_db

useshow

Ngày đăng: 21/01/2014, 09:20

TỪ KHÓA LIÊN QUAN