my sql

65
1 MySQL Pengaturcaraan PHP

Upload: salissal

Post on 24-May-2015

392 views

Category:

Education


1 download

TRANSCRIPT

Page 1: My sql

1

MySQL

Pengaturcaraan PHP

Page 2: My sql

2

MySQL is a database management system (DBMS) for relational databases.

A database, in the simplest terms, is a collection of interrelated data, be it text, numbers, or binary files, that are stored and kept organizedby the DBMS.

Pengaturcaraan PHP

A relational database uses multiple tables to store information in its most discernable parts. Prior to the early 1970s, when this concept was developed, databases looked more like spreadsheets with single, vast tables storing everything.

While relational databases may involve more thought in the designing and programming stages, they offer an improvement to reliability and data integrity that more than makes up for the extra effort required. Furthermore, relational databases are more searchable and allow for concurrent users.

Pengaturcaraan PHP

Page 3: My sql

3

By incorporating a database into a Web application, some of the data generated by PHP can be retrieved from MySQL. This further moves the site's content from a static, hard-coded basis to a flexible one, flexibility being the key to a dynamic Web site.

Pengaturcaraan PHP

MySQL is an open-source application, like PHP, meaning that it is free to use or even modify (the source code itself is downloadable).

There are occasions in which you should pay for a MySQL license, especially if you are making money from the sales or incorporation of the MySQLproduct. Check MySQL's licensing policy for more information on this.

Pengaturcaraan PHP

Page 4: My sql

4

The MySQL software consists of several pieces, including the MySQL server (mysqld, which runs and manages the databases), the mysql client (mysql, which gives you an interface to the server), and numerous utilities for maintenance and other purposes.

PHP has always had good support for MySQL, and that is even more true in the most recent versions of the language.

Pengaturcaraan PHP

MySQL has been known to handle databases as large as 60,000 tables with more than five billion rows.

MySQL can work with tables as large as eight million terabytes on some operating systems, generally a healthy 4 GB otherwise.

Pengaturcaraan PHP

Page 5: My sql

5

Choosing Column Types

Pengaturcaraan PHP

Before you start working with SQL and MySQL, you have to identify your application's needs. This then dictates the database design.

For the examples in this lesson, I'll create a database called sitename that stores some user registration information. The database will consist of a single table, users, that contains columns to store user ID, first name, last name, email address, password, and registration date. The users table has the current layout, using MySQL's naming rules for column titles — alphanumeric names, plus the underscore, with no spaces.

2004-12-15 17:00:00 registration_date

[email protected]

Maucklast_name

Hannah first_name

834 user_idExampleColumn Name

Page 6: My sql

6

Once you have identified all of the tables and columns that the database will need, you should determine each field's MySQL data type.

When creating the database, MySQL requires that you define what sort of information each field will contain. There are three primary categories, which is true for almost every database application:

Text

Numbers

Dates & Times

Pengaturcaraan PHP

Many of the types can take an optional Length attribute, limiting their size. The square brackets, [ ], indicate an optional parameter to be put in parentheses. You should keep in mind that if you insert a string five characters long into a CHAR(2) field, the final three characters will be truncated.

This is true for any field in which the length is set (CHAR, VARCHAR, INT, etc.). So your length should always correspond to the maximum possible value, as a number, or longest possible string, as text, that might be stored.

Pengaturcaraan PHP

Page 7: My sql

7

There are also two special types —ENUM and SET — that allow you to define a series of acceptable values for that field.

An ENUM column can have only one value of a possible several thousand values, while SET allows for several of up to 64 possible values. These are available in MySQL but aren't present in every database application.

Pengaturcaraan PHP

Set the maximum lengths for text and number columns.

The size of any field should be restricted to the smallest possible value, based upon the largest possible input. For example, if the largest a number such as user_id can be is in the hundreds, set the column as a three-digit SMALLINT allowing for up to 999 values.

DATETIMEregistration_dateCHAR(40)passwordVARCHAR(40)emailVARCHAR(30)last_nameVARCHAR(15)first_nameSMALLINTuser_idTypeColumn Name

Pengaturcaraan PHP

Page 8: My sql

8

Many of the data types have synonymous names: INT and INTEGER, DEC and DECIMAL, etc.

The TIMESTAMP field type is automatically set as the current dateand time when an INSERT or UPDATE occurs, even if no value is specified for that particular field.

If a table has multiple TIMESTAMP columns, only the first one will be updated when an INSERT or UPDATE is performed.

Pengaturcaraan PHP

There is also a BLOB type, which is a variant on TEXT that allows for storing binary files, like images, in a table. This type is also used for some encrypted data.

Pengaturcaraan PHP

Page 9: My sql

9

Choosing Other Column Properties

Pengaturcaraan PHP

Every type can be set as NOT NULL. The NULL value, in databases and programming, is equivalent to saying that the field has no value. Ideally, every field of every record in a database should have a value, but that is rarely the case in reality. To force a field to have a value, you add the NOT NULL description to its column type. For example, a required dollar amount can be described as:

Pengaturcaraan PHP

Page 10: My sql

10

When creating a table, you can also specify a default value for any type. In cases where a majority of the records will have the same value for a column, presetting a default will save you from having to specify a value when inserting new rows, unless that row's value for that column is different from the norm.

Pengaturcaraan PHP

Finishing Defining ColumnsFinally, when designing a database, you'll need to consider creating indexes, adding keys, and using the AUTO_INCREMENT property.

Pengaturcaraan PHP

Page 11: My sql

11

Identify your primary key. The primary key is quixotically both arbitrary and critically important. Almost always a number value, the primary key is a unique way to refer to a particular record. For example, your phone number has no inherent value but is uniquely a way to reach you.

Pengaturcaraan PHP

Indexes, Keys, and AUTO_INCREMENT

Two concepts closely related to database design are indexes and keys.

An index in a database is a way of requesting that the database keep an eye on the values of a specific column or combination of columns.

The end result of this is improved performance when retrieving records but slightly hindered performance when inserting or updating them.

Pengaturcaraan PHP

Page 12: My sql

12

A key in a database table is integral to the normalization process used for designing more complicated databases.

There are two types of keys: primary and foreign.

Each table should have one primary key. The primary key in a table is often linked as a foreign key in another.

Pengaturcaraan PHP

A table's primary key is an artificial way to refer to a record and should abide by three rules:

- It must always have a value

- That value must never change.

- That value must be unique for each record in the table

Pengaturcaraan PHP

Page 13: My sql

13

Using the mysql client

Pengaturcaraan PHP

The mysql client is accessed from a command-line interface, be it the Terminal application in Linux or Mac OS X, or a DOS prompt in Windows. It can take several arguments up front, including the username, password, and hostname (computer name or URL). You establish these arguments like so:

Pengaturcaraan PHP

Page 14: My sql

14

The -p option will cause the client to prompt you for the password. You can also specify the password on this line if you prefer — by typing it directly after the -p prompt — but it will be visible, which is insecure. The -h hostname argument is optional, and I tend to leave it off unless I cannot connect to the MySQL server otherwise.

Pengaturcaraan PHP

Within the mysql client, every statement or SQL command needs to be terminated by a semicolon. These semicolons are an indication to MySQLthat the query is complete; the semicolons are not part of the SQL itself.

What this means is that you can continue the same SQL statement over several lines within the mysql client, to make it easier to read.

Pengaturcaraan PHP

Page 15: My sql

15

If you are using MySQL hosted on another computer, such as a Web host, that system's administrator should provide you with access and you may need to use another interface tool, such as phpMyAdmin.

Pengaturcaraan PHP

Page 16: My sql

16

Pengaturcaraan PHP

Pengaturcaraan PHP

Page 17: My sql

17

Pengaturcaraan PHP

Since the mysql client is a command-line tool, you may not be able to use it if you are working with an ISP's or Web host's server. Here are two things you can try:

- Telnet or SSH into the remote server and then use mysql.

- Install the MySQL software on your computer and use the mysql client to connect to the remote server by specifying it as the hostname (mysql -u username -p -h www.site.com).

Pengaturcaraan PHP

Page 18: My sql

18

If neither of these options work, you have other choices, beginning with phpMyAdmin. A popular open source tool written in PHP, phpMyAdmin, provides a Web-based interface for MySQL. Available from the http://www.phpmyadmin.net Web site, this software is so common that many Web hosting companies offer it as the default way for their users to interface with a MySQL database.

Pengaturcaraan PHP

If you cannot access MySQL through the mysql client, you can still do practically everything with phpMyAdmin. The SQL tab in the latest version allows you to directly type in SQL commands, although many common commands have their own shortcuts in the program.

Pengaturcaraan PHP

Page 19: My sql

19

The good people at MySQLhave other tools available for download, including the MySQLQuery Browser, which will let you interact with the server through a graphical interface.

If this isn't to your liking, there are dozens of others available, from third parties, if you search the Web.

Pengaturcaraan PHP

To see what else you can do with the mysql utility, type:

The mysql client on most systems allows you to use the up and down arrows to scroll through previously entered commands. This can save you time when working with a database.

Pengaturcaraan PHP

Page 20: My sql

20

Creating Databases and Tables

Pengaturcaraan PHP

The syntax for creating a new database using SQL and MySQL is:

Pengaturcaraan PHP

Page 21: My sql

21

The CREATE term is also used for making tables.

As you can see from this syntax, after naming the table, you define each column — in order — within parentheses. Each column-description pair should be separated from the next by a comma. Should you choose to create indexes at this time, you can add those at the end of the creation statement, but you can add indexes at a later time as well.

Pengaturcaraan PHP

Create and select the new database.

The first line creates the database, assuming that you are logged into mysql as a user with permission to create new databases.

The second line tells MySQL that you want to work within this database from here on out. Remember that within the mysql client, you must terminate every SQL command with a semicolon, although these semicolons aren't technically part of SQL itself. If you are using a hosting company's MySQL, they will probably create the database for you.

Page 22: My sql

22

Create the users table.

This step takes the design for the users table and integrates that within the CREATE table syntax.

The order in which you enter the columns here will dictate the order in which the columns appear in the table.

Step 4Confirm the existence of the table.

The SHOW command reveals the tables in a database or the column names and types in a table, if named.

Page 23: My sql

23

DESCRIBE tablename, which you might see in other resources, is the same statement:

Pengaturcaraan PHP

Inserting Records

Pengaturcaraan PHP

Page 24: My sql

24

With that in mind, there are two formats for inserting data. With the first, you specify the columns to be used:

Using this structure, you can add rows of records, populating only the columns that matter. The result will be that any columns not given a value will be treated as NULL or given a default value, if that was defined. Note that if a column cannot have a NULL value, it was set as NOTNULL, not specifying a value will cause an error.

Pengaturcaraan PHP

The second format for inserting records is not to specify any columns at all but to include values for every one.

If you use this second method, you must specify a value, even if it's NULL, for every column. If there are six columns in the table, you must list six values. Failure to match the number of values to the number of columns will cause an error. For this and other reasons, the first format of inserting records is generally preferable.

Pengaturcaraan PHP

Page 25: My sql

25

MySQL also allows you to insert multiple rows at one time, separating each record by a comma:

Pengaturcaraan PHP

Inserting Data into a TableThe following steps can be used to insert data into a table.

Two functions are used in both cases. I use the NOW() function to set the registration_date as this moment. Notice the function is not enclosed by quotation marks.

Another function, SHA(), is used to store an encrypted form of the password. It's available in versions 4.0.2 and later of MySQL. If you have an earlier version, use MD5() instead of SHA().

Pengaturcaraan PHP

Page 26: My sql

26

Step 2Insert several values into the users table.

Since MySQL allows you to insert multiple values at once, you can take advantage of this and fill up the table with records.

The SHA() function is one way to encrypt data. This function creates an encrypted string that is always exactly 40 characters long, which is why I set the users table's password column as CHAR(40). SHA() is a one-way encryption technique, meaning that it cannot be reversed. It's useful for storing sensitive data that need not be viewed in an unencrypted form again, but it's obviously not a good choice for sensitive data that should be protected but later viewed like credit card numbers.

If you are not using a version of MySQL later than 4.0.1, you can use the MD5() function instead, and set the password column as CHAR(32). This function does the same task, using a different algorithm, and returns a 32-character long string.

Pengaturcaraan PHP

Page 27: My sql

27

The NOW() function is handy for date, time, and timestamp columns, since it will insert the current date and time on the server for that field.

Pengaturcaraan PHP

When using any function in a SQL statement, do not place it within quotation marks. You also must not have any spaces between the function's name and the following parenthesis so NOW() not NOW ().

Pengaturcaraan PHP

Page 28: My sql

28

If you need to insert a value containing a single quotation mark, escape it with a backslash:

Pengaturcaraan PHP

Selecting Data

Pengaturcaraan PHP

Page 29: My sql

29

Now that the database has some records in it, you can begin to retrieve the information with the most used of all SQL terms, SELECT. This type of query returns rows of records that match certain criteria, using the syntax:

Pengaturcaraan PHP

The simplest SELECT query is:

The asterisk means that you want to view every column.

Pengaturcaraan PHP

Page 30: My sql

30

Your other choice would be to specify the columns to be returned, with each separated from the next by a comma.

Pengaturcaraan PHP

There are a few benefits to being explicit about which columns are selected. The first is performance: there's no reason to fetch columns you will not be using.

The second is order: you can return columns in an order other than their layout in the table.

Third, it allows you to manipulate the values in those columns using functions.

Pengaturcaraan PHP

Page 31: My sql

31

Retrieve all the data from the users table. This very basic SQL commandwill retrieve every column of every row stored within that table.

Pengaturcaraan PHP

Retrieve just the first and last names from users.

Instead of showing the data from every field in the users table, you can use the SELECT statement to limit yourself to only the pertinent information.

Pengaturcaraan PHP

Page 32: My sql

32

Pengaturcaraan PHP

Using Conditionals

Pengaturcaraan PHP

Page 33: My sql

33

The problem with the SELECT statement as I have used it thus far is that it will automatically retrieve every record. While this isn't a big issue when dealing with a few rows of information, it will greatly hinder the performance of your database as the number of records grows. To improve the efficiency of your SELECT statements, you can use different conditionals in an almost limitless number of combinations. These conditionals use the SQL term WHERE and are written much as you'd write a conditional in PHP.

Pengaturcaraan PHP

The MySQL Operators table lists the most common operators you would use within a WHERE conditional. These MySQL operators are frequently, but not exclusively, used with WHERE expressions.

where the condition is not true NOT(also !)where both conditionals are true AND(also &&)where one of two conditionals is true OR(also ||)outside of a range NOT BETWEENwithin a range BETWEENdoes not have a value IS NULLhas a value IS NOT NULLnot equal to != greater than or equal to >= less than or equal to <= greater than > less than < equals = MeaningOperator

Page 34: My sql

34

These operators can be used together, along with parentheses, to create more complex expressions.

Pengaturcaraan PHP

To demonstrate using conditionals, I'll retrieve more specific data from the sitename database. The examples that follow will be just a few of the possibilities.

Select the records for every user registered on a specific date.

Pengaturcaraan PHP

Page 35: My sql

35

Select all the first names of users whose last name is Simpson.

Here I'm just returning one field (first_name) for each row. The returned records themselves are determined by the value of another field (last_name).

Pengaturcaraan PHP

Select everything from every record in the users table that does not have an email address.

The IS NULL conditional is the same as saying, "does not have a value." Keep in mind that an empty string is the same thing as a value, in NULL terms, and therefore would not match this condition. Such a case would, however, match SELECT * FROM users WHERE email = '';

Pengaturcaraan PHP

Page 36: My sql

36

Select the record in which the password is password.

Since the stored passwords were encrypted with the SHA() function, you can find a match by comparing the stored version against an encrypted version. SHA() is case-sensitive, so this query will work only if the passwords (storedvs. queried) match exactly.

Pengaturcaraan PHP

You can also use the IN and NOT IN operators to determine if a column's value is or is not one of a listed set of values.

Pengaturcaraan PHP

Page 37: My sql

37

Using LIKE and NOT LIKE

Pengaturcaraan PHP

Using numbers, dates, and NULLs in conditionals is a straightforward process, but strings can be trickier. You can check for string equality with a query such as:

Pengaturcaraan PHP

Page 38: My sql

38

If you wanted to match a person's last name that could be Smith or Smithsor Smithson, you would need a more flexible conditional. This is where the LIKE and NOT LIKE terms come in. These are used — primarily with strings — in conjunction with two wildcard characters: the underscore (_), which matches a single character, and the percentage sign (%), which matches zero or more characters. In the last-name example, the query I would write would be:

Pengaturcaraan PHP

To demonstrate using the LIKE term, I'll retrieve more specific data from the sitename database. The examples that follow will be just a few of the possibilities.

Select all of the records in which the last name starts with Bank.

Pengaturcaraan PHP

Page 39: My sql

39

Select the name for every record whose email address is not of the form [email protected].

If I want to rule out certain possibilities, I can use NOT LIKE with the wildcard.

Pengaturcaraan PHP

Wildcard charactersThe wildcard characters can be used at the front and/or back of a string in your queries.

SELECT * FROM users WHERE user_name =‘%_smith%'

Pengaturcaraan PHP

Page 40: My sql

40

Sorting and Limiting Query Results

Pengaturcaraan PHP

Whereas the WHERE conditional places restrictions on what records are returned, the ORDER BY clause will affect how those records are presented. Much as listing the columns of a table arranges the returned order, ORDER BY structures the entire list. When you do not dictate the order of the returned data, it will be presented to you in somewhat unpredictable ways, although probably on the primary key in ascending order.

Pengaturcaraan PHP

Page 41: My sql

41

The default order when using ORDER BY is ascending (abbreviated ASC), meaning that numbers increase from small to large and dates go from older to most recent. You can reverse this order by specifying DESC.

Pengaturcaraan PHP

You can even order the returned values by multiple columns.

Here, I select all of the users in alphabetical order by last name.

Pengaturcaraan PHP

Page 42: My sql

42

In this example, I display all of the users in alphabetical order by last name and then first name.

In this query, the effect would be that every row is returned, first ordered by the last_name, and then by first_name within the last_names. The effect is most evident among the Simpson's.

Pengaturcaraan PHP

Using ORDER BY with WHEREYou can, and frequently will, use ORDER BY with WHERE or other clauses. When doing so, place the ORDER BY after the other conditions:

SELECT * FROM users WHE registration_date >= '2005-03-01‘ORDER BY last_name ASC

Pengaturcaraan PHP

Page 43: My sql

43

Another SQL term you can add to your query statement is LIMIT. Unlike WHERE, which affects which records to return, or ORDER BY, whichdecides how those records are sorted, LIMIT states how many records to return. It is used like so:

In the first example, only the initial 10 records from the query will be returned. In the second, 20 records will be returned, starting with the 11th. Like arrays in PHP, the indexes in databases begin at 0 when it comes to LIMITs, so 10 is the 11th record.

Pengaturcaraan PHP

You can use LIMIT with WHERE and/or ORDER BY, appending it to the end of your query.

Even though LIMIT does not reduce the strain of a query on the database (since it has to assemble every record and then truncate the list), it will minimize the amount of data to handle when it comes to the mysql client or your PHP scripts. As a rule, when writing queries, there is never any reason to return columns or rows you will not use.

Pengaturcaraan PHP

Page 44: My sql

44

You can even limit the amount of data returned.

Here I select the last five registered users.

To return the latest of anything, I must sort the data by date, in descending order. Then, to see just the most recent five, I apply a LIMIT 5 to the query.

Pengaturcaraan PHP

Here I select the second person to register.

This may look strange, but it's just a good application of the information learned so far. First I order all of the records by registration_date ascending, so the first people to register would be returned first. Then I limit this group to start at 1 (which is the second row) and to return just one record.

Pengaturcaraan PHP

Page 45: My sql

45

Displaying multiple pagesThe LIMIT x, y clause is most frequently used when displaying multiple pages of query results where you would want to show the first 20 results, then the second 20, and so forth.

Pengaturcaraan PHP

Updating and Deleting Data

Pengaturcaraan PHP

Page 46: My sql

46

Once your tables contain some data, you have the option of changing existing records. The most frequent reason for doing this would be if information were entered incorrectly — or in the case of user information, if data gets changed, such as a last name or email address, and that needs to be reflected in the database. The syntax for updating records is:

Pengaturcaraan PHP

You can alter multiple columns of one record at a single time, separating each from the next by a comma.

Pengaturcaraan PHP

Page 47: My sql

47

Normally you will want to use a WHERE clause to specify what rows to affect; otherwise, the change would be applied to every row.

The primary key — which should never change — can be a reference point in WHERE clauses, even if every other field needs to be altered.

Pengaturcaraan PHP

Next, I will update the record.

To change the email address, I use an UPDATE query, being certain to specify to which record this should apply, using the primary key (user_id). MySQL will report upon the success of the query and how many rows were affected.

Pengaturcaraan PHP

Page 48: My sql

48

Protecting against accidental UPDATEsTo protect yourself against accidentally updating too many rows, apply a LIMIT clause to your UPDATEs.

UPDATE users SET email ='[email protected]' WHEREuser_id = 17 LIMIT 1

Pengaturcaraan PHP

Another step you can easily take on existing data is to entirely remove it from the database. To do this, you use the DELETE command.

Note that once you have deleted a record, there is no way of retrieving it, so you may want to back up your database before performing any deletes. Also, you should get in the habit of using WHERE when deleting data, or else you will delete all of the data in a table. The query DELETE FROM tablename will empty out a table, while still retaining its structure. Similarly, the command TRUNCATE TABLE tablename will delete an entire table (both the records and the structure) and then re-create the structure. The end result is the same, but this method is faster and safer

Pengaturcaraan PHP

Page 49: My sql

49

Now delete the record.

As with the update, MySQL will report on the successful execution of the query and how many rows were affected.

At this point, there is no way of reinstating the deleted records unless you backed up the database beforehand.

Pengaturcaraan PHP

Deleting all the data in a tableTo delete all of the data in a table, as well as the table itself, use DROP TABLE:

DROP TABLE tablename

Deleting an entire databaseTo delete an entire database, including every table therein and all of its data, use DROP DATABASE:

DROP DATABASE databasename

Adding a LIMIT when deleting recordsFor extra security when deleting records, you can add a LIMIT clause (assuming you want to delete only a set number of records):

DELETE FROM tablename WHERE id = 4 LIMIT 1

Pengaturcaraan PHP

Page 50: My sql

50

Using Text and Numeric Functions

Pengaturcaraan PHP

Using FunctionsFunctions — such as NOW() and SHA() — are just the tip of the iceberg. Most of the functions discussed here are used with SELECT queries to format and alter the returned data, but you may use MySQL functions in any number of different queries.

To use any function, you need to modify your query so that you specify to which column or columns the function should be applied.

Pengaturcaraan PHP

Page 51: My sql

51

To specify multiple columns, you can write a query like either of these:

Pengaturcaraan PHP

Text FunctionsThe first group of functions I will demonstrate are those meant for manipulating the various text and character columns. Most of the functions in this category are listed in the table.

Returns length characters from column beginning with start(indexed from 0).

SUBSTRING(column, start, length)

SUBSTRING()

Turns the stored string into an all-lowercase format. LOWER(column)LOWER()

Capitalizes the entire stored string. UPPER(column)UPPER()

Trims excess spaces from the beginning and end of the stored value.

TRIM(column)TRIM()

Returns the rightmost x characters from a column's value. RIGHT(column, x)RIGHT()

Returns the leftmost x characters from a column's value. LEFT(column, x)LEFT()

Returns the length of the value stored in the column. LENGTH(column)LENGTH()

Creates a new string of the form xy. CONCAT(x, y,...)CONCAT()

PurposeUsageFunction

Page 52: My sql

52

CONCAT(), perhaps the most useful of the text functions, deserves special attention. The CONCAT() function accomplishes concatenation, for which PHP uses the period. The syntax for concatenation requires you to place, within parentheses, the various values you want assembled, in order and separated by commas:

Pengaturcaraan PHP

While you can — and normally will — apply CONCAT() to columns, you can also incorporate strings, entered within single quotation marks. To format a person's name as Surname, First from two columns, you would use:

Pengaturcaraan PHP

Page 53: My sql

53

Because concatenation normally returns a new form of a column, it's an excellent time to use an alias.

Pengaturcaraan PHP

Example 1Concatenate the names without using an alias.

Two points are demonstrated here. First, the users' first names, last names, and a space are concatenated together to make one string. Second, if you don't use an alias, the returned data's column heading is very literal and often unwieldy.

Pengaturcaraan PHP

Page 54: My sql

54

Example 2Concatenate the names while using an alias.

To use an alias, just add AS aliasname after the item to be renamed. The alias will be the new title for the returned data.

Pengaturcaraan PHP

Example 3Find the longest last name.

This query first determines the length of each last name and calls that L. Then the whole list is sorted by that value from highest to lowest, and the string length and first name of the first row is returned.

Pengaturcaraan PHP

Page 55: My sql

55

Columns and stringsFunctions can be equally applied to both columns and manually entered strings. For example, the following is perfectly acceptable:

SELECT UPPER ('makemebig')

Pengaturcaraan PHP

Numeric FunctionsBesides the standard math operators that MySQL uses (for addition, subtraction, multiplication, and division), there are about two dozen functions dedicated to formatting and performing calculations on numeric values. The table lists the most common of these, some of which I will demonstrate shortly.

Pengaturcaraan PHP

Page 56: My sql

56

Calculates the square root of x. SQRT(x)SQRT()

Returns a value indicating whether a number is negative (–1), zero (0), or positive (+1).

SIGN(x)SIGN()

Returns the number x rounded to y decimal places. ROUND(x, y)ROUND()

Returns a random number between 0 and 1.0. RAND()RAND()

Returns the remainder of dividing x by y (either or both can be a column). MOD(x, y)MOD()

Returns x formatted as a number with y decimal places and commas inserted every three spaces.

FORMAT(x, y)

FORMAT()

Returns the integer value of x. FLOOR(x)FLOOR()

Returns the next-highest integer based upon the value of x. CEILING(x)CEILING()

Returns the absolute value of x. ABS(x)ABS()

PurposeUsageFunction

Pengaturcaraan PHP

I want to specifically mention three of these functions: FORMAT(), ROUND(), and RAND(). The first — which is not technically number specific — turns any number into a more conventionally formatted layout. For example, if you stored the cost of a car as 20198.20, FORMAT(car_cost, 2) would turn that number into the more common 20,198.20.

Pengaturcaraan PHP

Page 57: My sql

57

ROUND() will take one value, presumably from a column, and round that to a specified number of decimal places. If no decimal places are indicated, it will round the number to the nearest integer.

If more decimal places are indicated than exist in the original number, the remaining spaces are padded with zeros (to the right of the decimal point).

Pengaturcaraan PHP

The RAND() function, as you might infer, is used for returning random numbers

Pengaturcaraan PHP

Page 58: My sql

58

A further benefit to the RAND() function is that it can be used with your queries to return the results in a random order.

Pengaturcaraan PHP

Using Numeric FunctionsHere I display a number, formatting the amount as dollars.

Using the FORMAT() function, as just described, with CONCAT(), you can turn any number into a currency format as you might display it in a Web page.

Pengaturcaraan PHP

Page 59: My sql

59

Next, retrieve a random email address from the table.

Pengaturcaraan PHP

Date and Time Functions

Pengaturcaraan PHP

Page 60: My sql

60

Returns the number of seconds since the epoch until the current moment or until the date specified. UNIX_TIMESTAMP(date) UNIX_TIMESTAMP()

Returns the current date and time. NOW()NOW()

Returns the current time. CURTIME()CURTIME()

Returns the current date. CURDATE()CURDATE()

Returns the value of x units subtracted from column. SUBDATE(column, INTERVAL x type)SUBDATE()

Returns the value of x units added to column. ADDDATE(column, INTERVAL x type)ADDDATE()

Returns just the year value of a stored date. YEAR(column)YEAR()

Returns just the numerical month value of a stored date. MONTH(column)MONTH()

Returns the name of the month in a date value. MONTHNAME(column)MONTHNAME()

Returns just the numerical day value of a stored date. DAYOFMONTH(column)DAYOFMONTH()

Returns the name of the day for a date value. DAYNAME(column)DAYNAME()

Returns just the second value of a stored date. SECOND(column)SECOND()

Returns just the minute value of a stored date. MINUTE(column)MINUTE()

Returns just the hour value of a stored date. HOUR(column)HOUR()

PurposeUsageFunction

Using Date and Time FunctionsUse the following steps to demonstrate the usage of date and time functions.

Here I display the first and last name for every user registered on the 30th of the month.

The DAY() function returns the day of the month part of a date column. So seeing if the returned result is equal to some value is an easy way to restrict what records are selected.

Pengaturcaraan PHP

Page 61: My sql

61

Next, I show the current date and time, according to MySQL.

To show what date and time MySQL currently thinks it is, you can select the CURDATE() and CURTIME() functions, which return these values. This is another example of a query that can be run without referring to a particular table name.

Pengaturcaraan PHP

ADDDATE() and SUBDATE()The ADDDATE() and SUBDATE() functions, which are synonyms for DATE_ADD() and DATE_SUB(), perform calculations upon date values. The syntax for using them is:

ADDDATE(date, INTERVAL x type)

In the example, date can be either an entered date or a value retrieved from a column. The x value differs, depending upon which type you specify. The available types are SECOND, MINUTE, HOUR, DAY, MONTH, and YEAR. There are even combinations of these: MINUTE_SECOND, HOUR_MINUTE, DAY_HOUR, and YEAR_MONTH.

To add two hours to a date, you would write:

ADDDATE(date, INTERVAL 2 HOUR)

To add two weeks from December 31, 2005:

ADDDATE('2005-12-31', INTERVAL 14 DAY)

To subtract 15 months from a date:

SUBDATE(date, INTERVAL '1-3' YEAR_MONTH)

This last query tells MySQL that you want to subtract one year and three months from the value stored in the date column.

Page 62: My sql

62

FormattingThere are two additional date and time functions that you might find yourself using more than all of the others combined: DATE_FORMAT() and TIME_FORMAT(). There is some overlap between the two and when you would use one or the other.

DATE_FORMAT() can be used to format both the date and time if a value contains both (e.g., YYYY-MM-DD HH:MM:SS). Comparatively, TIME_FORMAT() can format only the time value and must be used if only the time value is being stored (e.g. HH:MM: SS). The syntax is:

Pengaturcaraan PHP

AM or PM AM or PM %p

20:17:02 Time, 24-hour clock %T

8:17:02 PM Time %r

00-59 Seconds %S

00-59 Minutes %i

00-23 Hour, 24-hour clock, two digit %H

0-23 Hour, 24-hour clock %k

01-12 Hour, two digit %h

1-12 (lowercase L) Hour %l

02 Year %y

2002 Year %Y

Jan-Dec Month name, abbreviated %b

January-December Month name %M

01-12 Month number, two digit %m

1-12 Month number %c

Sun-Sat Abbreviated weekday name %a

Sunday-Saturday Weekday name %W

1st-31st Day with suffix %D

01-31 Day of the month, two digit %d

1-31 Day of the month %e

ExampleUsageTerm

Page 63: My sql

63

Assuming that a column called the_date has the date and time of 2005-04-30 23:07:45 stored in it, common formatting tasks and results would be:

Time (11:07:45 PM)

Pengaturcaraan PHP

Time without seconds (11:07 PM)

Date (April 30th, 2005)

Pengaturcaraan PHP

Page 64: My sql

64

Here, I return the current date and time as Month DD, YYYY HH:MM.

Using the NOW() function, which returns the current date and time, I can practice my formatting to see what results are returned.

Pengaturcaraan PHP

Next, I display the current time, using 24-hour notation.

Pengaturcaraan PHP

Page 65: My sql

65

End

Pengaturcaraan PHP