• Like
My sql
Upcoming SlideShare
Loading in...5
Uploaded on


More in: Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. MySQLPengaturcaraan PHP 1
  • 2. Pengaturcaraan PHP 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 organized by the DBMS. Pengaturcaraan PHPA relational database uses multiple tables to store information in its mostdiscernable parts. Prior to the early 1970s, when this concept wasdeveloped, databases looked more like spreadsheets with single, vasttables storing everything.While relational databases may involve more thought in the designing andprogramming stages, they offer an improvement to reliability and dataintegrity that more than makes up for the extra effort required. Furthermore,relational databases are more searchable and allow for concurrent users. 2
  • 3. Pengaturcaraan PHPBy incorporating a database into a Web application, some of the datagenerated by PHP can be retrieved from MySQL. This further moves thesites content from a static, hard-coded basis to a flexible one, flexibilitybeing the key to a dynamic Web site.Pengaturcaraan PHPMySQL is an open-source application, like PHP, meaning that it is free touse or even modify (the source code itself is downloadable).There are occasions in which you should pay for a MySQL license, especiallyif you are making money from the sales or incorporation of the MySQLproduct. Check MySQLs licensing policy for more information on this. 3
  • 4. Pengaturcaraan PHPThe MySQL software consists ofseveral pieces, including theMySQL server (mysqld, which runsand manages the databases), themysql client (mysql, which givesyou an interface to the server), andnumerous utilities for maintenanceand other purposes.PHP has always had good supportfor MySQL, and that is even moretrue in the most recent versions ofthe 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. 4
  • 5. Choosing Column Types Pengaturcaraan PHPBefore you start working with SQL and MySQL, you have to identify yourapplications needs. This then dictates the database design.For the examples in this lesson, Ill create a database called sitename that storessome user registration information. The database will consist of a single table,users, that contains columns to store user ID, first name, last name, emailaddress, password, and registration date. The users table has the current layout,using MySQLs naming rules for column titles — alphanumeric names, plusthe underscore, with no spaces. Column Name Example user_id 834 first_name Hannah last_name Mauck email phpmysql2@dmcinsights.com password bethany registration_date 2004-12-15 17:00:00 5
  • 6. Pengaturcaraan PHPOnce you have identified all of the tables and columns that the database willneed, you should determine each fields MySQL data type.When creating the database, MySQL requires that you define what sort ofinformation each field will contain. There are three primary categories, whichis true for almost every database application:TextNumbersDates & TimesPengaturcaraan PHPMany of the types can take an optionalLength attribute, limiting their size. Thesquare brackets, [ ], indicate an optionalparameter to be put in parentheses.You should keep in mind that if youinsert a string five characters longinto a CHAR(2) field, the final threecharacters will be truncated.This is true for any field in which thelength is set (CHAR, VARCHAR, INT,etc.). So your length should alwayscorrespond to the maximum possiblevalue, as a number, or longest possiblestring, as text, that might be stored. 6
  • 7. Pengaturcaraan PHPThere are also two special types —ENUM and SET — that allow you todefine a series of acceptable valuesfor that field.An ENUM column can have only onevalue of a possible severalthousand values, while SET allowsfor several of up to 64 possiblevalues. These are available inMySQL but arent present in everydatabase application.Pengaturcaraan PHPSet 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 numbersuch as user_id can be is in the hundreds, set the column as a three-digitSMALLINT allowing for up to 999 values. Column Name Type user_id SMALLINT first_name VARCHAR(15) last_name VARCHAR(30) email VARCHAR(40) password CHAR(40) registration_date DATETIME 7
  • 8. Pengaturcaraan PHPMany of the data types havesynonymous names: INT andINTEGER, DEC and DECIMAL, etc.The TIMESTAMP field type isautomatically set as the current dateand time when an INSERT or UPDATEoccurs, even if no value is specified forthat particular field.If a table has multiple TIMESTAMPcolumns, only the first one will beupdated when an INSERT or UPDATEis performed.Pengaturcaraan PHPThere is also a BLOB type, which is a variant on TEXT that allows forstoring binary files, like images, in a table. This type is also used forsome encrypted data. 8
  • 9. Choosing Other Column Properties Pengaturcaraan PHPPengaturcaraan PHPEvery type can be set as NOT NULL. The NULL value, in databases andprogramming, 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 israrely the case in reality. To force a field to have a value, you add the NOTNULL description to its column type. For example, a required dollar amountcan be described as: 9
  • 10. Pengaturcaraan PHPWhen creating a table, you can also specify a default value for any type. Incases 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 wheninserting new rows, unless that rows value for that column is different fromthe norm.Pengaturcaraan PHP Finishing Defining Columns Finally, when designing a database, youll need to consider creating indexes, adding keys, and using the AUTO_INCREMENT property. 10
  • 11. Pengaturcaraan PHPIdentify your primary key. The primary key is quixotically both arbitrary andcritically important. Almost always a number value, the primary key is aunique way to refer to a particular record. For example, your phonenumber has no inherent value but is uniquely a way to reach you.Pengaturcaraan PHPIndexes, Keys, andAUTO_INCREMENTTwo concepts closely related todatabase design are indexes and keys.An index in a database is a way ofrequesting that the database keep aneye on the values of a specificcolumn or combination of columns.The end result of this is improvedperformance when retrievingrecords but slightly hinderedperformance when inserting orupdating them. 11
  • 12. Pengaturcaraan PHP 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 PHPA tables primary key is an artificial way to refer to a record and should abideby three rules:- It must always have a value- That value must never change.- That value must be unique foreach record in the table 12
  • 13. Using the mysql client Pengaturcaraan PHPPengaturcaraan PHPThe mysql client is accessed from a command-line interface, beit the Terminal application in Linux or Mac OS X, or a DOS prompt inWindows. It can take several arguments up front, including theusername, password, and hostname (computer name or URL). Youestablish these arguments like so: 13
  • 14. Pengaturcaraan PHP 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 PHPWithin the mysql client, every statement or SQL command needs to beterminated 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 overseveral lines within the mysql client, to make it easier to read. 14
  • 15. Pengaturcaraan PHPIf you are using MySQL hosted on anothercomputer, such as a Web host, thatsystems administrator should provide youwith access and you may need to useanother interface tool, such asphpMyAdmin. 15
  • 16. Pengaturcaraan PHPPengaturcaraan PHP 16
  • 17. Pengaturcaraan PHPPengaturcaraan PHPSince the mysql client is a command-line tool, you may not be able to useit if you are working with an ISPs or Web hosts server. Here are twothings you can try:- Telnet or SSH into the remote server and then use mysql.- Install the MySQL software on your computer and use themysql client to connect to the remote server by specifying it asthe hostname (mysql -u username -p -h www.site.com). 17
  • 18. Pengaturcaraan PHPIf neither of these options work, you have other choices,beginning with phpMyAdmin. A popular open source toolwritten in PHP, phpMyAdmin, provides a Web-based interfacefor MySQL. Available from the http://www.phpmyadmin.net Website, this software is so common that many Web hostingcompanies offer it as the default way for their users tointerface with a MySQL database.Pengaturcaraan PHPIf you cannot access MySQL through the mysql client, you can still dopractically everything with phpMyAdmin. The SQL tab in the latest versionallows you to directly type in SQL commands, although many commoncommands have their own shortcuts in the program. 18
  • 19. Pengaturcaraan PHPThe good people at MySQLhave other tools available fordownload, including the MySQLQuery Browser, which will letyou interact with the serverthrough a graphical interface.If this isnt to your liking, thereare dozens of others available,from third parties, if you searchthe 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 anddown arrows to scroll through previously entered commands. Thiscan save you time when working with a database. 19
  • 20. Creating Databases and Tables Pengaturcaraan PHPPengaturcaraan PHPThe syntax for creating a new database using SQL and MySQL is: 20
  • 21. Pengaturcaraan PHP 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.Create and select the new database.The first line creates the database, assuming that you are logged intomysql as a user with permission to create new databases.The second line tells MySQL that you want to work within this databasefrom here on out. Remember that within the mysql client, you mustterminate every SQL command with a semicolon, although thesesemicolons arent technically part of SQL itself. If you are using a hostingcompanys MySQL, they will probably create the database for you. 21
  • 22. Create the users table.This step takes the designfor the users table andintegrates that within theCREATE table syntax.The order in which you enterthe columns here will dictatethe order in which thecolumns appear in the table. Step 4 Confirm 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. 22
  • 23. Pengaturcaraan PHPDESCRIBE tablename, which you might see in other resources, is thesame statement: Inserting Records Pengaturcaraan PHP 23
  • 24. Pengaturcaraan PHPWith that in mind, there are two formats for inserting data. With thefirst, you specify the columns to be used:Using this structure, you can add rows of records, populating only thecolumns that matter. The result will be that any columns not given a value willbe treated as NULL or given a default value, if that was defined. Note that if acolumn cannot have a NULL value, it was set as NOTNULL, not specifying avalue will cause an error.Pengaturcaraan PHPThe second format for inserting records is not to specify anycolumns at all but to include values for every one.If you use this second method, you must specify a value, even if itsNULL, for every column. If there are six columns in the table, you mustlist six values. Failure to match the number of values to the number ofcolumns will cause an error. For this and other reasons, the first formatof inserting records is generally preferable. 24
  • 25. Pengaturcaraan PHP MySQL also allows you to insert multiple rows at one time, separating each record by a comma: Pengaturcaraan PHPInserting Data into a TableThe following steps can be used toinsert data into a table.Two functions are used in both cases. Iuse the NOW() function to set theregistration_date as this moment. Noticethe function is not enclosed byquotation marks.Another function, SHA(), is used tostore an encrypted form of thepassword. Its available in versions4.0.2 and later of MySQL. If you havean earlier version, use MD5() instead ofSHA(). 25
  • 26. Step 2Insert several values into theusers table.Since MySQL allows you toinsert multiple values at once,you can take advantage of thisand fill up the table with records. Pengaturcaraan PHPThe SHA() function is one way to encryptdata. This function creates an encryptedstring that is always exactly 40 characterslong, which is why I set the users tablespassword column as CHAR(40). SHA() is aone-way encryption technique, meaningthat it cannot be reversed. Its useful forstoring sensitive data that need not beviewed in an unencrypted form again, but itsobviously not a good choice for sensitive datathat should be protected but later viewed likecredit card numbers.If you are not using a version of MySQL laterthan 4.0.1, you can use the MD5() functioninstead, and set the password column asCHAR(32). This function does the same task,using a different algorithm, and returns a32-character long string. 26
  • 27. Pengaturcaraan PHPThe NOW() function is handyfor date, time, and timestampcolumns, since it will insert thecurrent date and time on theserver for that field.Pengaturcaraan PHPWhen using any function in a SQL statement, do not place it withinquotation marks. You also must not have any spaces between thefunctions name and the following parenthesis so NOW() not NOW (). 27
  • 28. Pengaturcaraan PHPIf you need to insert a value containing a single quotation mark, escape itwith a backslash: Selecting Data Pengaturcaraan PHP 28
  • 29. Pengaturcaraan PHPNow that the database has some records in it, you can begin toretrieve the information with the most used of all SQL terms,SELECT. This type of query returns rows of records that matchcertain criteria, using the syntax:Pengaturcaraan PHP The simplest SELECT query is: The asterisk means that you want to view every column. 29
  • 30. Pengaturcaraan PHPYour other choice would be to specify the columns to be returned,with each separated from the next by a comma.Pengaturcaraan PHPThere are a few benefits to being explicit about which columns areselected. The first is performance: theres no reason to fetch columnsyou will not be using.The second is order: you can return columns in an order other thantheir layout in the table.Third, it allows you to manipulate the values in those columns usingfunctions. 30
  • 31. Pengaturcaraan PHPRetrieve all the data from the users table. This very basic SQL commandwill retrieve every column of every row stored within that table. Pengaturcaraan PHPRetrieve just the first and last names from users.Instead of showing the data from every field in the users table, you can use theSELECT statement to limit yourself to only the pertinent information. 31
  • 32. Pengaturcaraan PHP Using ConditionalsPengaturcaraan PHP 32
  • 33. Pengaturcaraan PHPThe problem with the SELECT statement as I have used it thus far is that itwill automatically retrieve every record. While this isnt a big issue whendealing with a few rows of information, it will greatly hinder the performance ofyour database as the number of records grows. To improve the efficiency ofyour SELECT statements, you can use different conditionals in an almostlimitless number of combinations. These conditionals use the SQL termWHERE and are written much as youd write a conditional in PHP.The MySQL Operators table lists the most common operators you would usewithin a WHERE conditional. These MySQL operators are frequently, but notexclusively, used with WHERE expressions.Operator Meaning= equals< less than> greater than<= less than or equal to>= greater than or equal to!= not equal toIS NOT NULL has a valueIS NULL does not have a valueBETWEEN within a rangeNOT BETWEEN outside of a rangeOR(also ||) where one of two conditionals is trueAND(also &&) where both conditionals are trueNOT(also !) where the condition is not true 33
  • 34. Pengaturcaraan PHPThese operators can be used together, along with parentheses, to createmore complex expressions.Pengaturcaraan PHPTo demonstrate using conditionals, Ill retrieve more specific data from thesitename database. The examples that follow will be just a few of thepossibilities.Select the records for every user registered on a specific date. 34
  • 35. Pengaturcaraan PHPSelect all the first names of users whose last name is Simpson.Here Im just returning one field (first_name) for each row. The returnedrecords themselves are determined by the value of another field (last_name).Pengaturcaraan PHPSelect everything from every record in the users table that does not havean 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 NULLterms, and therefore would not match this condition. Such a case would,however, match SELECT * FROM users WHERE email = ; 35
  • 36. Pengaturcaraan PHPSelect the record in which the password is password.Since the stored passwords were encrypted with the SHA() function, you canfind 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 PHPYou can also use the IN and NOT IN operators to determine if a columnsvalue is or is not one of a listed set of values. 36
  • 37. Using LIKE and NOT LIKE Pengaturcaraan PHPPengaturcaraan PHPUsing numbers, dates, and NULLs in conditionals is astraightforward process, but strings can be trickier. You can checkfor string equality with a query such as: 37
  • 38. Pengaturcaraan PHP If you wanted to match a persons last name that could be Smith or Smiths or 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 PHPTo demonstrate using the LIKE term, Ill retrieve more specific data from thesitename database. The examples that follow will be just a few of thepossibilities.Select all of the records in which the last name starts with Bank. 38
  • 39. Pengaturcaraan PHPSelect the name for every record whose email address is not of the formsomething@authors.com.If I want to rule out certain possibilities, I can use NOT LIKE with the wildcard.Pengaturcaraan PHPWildcard charactersThe wildcard characters can be used at the front and/or back of a string inyour queries.SELECT * FROM users WHERE user_name =‘%_smith% 39
  • 40. Sorting and Limiting Query Results Pengaturcaraan PHPPengaturcaraan PHPWhereas the WHERE conditional places restrictions on what records arereturned, the ORDER BY clause will affect how those records arepresented. Much as listing the columns of a table arranges the returnedorder, ORDER BY structures the entire list. When you do not dictate theorder of the returned data, it will be presented to you in somewhatunpredictable ways, although probably on the primary key in ascendingorder. 40
  • 41. Pengaturcaraan PHPThe default order when using ORDER BY is ascending (abbreviatedASC), meaning that numbers increase from small to large and datesgo from older to most recent. You can reverse this order by specifyingDESC.Pengaturcaraan PHPYou can even order the returned values by multiple columns.Here, I select all of the users in alphabetical order by last name. 41
  • 42. Pengaturcaraan PHPIn this example, I display all of the users in alphabetical order by last nameand then first name.In this query, the effect would be that every row is returned, first ordered bythe last_name, and then by first_name within the last_names. The effect is mostevident among the Simpsons.Pengaturcaraan PHP Using ORDER BY with WHERE You 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 42
  • 43. Pengaturcaraan PHPAnother SQL term you can add to your query statement is LIMIT. UnlikeWHERE, which affects which records to return, or ORDER BY, whichdecides how those records are sorted, LIMIT states how many records toreturn. 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 inPHP, the indexes in databases begin at 0 when it comes to LIMITs, so 10 isthe 11th record.Pengaturcaraan PHPYou can use LIMIT with WHERE and/or ORDER BY, appending it tothe 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 willminimize the amount of data to handle when it comes to the mysql client oryour PHP scripts. As a rule, when writing queries, there is never any reasonto return columns or rows you will not use. 43
  • 44. Pengaturcaraan PHPYou 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 descendingorder. Then, to see just the most recent five, I apply a LIMIT 5 to the query. Pengaturcaraan PHPHere I select the second person to register.This may look strange, but its just a good application of the information learnedso far. First I order all of the records by registration_date ascending, so the firstpeople 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. 44
  • 45. Pengaturcaraan PHPDisplaying multiple pagesThe LIMIT x, y clause is most frequently used when displaying multiple pagesof query results where you would want to show the first 20 results, then thesecond 20, and so forth. Updating and Deleting Data Pengaturcaraan PHP 45
  • 46. Pengaturcaraan PHPOnce your tables contain some data, you have the option of changingexisting records. The most frequent reason for doing this would be ifinformation were entered incorrectly — or in the case of user information, ifdata gets changed, such as a last name or email address, and that needsto 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. 46
  • 47. Pengaturcaraan PHPNormally you will want to use a WHERE clause to specify what rowsto affect; otherwise, the change would be applied to every row.The primary key — which should never change — can be areference point in WHERE clauses, even if every other field needsto be altered.Pengaturcaraan PHPNext, I will update the record.To change the email address, I use an UPDATE query, being certain tospecify 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 wereaffected. 47
  • 48. Pengaturcaraan PHP Protecting against accidental UPDATEs To protect yourself against accidentally updating too many rows, apply a LIMIT clause to your UPDATEs. UPDATE users SET email =mike@authors.com WHERE user_id = 17 LIMIT 1Pengaturcaraan PHPAnother step you can easily take on existing data is to entirely remove it fromthe database. To do this, you use the DELETE command.Note that once you have deleted a record, there is no way of retrieving it, soyou 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 youwill delete all of the data in a table. The query DELETE FROM tablename willempty out a table, while still retaining its structure. Similarly, the commandTRUNCATE TABLE tablename will delete an entire table (both the recordsand the structure) and then re-create the structure. The end result is thesame, but this method is faster and safer 48
  • 49. Pengaturcaraan PHPNow delete the record.As with the update, MySQL will report on the successful execution of the queryand how many rows were affected.At this point, there is no way of reinstating the deleted records unless youbacked up the database beforehand.Pengaturcaraan PHP Deleting all the data in a table To delete all of the data in a table, as well as the table itself, use DROP TABLE: DROP TABLE tablename Deleting an entire database To delete an entire database, including every table therein and all of its data, use DROP DATABASE: DROP DATABASE databasenameAdding 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 49
  • 50. Using Text and Numeric Functions Pengaturcaraan PHPPengaturcaraan PHPUsing FunctionsFunctions — such as NOW() and SHA() — are just the tip of the iceberg.Most of the functions discussed here are used with SELECT queries toformat and alter the returned data, but you may use MySQL functionsin any number of different queries.To use any function, you need to modify your query so that you specifyto which column or columns the function should be applied. 50
  • 51. Pengaturcaraan PHP To specify multiple columns, you can write a query like either of these:Text FunctionsThe first group of functions I will demonstrate are those meant for manipulatingthe various text and character columns. Most of the functions in this categoryare listed in the table. Function Usage Purpose CONCAT() CONCAT(x, y,...) Creates a new string of the form xy. LENGTH() LENGTH(column) Returns the length of the value stored in the column. LEFT() LEFT(column, x) Returns the leftmost x characters from a columns value. RIGHT() RIGHT(column, x) Returns the rightmost x characters from a columns value. TRIM() TRIM(column) Trims excess spaces from the beginning and end of the stored value. UPPER() UPPER(column) Capitalizes the entire stored string. LOWER() LOWER(column) Turns the stored string into an all-lowercase format. SUBSTRING() SUBSTRING(column, Returns length characters from column beginning with start start, length) (indexed from 0). 51
  • 52. Pengaturcaraan PHPCONCAT(), perhaps the most useful of the text functions, deserves specialattention. The CONCAT() function accomplishes concatenation, for whichPHP uses the period. The syntax for concatenation requires you to place,within parentheses, the various values you want assembled, in order andseparated by commas:Pengaturcaraan PHPWhile you can — and normally will — apply CONCAT() to columns, you canalso incorporate strings, entered within single quotation marks. To format apersons name as Surname, First from two columns, you would use: 52
  • 53. Pengaturcaraan PHP Because concatenation normally returns a new form of a column, its an excellent time to use an alias.Pengaturcaraan PHPExample 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 youdont use an alias, the returned datas column heading is very literal and oftenunwieldy. 53
  • 54. Pengaturcaraan PHPExample 2Concatenate the names while using an alias.To use an alias, just add AS aliasname after the item to be renamed. Thealias will be the new title for the returned data. Pengaturcaraan PHPExample 3Find the longest last name.This query first determines the length of each last name and calls that L. Thenthe whole list is sorted by that value from highest to lowest, and the stringlength and first name of the first row is returned. 54
  • 55. Pengaturcaraan PHPColumns and stringsFunctions can be equally applied to both columns and manually enteredstrings. For example, the following is perfectly acceptable:SELECT UPPER (makemebig)Pengaturcaraan PHPNumeric FunctionsBesides the standard math operators that MySQL uses (for addition,subtraction, multiplication, and division), there are about two dozenfunctions dedicated to formatting and performing calculations on numericvalues. The table lists the most common of these, some of which I willdemonstrate shortly. 55
  • 56. Pengaturcaraan PHPFunction Usage PurposeABS() ABS(x) Returns the absolute value of x.CEILING() CEILING(x) Returns the next-highest integer based upon the value of x.FLOOR() FLOOR(x) Returns the integer value of x.FORMAT() FORMAT(x, Returns x formatted as a number with y decimal places and commas inserted y) every three spaces.MOD() MOD(x, y) Returns the remainder of dividing x by y (either or both can be a column).RAND() RAND() Returns a random number between 0 and 1.0.ROUND() ROUND(x, y) Returns the number x rounded to y decimal places.SIGN() SIGN(x) Returns a value indicating whether a number is negative (–1), zero (0), or positive (+1).SQRT() SQRT(x) Calculates the square root of x. Pengaturcaraan PHPI want to specifically mention three of these functions: FORMAT(), ROUND(),and RAND(). The first — which is not technically number specific — turns anynumber into a more conventionally formatted layout. For example, if you storedthe cost of a car as 20198.20, FORMAT(car_cost, 2) would turn that numberinto the more common 20,198.20. 56
  • 57. Pengaturcaraan PHPROUND() will take one value, presumably from a column, and round thatto a specified number of decimal places. If no decimal places areindicated, it will round the number to the nearest integer.If more decimal places are indicated than exist in the original number, theremaining spaces are padded with zeros (to the right of the decimal point).Pengaturcaraan PHPThe RAND() function, as you might infer, is used for returning randomnumbers 57
  • 58. Pengaturcaraan PHP 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 PHPUsing Numeric FunctionsHere I display a number, formatting the amount as dollars.Using the FORMAT() function, as just described, with CONCAT(), you can turnany number into a currency format as you might display it in a Web page. 58
  • 59. Pengaturcaraan PHPNext, retrieve a random email address from the table. Date and Time FunctionsPengaturcaraan PHP 59
  • 60. Function Usage PurposeHOUR() HOUR(column) Returns just the hour value of a stored date.MINUTE() MINUTE(column) Returns just the minute value of a stored date.SECOND() SECOND(column) Returns just the second value of a stored date.DAYNAME() DAYNAME(column) Returns the name of the day for a date value.DAYOFMONTH() DAYOFMONTH(column) Returns just the numerical day value of a stored date.MONTHNAME() MONTHNAME(column) Returns the name of the month in a date value.MONTH() MONTH(column) Returns just the numerical month value of a stored date.YEAR() YEAR(column) Returns just the year value of a stored date. ADDDATE(column,ADDDATE() Returns the value of x units added to column. INTERVAL x type) SUBDATE(column,SUBDATE() Returns the value of x units subtracted from column. INTERVAL x type)CURDATE() CURDATE() Returns the current date.CURTIME() CURTIME() Returns the current time.NOW() NOW() Returns the current date and time. Returns the number of seconds since the epoch until theUNIX_TIMESTAMP() UNIX_TIMESTAMP(date) current moment or until the date specified. Pengaturcaraan PHPUsing 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 themonth.The DAY() function returns the day of the month part of a date column. So seeingif the returned result is equal to some value is an easy way to restrict whatrecords are selected. 60
  • 61. Pengaturcaraan PHP 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.ADDDATE() and SUBDATE()The ADDDATE() and SUBDATE() functions, which are synonyms for DATE_ADD() andDATE_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. Thex 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 thevalue stored in the date column. 61
  • 62. Pengaturcaraan PHP Formatting There 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:Term Usage Example%e Day of the month 1-31%d Day of the month, two digit 01-31%D Day with suffix 1st-31st%W Weekday name Sunday-Saturday%a Abbreviated weekday name Sun-Sat%c Month number 1-12%m Month number, two digit 01-12%M Month name January-December%b Month name, abbreviated Jan-Dec%Y Year 2002%y Year 02%l Hour 1-12 (lowercase L)%h Hour, two digit 01-12%k Hour, 24-hour clock 0-23%H Hour, 24-hour clock, two digit 00-23%i Minutes 00-59%S Seconds 00-59%r Time 8:17:02 PM%T Time, 24-hour clock 20:17:02%p AM or PM AM or PM 62
  • 63. Pengaturcaraan PHPAssuming that a column called the_date has the date and time of2005-04-30 23:07:45 stored in it, common formatting tasks andresults would be:Time (11:07:45 PM)Pengaturcaraan PHPTime without seconds (11:07 PM) Date (April 30th, 2005) 63
  • 64. Pengaturcaraan PHPHere, I return the current date and time as Month DD, YYYYHH:MM.Using the NOW() function, which returns the current date andtime, I can practice my formatting to see what results are returned.Pengaturcaraan PHPNext, I display the current time, using 24-hour notation. 64
  • 65. EndPengaturcaraan PHP 65