A database is a separate application that stores a collection of data. A Relational DataBase Management System (RDBMS) is a software that' Enables you to implement a database with tables, columns, and inde(es.
A database is a separate application that stores a collection of data. A Relational DataBase Management System (RDBMS) is a software that' Enables you to implement a database with tables, columns, and inde(es.
A database is a separate application that stores a collection of data. A Relational DataBase Management System (RDBMS) is a software that' Enables you to implement a database with tables, columns, and inde(es.
A database is a separate application that stores a collection of data.
Each database has one or more distinct APIs for creating, accessing, managing, searching, and replicating the data it holds. Other kinds of data stores can be used, such as files on the file system or large hash tables in memory but data fetching and writing would not be so fast and easy with those type of systems. So now a days we use relational database management systems (!"#S$ to store and manager huge %olume of data. &his is called relational database because all the data is stored into different tables and relations are established using primary keys or other keys known as foreign keys. A Relational DataBase Management System (RDBMS) is a software that' Enables you to implement a database with tables, columns, and inde(es. )uarantees the eferential Integrity between rows of %arious tables. *pdates the inde(es automatically. Interprets an S+, -uery and combines information from %arious tables. RDBMS Terminology: "efore we proceed to e(plain #yS+, database system, lets re%ise few definitions related to database. Database: A database is a collection of tables, with related data. Table: A table is a matri( with data. A table in a database looks like a simple spreadsheet. Column: One column (data element$ contains data of one and the same kind, for e(ample the column postcode. Row: A row (. tuple, entry or record$ is a group of related data, for e(ample the data of one subscription. Redundancy: Storing data twice, redundantly to make the system faster. Primary Key: A primary key is uni-ue. A key %alue can not occur twice in one table. /ith a key you can find at most one row. Foreign Key: A foreign key is the linking pin between two tables. Comound Key: A compound key (composite key$ is a key that consists of multiple columns, because one column is not sufficiently uni-ue. !nde": An inde( in a database resembles an inde( at the back of a book. Re#erential !ntegrity: eferential Integrity makes sure that a foreign key %alue always points to an e(isting row. MySQL Database: #yS+, is a fast, easy0to0use !"#S used being used for many small and big businesses. #yS+, is de%eloped, marketed, and supported by #yS+, A", which is a Swedish company. #yS+, is becoming so popular because of many good reasons. #yS+, is released under an open0source license. So you ha%e nothing to pay to use it. #yS+, is a %ery powerful program in its own right. It handles a large subset of the functionality of the most e(pensi%e and powerful database packages. #yS+, uses a standard form of the well0known S+, data language. #yS+, works on many operating systems and with many languages including P1P, PE,, 2, 233, 4A5A etc. #yS+, works %ery -uickly and works well e%en with large data sets. #yS+, is %ery friendly to P1P, the most appreciated language for web de%elopment. #yS+, supports large databases, up to 67 million rows or more in a table. &he default file si8e limit for a table is 9)", but you can increase this (if your operating system can handle it$ to a theoretical limit of : million terabytes (&"$. #yS+, is customi8able. &he open source )P, license allows programmers to modify the #yS+, software to fit their own specific en%ironments. Before You Begin: "efore you begin this tutorial you should ha%e a basic knowledge of the information co%ered in our P1P and 1&#, tutorials. &his tutorial focuses hea%ily on using #yS+, in a P1P en%ironment. #any e(amples gi%en in this tutorial will be useful for P1P Programmers. MySQL Installation - Linux and Windows Ad%ertisements Downloading MySQL: All downloads for #yS+, are located at #yS+, !ownloads. Pick the %ersion number for MySQL Community Server you want and, as e(actly as possible, the platform you want. Installing MySQL on Linux/Unix &he recommended way to install #yS+, on a ,inu( system is %ia P#. #yS+, A" makes the following P#s a%ailable for download on its web site' MyS$% & &he #yS+, database ser%er, which manages databases and tables, controls user access, and processes S+, -ueries. MyS$%&client & #yS+, client programs, which makes it possible to connect to, and interact with, the ser%er. MyS$%&de'el & ,ibraries and header files that come in handy when compiling other programs that use #yS+,. MyS$%&s(ared & Shared libraries for the #yS+, client MyS$%&benc( & "enchmark and performance testing tools for the #yS+, database ser%er. &he #yS+, P#s listed here are all built on a SuSE ,inu( system, but they.ll usually work on other ,inu( %ariants with no difficulty. ;ow follow the following steps to proceed for installation' <. ,ogin to the system using root user. =. Switch to the directory containing the P#s' >. Install the #yS+, database ser%er by e(ecuting the following command. emember to replace the filename in italics with the file name of your P#. [root@host]# rpm -i MySQL-5.0.9-0.i386.rpm Abo%e command takes care of installing #yS+, ser%er, creating a user of #yS+,, creating necessary configuration and starting #yS+, ser%er automatically. ?ou can find all the #yS+, related binaries in @usr@bin and @usr@sbin. All the tables and databases will be created in @%ar@lib@mys-l directory. 9. &his is optional but recommended step to install the remaining P#s in the same manner' [root@host]# rpm -i MySQL-client-5.0.9-0.i386.rpm [root@host]# rpm -i MySQL-deel-5.0.9-0.i386.rpm [root@host]# rpm -i MySQL-sh!red-5.0.9-0.i386.rpm [root@host]# rpm -i MySQL-"ench-5.0.9-0.i386.rpm Installing MySQL on Windows: !efault installation on any %ersion of /indows is now much easier than it used to be, as #yS+, now comes neatly packaged with an installer. Simply download the installer package, un8ip it anywhere, and run setup.e(e. !efault installer setup.e(e will walk you through the tri%ial process and by default will install e%erything under 2'Amys-l. &est the ser%er by firing it up from the command prompt the first time. )o to the location of the mys-ld ser%er, which is probably 2'Amys-lAbin, and type' mys#ld.e$e --console )*T+: If you are on ;& then you will ha%e to use mys-ld0nt.e(e instead of mys-ld.e(e If all went well, you will see some messages about startup and Inno!". If not, you may ha%e a permissions issue. #ake sure that the directory that holds your data is accessible to whate%er user (probably mys-l$ the database processes run under. #yS+, will not add itself to the start menu, and there is no particularly nice )*I way to stop the ser%er either. &herefore, if you tend to start the ser%er by double clicking the mys-ld e(ecutable, you should remember to halt the process by hand by using mys-ladmin, &ask ,ist, &ask #anager, or other /indows0specific means. Verifying MySQL Installation: After #yS+, has been successfully installed, the base tables ha%e been initiali8ed, and the ser%er has been started, you can %erify that all is working as it should %ia some simple tests. ,se t(e mys-ladmin ,tility to *btain Ser'er Status: *se mys-ladmin binary to check ser%er %ersion. &his binary would be a%ailable in @usr@bin on linu( and in 2'Amys-lAbin on windows. [root@host]# mys#l!dmin --ersion It will produce following result on ,inu(. It may %ary depending on your installation' mys#l!dmin %er 8.&3 'istri" 5.0.9-0( )or redh!t-lin*$-+n* on i386 If you do not get such message then there may be some problem in your installation and you would need some help to fi( it. +"ecute simle S$% commands using MyS$% Client: ?ou can connect to your #yS+, ser%er by using #yS+, client using mys-l command. At this momemnt you do not need to gi%e any password as by default it will be set to blank. So Bust use following command [root@host]# mys#l It should be rewarded with a mys-lC prompt. ;ow you are connected to the #yS+, ser%er and you can e(ecute all the S+, command at mys-lC prompt as follows. mys#l, S-./ '01020S3S4 5----------5 6 '!t!"!se 6 5----------5 6 mys#l 6 6 test 6 5----------5 & ro7s in set 80.93 sec: Post-installation Steps: #yS+, ships with a blank password for the root #yS+, user. As soon as you ha%e successfully installed the database and client you need to set a root password as follows' [root@host]# mys#l!dmin -* root p!ss7ord ;ne7<p!ss7ord;4 ;ow to make a connection to your #yS+, ser%er you would ha%e to use following command' [root@host]# mys#l -* root -p 3nter p!ss7ord=>>>>>>> *ni( users will also want to put your #yS+, directory in your PA&1, so you wonDt ha%e to keep typing out the full path e%ery time you want to use the command0line client. Eor bash, it would be something like' e$port ?01-@A?01-=B*srB"in=B*srBs"in Running MySQL at boot time: If you want to run #yS+, ser%er at boot time then make sure you ha%e following entry in @etc@rc.local file BetcBinit.dBmys#ld st!rt Also,you should ha%e mys-ld binary in @etc@init.d@ directory. Running and Shutting down MySQL Server: Eirst check if your #yS+, ser%er is running or not. ?ou can use following command to check this' ps -e) 6 +rep mys#ld If your #yS-l is running then you will see mys-ld process listed out in your result. If ser%er is not running then you can start it by using following command' root@ho!t# cd B*srB"in .Bs!)e<mys#ld C ;ow if you want to shutdown an already running #yS+, ser%er then you can do it by using following command' root@ho!t# cd B*srB"in .Bmys#l!dmin -* root -p sh*tdo7n 3nter p!ss7ord= >>>>>> Setting Up a MySQL User Accounts: Eor adding a new user to #yS+, you Bust need to add a new entry to user table in database mys-l. "elow is an e(ample of adding new user guest with SE,E2&, I;SE& and *P!A&E pri%ileges with the password guest./0 the S+, -uery is ' root@host# mys#l -* root -p 3nter p!ss7ord=>>>>>>> mys#l, *se mys#l4 '!t!"!se ch!n+ed mys#l, DES3F1 DE1. *ser 8host( *ser( p!ss7ord( select<pri( insert<pri( *pd!te<pri: %0LG3S 8Hloc!lhostH( H+*estH( ?0SS/.F'8H+*est9&3H:( HIH( HIH( HIH:4 Q*ery .J( 9 ro7 !))ected 80.&0 sec: mys#l, KLGS- ?FD%DL3L3S4 Q*ery .J( 9 ro7 !))ected 80.09 sec: mys#l, S3L3M1 host( *ser( p!ss7ord KF.M *ser /-3F3 *ser @ H+*estH4 5-----------5---------5------------------5 6 host 6 *ser 6 p!ss7ord 6 5-----------5---------5------------------5 6 loc!lhost 6 +*est 6 6)8c99N"58)&ce9e 6 5-----------5---------5------------------5 9 ro7 in set 80.00 sec: /hen adding a new user remember to encrypt the new password using PASS/O!($ function pro%ided by #yS+,. As you can see in the abo%e e(ample the password mypass is encrypted to Ff:c<<9b6:f=ceGe. ;otice the E,*S1 PI5I,E)ES statement. &his tells the ser%er to reload the grant tables. If you donDt use it then you wonDt be able to connect to mys-l using the new user account at least until the ser%er is rebooted. ?ou can also specify other pri%ileges to a new user by setting the %alues of following columns in user table to D?D when e(ecuting the I;SE& -uery or you can update them later using *P!A&E -uery. SelectHpri% InsertHpri% *pdateHpri% !eleteHpri% 2reateHpri% !ropHpri% eloadHpri% ShutdownHpri% ProcessHpri% EileHpri% )rantHpri% eferencesHpri% Inde(Hpri% AlterHpri% Another way of adding user account is by using )A;& S+, commandI Eollowing e(ample will ada user 1ara with password 1ara./0 for a particular database called T,T*R!2%S. root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se mys#l4 '!t!"!se ch!n+ed mys#l, LF0E1 S3L3M1(DES3F1(G?'013('3L313(MF3013('F.? -, .E 1G1.FD0LS.> -, 1. HO!r!H@Hloc!lhostH -, D'3E1DKD3' 2I HO!r!9&3H4 &his will also create an entry in mys-l database table called user. )*T+: #yS+, does not terminate a command until you gi%e a semi colon (I$ at the end of S+, command. The /etc/my.cnf File Confguration: #ost of the cases you should not touch this file. "y default it will ha%e following entries' [mys#ld] d!t!dir@B!rBli"Bmys#l socPet@B!rBli"Bmys#lBmys#l.socP [mys#l.serer] *ser@mys#l "!sedir@B!rBli" [s!)e<mys#ld] err-lo+@B!rBlo+Bmys#ld.lo+ pid-)ile@B!rBr*nBmys#ldBmys#ld.pid 1ere you can specify a different directory for error log, otherwise you should not change any entry in this table. Administrative MySQL Command: 1ere is the list of important #yS+, command which you will use time to time to work with #yS+, database' ,S+ Databasename ' &his will be used to select a particular database in #yS+, workarea. S3*4 D2T2B2S+S: ,ists the databases that are accessible by the #yS+, !"#S. S3*4 T2B%+S: Shows the tables in the database once a database has been selected with the use command. S3*4 C*%,M)S FR*M tablename: Shows the attributes, types of attributes, key information, whether ;*,, is permitted, defaults, and other information for a table. S3*4 !)D+5 FR*M tablename: Presents the details of all inde(es on the table, including the PI#A? JE?. S3*4 T2B%+ ST2T,S %!K+ tablename67: eports details of the #yS+, !"#S performance and statistics. #yS+, works %ery well in combination of %arious programming languages like PE,, 2, 233, 4A5A and P1P. Out of these languages, P1P is the most popular one because of its web application de%elopment capabilities. &his tutorial focuses hea%ily on using #yS+, in a P1P en%ironment. If you are interested in #yS+, with PE, then you can look into PE, and #yS+, &utorial. P1P pro%ides %arious functions to access #yS+, database and to manipulate data records inside #yS+, database. ?ou would re-uire to call P1P functions in the same way you call any other P1P function. &he P1P functions for use with #yS+, ha%e the following general format' mys#l<function8!l*e(!l*e(...:4 &he second part of the function name is specific to the function, usually a word that describes what the function does. &he following are two of the functions which we will use in our tutorial mys#li<connect8Aconnect:4 mys#li<#*ery8Aconnect(;SQL st!tement;:4 Eollowing e(ample shows a generic sysnta( of P1P to call any #yS+, function. Qhtml, Qhe!d, Qtitle,?-? 7ith MySQLQBtitle, QBhe!d, Q"ody, QRphp Aret!l @ mys#l<function8!l*e( [!l*e(...]:4 i)8 SAret!l : T die 8 ;3rror= ! rel!ted error mess!+e; :4 U BB .ther7ise MySQL or ?-? St!tements R, QB"ody, QBhtml, Starting from ne(t chapter we will see all the important #yS+, functionality along with P1P. MySQL Connection using mysql binary: ?ou can establish #yS+, database using mys-l binary at command prompt. +"amle: 1ere is a simple e(ample to connect to #yS+, ser%er from command prompt' [root@host]# mys#l -* root -p 3nter p!ss7ord=>>>>>> &his will gi%e you mys-lC command prompt where you will be able to e(ecute any S+, command. Eollowing is the result of abo%e command' /elcome to the MySQL monitor. Momm!nds end 7ith 4 or V+. Io*r MySQL connection id is &85NW60 to serer ersion= 5.0.9 1ype Hhelp4H or HVhH )or help. 1ype HVcH to cle!r the "*))er. In abo%e e(ample we ha%e used root as a user but you can use any other user. Any user will be able to perform all the S+, operation which are allowed to that user. ?ou can disconnect from #yS+, database any time using e"it command at mys-lC prompt. mys#l, e$it 2ye MySQL Connection using PHP Script: P1P pro%ides mys-l8connect() function to open a database connection. &his function takes fi%e parameters and returns a #yS+, link identifier on success, or EA,SE on failure. Synta": connection mys#l<connect8serer(*ser(p!ss7d(ne7<linP(client<)l!+:4 Parameter Descrition ser%er Optional 0 &he host name running database ser%er. If not specified then default %alue is local(ost:090:. user Optional 0 &he username accessing the database. If not specified then default is the name of the user that owns the ser%er process. passwd Optional 0 &he password of the user accessing the database. If not specified then default is an empty password. newHlink Optional 0 If a second call is made to mys-lHconnect($ with the same arguments, no new connection will be establishedI instead, the identifier of the already opened connection will be returned. clientHflags Optional 0 A combination of the following constants' #?S+,H2,IE;&HSS, 0 *se SS, encryption #?S+,H2,IE;&H2O#PESS 0 *se compression protocol #?S+,H2,IE;&HI);OEHSPA2E 0 Allow space after function names #?S+,H2,IE;&HI;&EA2&I5E 0 Allow interacti%e timeout seconds of inacti%ity before closing the connection ?ou can disconnect from #yS+, database anytime using another P1P function mys-l8close(). &his function takes a single parameter which is a connection returned by mys-l8connect() function. Synta": "ool mys#l<close 8 reso*rce AlinP<identi)ier :4 If a resource is not specified then last opened database is closed. &his function returns true if it closes connection successfully otherwise it returns false. +"amle: &ry out following e(ample to connect to a #yS+, ser%er' Qhtml, Qhe!d, Qtitle,Monnectin+ MySQL SererQBtitle, QBhe!d, Q"ody, QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ H+*estH4 Ad"p!ss @ H+*est9&3H4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U echo HMonnected s*ccess)*llyH4 mys#l<close8Aconn:4 R, QB"ody, QBhtml, Create Database using mysqladmin: ?ou would need special pri%ilege to create or to delete a #yS+, database. So assuming you ha%e access to root user, you can create any database using mys-l mys-ladmin binary. +"amle: 1ere is a simple e(ample to create database called T,T*R!2%S' [root@host]# mys#l!dmin -* root -p cre!te 1G1.FD0LS 3nter p!ss7ord=>>>>>> &his will create a #yS+, database &*&OIA,S. Create Database using PHP Script: P1P uses mys-l8-uery function to create or delete a #yS+, database. &his function takes two parameters and returns &*E on success or EA,SE on failure. Synta": "ool mys#l<#*ery8 s#l( connection :4 Parameter Descrition s-l e-uired 0 S+, -uery to create or delete a #yS+, database connection Optional 0 if not specified then last opened connection by mys-lHconnect will be used. +"amle: &ry out following e(ample to create a database' Qhtml, Qhe!d, Qtitle,Mre!tin+ MySQL '!t!"!seQBtitle, QBhe!d, Q"ody, QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U echo HMonnected s*ccess)*llyQ"r B,H4 As#l @ HMF3013 '01020S3 1G1.FD0LSH4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not cre!te d!t!"!se= H . mys#l<error8::4 U echo ;'!t!"!se 1G1.FD0LS cre!ted s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, QB"ody, QBhtml, Drop Database using mysqladmin: ?ou would need special pri%ilege to create or to delete a #yS+, database. So assuming you ha%e access to root user, you can create any database using mys-l mys-ladmin binary. "e careful while deleting any database because it will lose your all the data a%ailable in your database. 1ere is an e(ample to delete a database created in pre%ious chapter' [root@host]# mys#l!dmin -* root -p drop 1G1.FD0LS 3nter p!ss7ord=>>>>>> &his will gi%e you a warning and it will confirm if you really want to delete this database or not. 'roppin+ the d!t!"!se is potenti!lly ! ery "!d thin+ to do. 0ny d!t! stored in the d!t!"!se 7ill "e destroyed. 'o yo* re!lly 7!nt to drop the H1G1.FD0LSH d!t!"!se [yBE] y '!t!"!se ;1G1.FD0LS; dropped Drop Database using PHP Script: P1P uses mys-l8-uery function to create or delete a #yS+, database. &his function takes two parameters and returns &*E on success or EA,SE on failure. Synta": "ool mys#l<#*ery8 s#l( connection :4 Parameter Descrition s-l e-uired 0 S+, -uery to create or delete a #yS+, database connection Optional 0 if not specified then last opened connection by mys-lHconnect will be used. +"amle: &ry out following e(ample to delete a database' Qhtml, Qhe!d, Qtitle,'eletin+ MySQL '!t!"!seQBtitle, QBhe!d, Q"ody, QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U echo HMonnected s*ccess)*llyQ"r B,H4 As#l @ H'F.? '01020S3 1G1.FD0LSH4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not delete d!t!"!se= H . mys#l<error8::4 U echo ;'!t!"!se 1G1.FD0LS deleted s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, QB"ody, QBhtml, 42R)!)7: /hile deleting a database using P1P script, it does not prompt you for any confirmation. So be careful while deleting a #yS+, database. Once you get connection with #yS+, ser%er,it is re-uired to select a particular database to work with. &his is because there may be more than one database a%ailable with #yS+, Ser%er. Selecting MySQL Database from Command Prompt: &his is %ery simple to select a particular database from mys-lC prompt. ?ou can use S+, command use to select a particular database. +"amle: 1ere is an e(ample to select database called T,T*R!2%S' [root@host]# mys#l -* root -p 3nter p!ss7ord=>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, ;ow you ha%e selected &*&OIA,S database and all the subse-uent operations will be performed on &*&OIA,S database. )*T+: all the database name, table names, table fields name are case sensiti%e. So you would ha%e to use proper names while gi%ing any S+, command. Selecting MySQL Database Using PHP Script: P1P pro%ides function mys-l8select8db to select a database. It returns &*E on success or EA,SE on failure. Synta": "ool mys#l<select<d"8 d"<n!me( connection :4 Parameter Descrition dbHname e-uired 0 #yS+, !atabase name to be selected connection Optional 0 if not specified then last opened connection by mys-lHconnect will be used. +"amle: 1ere is the e(ample showing you how to select a database. Qhtml, Qhe!d, Qtitle,Selectin+ MySQL '!t!"!seQBtitle, QBhe!d, Q"ody, QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ H+*estH4 Ad"p!ss @ H+*est9&3H4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U echo HMonnected s*ccess)*llyH4 mys#l<select<d"8 H1G1.FD0LSH :4 mys#l<close8Aconn:4 R, QB"ody, QBhtml, Properly defining the fields in a table is important to the o%erall optimi8ation of your database. ?ou should use only the type and si8e of field you really need to useI donDt define a field as <7 characters wide if you know youDre only going to use = characters. &hese types of fields (or columns$ are also referred to as data types, after the tye o# data you will be storing in those fields. #yS+, uses many different data types, broken into three categories' numeric, date and time, and string types. Numeric Data Types: #yS+, uses all the standard A;SI S+, numeric data types, so if youDre coming to #yS+, from a different database system, these definitions will look familiar to you. &he following list shows the common numeric data types and their descriptions. !)T 0 A normal0si8ed integer that can be signed or unsigned. If signed, the allowable range is from 0=<9K9:>F9: to =<9K9:>F9K. If unsigned, the allowable range is from 7 to 9=G9GFK=G6. ?ou can specify a width of up to << digits. T!);!)T 0 A %ery small integer that can be signed or unsigned. If signed, the allowable range is from 0<=: to <=K. If unsigned, the allowable range is from 7 to =66. ?ou can specify a width of up to 9 digits. SM2%%!)T 0 A small integer that can be signed or unsigned. If signed, the allowable range is from 0>=KF: to >=KFK. If unsigned, the allowable range is from 7 to F66>6. ?ou can specify a width of up to 6 digits. M+D!,M!)T 0 A medium0si8ed integer that can be signed or unsigned. If signed, the allowable range is from 0:>::F7: to :>::F7K. If unsigned, the allowable range is from 7 to <FKKK=<6. ?ou can specify a width of up to G digits. B!7!)T 0 A large integer that can be signed or unsigned. If signed, the allowable range is from 0G==>>K=7>F:69KK6:7: to G==>>K=7>F:69KK6:7K. If unsigned, the allowable range is from 7 to <:99FK997K>K7G66<F<6. ?ou can specify a width of up to << digits. F%*2T(M<D) 0 A floating0point number that cannot be unsigned. ?ou can define the display length (#$ and the number of decimals (!$. &his is not re-uired and will default to <7,=, where = is the number of decimals and <7 is the total number of digits (including decimals$. !ecimal precision can go to =9 places for a E,OA&. D*,B%+(M<D) 0 A double precision floating0point number that cannot be unsigned. ?ou can define the display length (#$ and the number of decimals (!$. &his is not re-uired and will default to <F,9, where 9 is the number of decimals. !ecimal precision can go to 6> places for a !O*",E. EA, is a synonym for !O*",E. D+C!M2%(M<D) 0 An unpacked floating0point number that cannot be unsigned. In unpacked decimals, each decimal corresponds to one byte. !efining the display length (#$ and the number of decimals (!$ is re-uired. ;*#EI2 is a synonym for !E2I#A,. Date and Time Types: &he #yS+, date and time datatypes are' D2T+ 0 A date in ????0##0!! format, between <77707<07< and GGGG0<=0><. Eor e(ample, !ecember >7th, <GK> would be stored as <GK>0<=0>7. D2T+T!M+ 0 A date and time combination in ????0##0!! 11'##'SS format, between <77707<07< 77'77'77 and GGGG0<=0 >< =>'6G'6G. Eor e(ample, >'>7 in the afternoon on !ecember >7th, <GK> would be stored as <GK>0<=0>7 <6'>7'77. T!M+ST2MP 0 A timestamp between midnight, 4anuary <, <GK7 and sometime in =7>K. &his looks like the pre%ious !A&E&I#E format, only without the hyphens between numbersI >'>7 in the afternoon on !ecember >7th, <GK> would be stored as <GK><=>7<6>777 ( ????##!!11##SS $. T!M+ 0 Stores the time in 11'##'SS format. ;+2R(M) 0 Stores a year in =0digit or 90digit format. If the length is specified as = (for e(ample ?EA(=$$, ?EA can be <GK7 to =7FG (K7 to FG$. If the length is specified as 9, ?EA can be <G7< to =<66. &he default length is 9. String Types: Although numeric and date types are fun, most data youDll store will be in string format. &his list describes the common string datatypes in #yS+,. C32R(M) 0 A fi(ed0length string between < and =66 characters in length (for e(ample 21A(6$$, right0padded with spaces to the specified length when stored. !efining a length is not re-uired, but the default is <. =2RC32R(M) 0 A %ariable0length string between < and =66 characters in lengthI for e(ample 5A21A(=6$. ?ou must define a length when creating a 5A21A field. B%*B or T+5T 0 A field with a ma(imum length of F66>6 characters. ",O"s are L"inary ,arge ObBectsL and are used to store large amounts of binary data, such as images or other types of files. Eields defined as &EM& also hold large amounts of dataI the difference between the two is that sorts and comparisons on stored data are case sensiti%e on ",O"s and are not case sensiti%e in &EM& fields. ?ou do not specify a length with ",O" or &EM&. T!);B%*B or T!);T+5T 0 A ",O" or &EM& column with a ma(imum length of =66 characters. ?ou do not specify a length with &I;?",O" or &I;?&EM&. M+D!,MB%*B or M+D!,MT+5T 0 A ",O" or &EM& column with a ma(imum length of <FKKK=<6 characters. ?ou do not specify a length with #E!I*#",O" or #E!I*#&EM&. %*)7B%*B or %*)7T+5T 0 A ",O" or &EM& column with a ma(imum length of 9=G9GFK=G6 characters. ?ou do not specify a length with ,O;)",O" or ,O;)&EM&. +),M 0 An enumeration, which is a fancy term for list. /hen defining an E;*#, you are creating a list of items from which the %alue must be selected (or it can be ;*,,$. Eor e(ample, if you wanted your field to contain LAL or L"L or L2L, you would define your E;*# as E;*# (DAD, D"D, D2D$ and only those %alues (or ;*,,$ could e%er populate that field. Create MySQL Tables Ad%ertisements &he table creation command re-uires' ;ame of the table ;ames of fields !efinitions for each field Synta": 1ere is generic S+, synta( to create a #yS+, table' MF3013 102L3 t!"le<n!me 8col*mn<n!me col*mn<type:4 ;ow we will create following table in T,T*R!2%S database. t*tori!ls<t"l8 t*tori!l<id DE1 E.1 EGLL 0G1.<DEMF3M3E1( t*tori!l<title %0FM-0F8900: E.1 EGLL( t*tori!l<!*thor %0FM-0F8N0: E.1 EGLL( s*"mission<d!te '013( ?FDM0FI J3I 8 t*tori!l<id : :4 1ere few items need e(planation' Eield Attribute )*T ),%% is being used because we do not want this field to be ;*,,. SO if user will try to create a record with ;*,, %alue then #yS+, will raise an error. Eield Attribute 2,T*8!)CR+M+)T tells to #yS+, to go ahead and add the ne(t a%ailable number to the id field. Jeyword PR!M2R; K+; is used to define a column as primary key. ?ou can use multiple columns separated by comma to define a primary key. Creating Tables from Command Prompt: &his is easy to create a #yS+, table from mys-lC prompt. ?ou will use S+, command CR+2T+ T2B%+ to create a table. +"amle: 1ere is an e(ample which creates tutorials8tbl' root@host# mys#l -* root -p 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, MF3013 102L3 t*tori!ls<t"l8 -, t*tori!l<id DE1 E.1 EGLL 0G1.<DEMF3M3E1( -, t*tori!l<title %0FM-0F8900: E.1 EGLL( -, t*tori!l<!*thor %0FM-0F8N0: E.1 EGLL( -, s*"mission<d!te '013( -, ?FDM0FI J3I 8 t*tori!l<id : -, :4 Q*ery .J( 0 ro7s !))ected 80.96 sec: mys#l, )*T+: #yS+, does not terminate a command until you gi%e a semi colon (I$ at the end of S+, command. Creating Tables Using PHP Script: &o create new table in any e(isting database you would need to use P1P function mys-l8-uery(). ?ou will pass its second argument with proper S+, command to create a table. +"amle: 1ere is an e(ample to create a table using P1P script' Qhtml, Qhe!d, Qtitle,Mre!tin+ MySQL 1!"lesQBtitle, QBhe!d, Q"ody, QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U echo HMonnected s*ccess)*llyQ"r B,H4 As#l @ ;MF3013 102L3 t*tori!ls<t"l8 ;. ;t*tori!l<id DE1 E.1 EGLL 0G1.<DEMF3M3E1( ;. ;t*tori!l<title %0FM-0F8900: E.1 EGLL( ;. ;t*tori!l<!*thor %0FM-0F8N0: E.1 EGLL( ;. ;s*"mission<d!te '013( ;. ;?FDM0FI J3I 8 t*tori!l<id ::4 ;4 mys#l<select<d"8 H1G1.FD0LSH :4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not cre!te t!"le= H . mys#l<error8::4 U echo ;1!"le cre!ted s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, QB"ody, QBhtml, It is %ery easy to drop an e(isting #yS+, table. "ut you need to be %ery careful while deleting any e(isting table because data lost will not be reco%ered after deleting a table. Synta": 1ere is generic S+, synta( to drop a #yS+, table' 'F.? 102L3 t!"le<n!me 4 Dropping Tables from Command Prompt: &his needs Bust to e(ecute DR*P T2B%+ S+, command at mys-lC prompt. +"amle: 1ere is an e(ample which deletes tutorials8tbl' root@host# mys#l -* root -p 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, 'F.? 102L3 t*tori!ls<t"l Q*ery .J( 0 ro7s !))ected 80.8 sec: mys#l, Dropping Tables Using PHP Script: &o drop an e(isting table in any database you would need to use P1P function mys-l8-uery(). ?ou will pass its second argument with proper S+, command to drop a table. +"amle: Qhtml, Qhe!d, Qtitle,Mre!tin+ MySQL 1!"lesQBtitle, QBhe!d, Q"ody, QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U echo HMonnected s*ccess)*llyQ"r B,H4 As#l @ ;'F.? 102L3 t*tori!ls<t"l;4 mys#l<select<d"8 H1G1.FD0LSH :4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not delete t!"le= H . mys#l<error8::4 U echo ;1!"le deleted s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, QB"ody, QBhtml, &o insert data into #yS+, table you would need to use S+, !)S+RT !)T* command. ?ou can insert data into #yS+, table by using mys-lC prompt or by using any script like P1P. Synta": 1ere is generic S+, synta( of I;SE& I;&O command to insert data into #yS+, table' DES3F1 DE1. t!"le<n!me 8 )ield9( )ield&(...)ieldE : %0LG3S 8 !l*e9( !l*e&(...!l*eE :4 &o insert string data types it is re-uired to keep all the %alues into double or single -uote, for e(ample'0 >'alue>. Inserting Data from Command Prompt: &his will use S+, I;SE& I;&O command to insert data into #yS+, table tutorialsHtbl +"amle: Eollowing e(ample will create > records into tutorials8tbl table' root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, DES3F1 DE1. t*tori!ls<t"l -,8t*tori!l<title( t*tori!l<!*thor( s*"mission<d!te: -,%0LG3S -,8;Le!rn ?-?;( ;Xohn ?o*l;( E./8::4 Q*ery .J( 9 ro7 !))ected 80.09 sec: mys#l, DES3F1 DE1. t*tori!ls<t"l -,8t*tori!l<title( t*tori!l<!*thor( s*"mission<d!te: -,%0LG3S -,8;Le!rn MySQL;( ;0"d*l S;( E./8::4 Q*ery .J( 9 ro7 !))ected 80.09 sec: mys#l, DES3F1 DE1. t*tori!ls<t"l -,8t*tori!l<title( t*tori!l<!*thor( s*"mission<d!te: -,%0LG3S -,8;X0%0 1*tori!l;( ;S!nY!y;( H&00W-05-06H:4 Q*ery .J( 9 ro7 !))ected 80.09 sec: mys#l, )*T+: Please note that all the arrow signs (0C$ are not part of S+, command they are indicating a new line and they are created automatically by #yS+, prompt while pressing enter key without gi%ing a semi colon at the end of each line of the command. In the abo%e e(ample we ha%e not pro%ided tutorialHid because at the time of table create we had gi%en A*&OHI;2E#E;& option for this field. So #yS+, takes care of inserting these I!s automatically. 1ere )*4() is a #yS+, function which returns current date and time. Inserting Data Using PHP Script: ?ou can use same S+, I;SE& I;&O command into P1P function mys-l8-uery() to insert data into a #yS+, table. +"amle: &his e(ample will take three parameters from user and will insert them into #yS+, table' Qhtml, Qhe!d, Qtitle,0dd Ee7 Fecord in MySQL '!t!"!seQBtitle, QBhe!d, Q"ody, QRphp i)8isset8A<?.S1[H!ddH]:: T Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U i)8S +et<m!+ic<#*otes<+pc8: : T At*tori!l<title @ !ddsl!shes 8A<?.S1[Ht*tori!l<titleH]:4 At*tori!l<!*thor @ !ddsl!shes 8A<?.S1[Ht*tori!l<!*thorH]:4 U else T At*tori!l<title @ A<?.S1[Ht*tori!l<titleH]4 At*tori!l<!*thor @ A<?.S1[Ht*tori!l<!*thorH]4 U As*"mission<d!te @ A<?.S1[Hs*"mission<d!teH]4 As#l @ ;DES3F1 DE1. t*tori!ls<t"l ;. ;8t*tori!l<title(t*tori!l<!*thor( s*"mission<d!te: ;. ;%0LG3S ;.
;8HAt*tori!l<titleH(HAt*tori!l<!*thorH(HAs*"mission<d!teH:;4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not enter d!t!= H . mys#l<error8::4 U echo ;3ntered d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 U else T R, Q)orm method@;post; !ction@;QRphp A<?-?<S3LK R,;, Qt!"le 7idth@;600; "order@;0; cellsp!cin+@;9; cellp!ddin+@;&;, Qtr, Qtd 7idth@;&50;,1*tori!l 1itleQBtd, Qtd, Qinp*t n!me@;t*tori!l<title; type@;te$t; id@;t*tori!l<title;, QBtd, QBtr, Qtr, Qtd 7idth@;&50;,1*tori!l 0*thorQBtd, Qtd, Qinp*t n!me@;t*tori!l<!*thor; type@;te$t; id@;t*tori!l<!*thor;, QBtd, QBtr, Qtr, Qtd 7idth@;&50;,S*"mission '!te [ yyyy-mm-dd ]QBtd, Qtd, Qinp*t n!me@;s*"mission<d!te; type@;te$t; id@;s*"mission<d!te;, QBtd, QBtr, Qtr, Qtd 7idth@;&50;, QBtd, Qtd, QBtd, QBtr, Qtr, Qtd 7idth@;&50;, QBtd, Qtd, Qinp*t n!me@;!dd; type@;s*"mit; id@;!dd; !l*e@;0dd 1*tori!l;, QBtd, QBtr, QBt!"le, QB)orm, QRphp U R, QB"ody, QBhtml, /hile doing data insert its best practice to use function get8magic8-uotes8gc() to check if current configuration for magic -uote is set or not. If this function returns false then use function addslas(es() to add slashes before -uotes. ?ou can put many %alidations around to check if entered data is correct or not and can take appropriate action. &he S+, S+%+CT command is used to fetch data from #yS+, database. ?ou can use this command at mys-lC prompt as well as in any script like P1P. Synta": 1ere is generic S+, synta( of SE,E2& command to fetch data from #yS+, table' S3L3M1 )ield9( )ield&(...)ieldE t!"le<n!me9( t!"le<n!me&... [/-3F3 Ml!*se] [.KKS31 M ][LDMD1 E] ?ou can use one or more tables separated by comma to include %arious condition using a /1EE clause. "ut /1EE clause is an optional part of SE,E2& command. ?ou can fetch one or more fields in a single SE,E2& command. ?ou can specify star (N$ in place of fields. In this case SE,E2& will return all the fields ?ou can specify any condition using /1EE clause. ?ou can specify an offset using *FFS+T from where SE,E2& will start returning records. "y default offset is 8ero ?ou can limit the number of returned using %!M!T attribute. Fetching Data from Command Prompt: &his will use S+, SE,E2& command to fetch data from #yS+, table tutorialsHtbl +"amle: Eollowing e(ample will return all the records from tutorials8tbl table' root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, S3L3M1 > )rom t*tori!ls<t"l 5-------------5----------------5----------------- 5-----------------5 6 t*tori!l<id 6 t*tori!l<title 6 t*tori!l<!*thor 6 s*"mission<d!te 6 5-------------5----------------5----------------- 5-----------------5 6 9 6 Le!rn ?-? 6 Xohn ?o*l 6 &00W-05- &9 6 6 & 6 Le!rn MySQL 6 0"d*l S 6 &00W-05- &9 6 6 3 6 X0%0 1*tori!l 6 S!nY!y 6 &00W-05- &9 6 5-------------5----------------5----------------- 5-----------------5 3 ro7s in set 80.09 sec: mys#l, Fetching Data Using PHP Script: ?ou can use same S+, SE,E2& command into P1P function mys-l8-uery(). &his function is used to e(ecute S+, command and later another P1P function mys-l8#etc(8array() can be used to fetch all the selected data. &his function returns row as an associati%e array, a numeric array, or both. &his function returns EA,SE if there are no more rows. "elow is a simple e(ample to fetch records from tutorials8tbl table. Example: &ry out following e(ample to display all the records from tutorialsHtbl table. QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U As#l @ HS3L3M1 t*tori!l<id( t*tori!l<title( t*tori!l<!*thor( s*"mission<d!te KF.M t*tori!ls<t"lH4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not +et d!t!= H . mys#l<error8::4 U 7hile8Aro7 @ mys#l<)etch<!rr!y8Aret!l( MISQL<0SS.M:: T echo ;1*tori!l D' =TAro7[Ht*tori!l<idH]U Q"r, ;. ;1itle= TAro7[Ht*tori!l<titleH]U Q"r, ;. ;0*thor= TAro7[Ht*tori!l<!*thorH]U Q"r, ;. ;S*"mission '!te = TAro7[Hs*"mission<d!teH]U Q"r, ;. ;--------------------------------Q"r,;4 U echo ;Ketched d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, &he content of the rows are assigned to the %ariable Orow and the %alues in row are then printed. )*T+: Always remember to put curly brackets when you want to insert an array %alue directly into a string. In abo%e e(ample the constant M;S$%82SS*C is used as the second argument to P1P function mys-l8#etc(8array(), so that it returns the row as an associati%e array. /ith an associati%e array you can access the field by using their name instead of using the inde(. P1P pro%ides another function called mys-l8#etc(8assoc() which also returns the row as an associati%e array. Example: &ry out following e(ample to display all the records from tutorialHtbl table using mys-lHfetchHassoc($ function. QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U As#l @ HS3L3M1 t*tori!l<id( t*tori!l<title( t*tori!l<!*thor( s*"mission<d!te KF.M t*tori!ls<t"lH4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not +et d!t!= H . mys#l<error8::4 U 7hile8Aro7 @ mys#l<)etch<!ssoc8Aret!l:: T echo ;1*tori!l D' =TAro7[Ht*tori!l<idH]U Q"r, ;. ;1itle= TAro7[Ht*tori!l<titleH]U Q"r, ;. ;0*thor= TAro7[Ht*tori!l<!*thorH]U Q"r, ;. ;S*"mission '!te = TAro7[Hs*"mission<d!teH]U Q"r, ;. ;--------------------------------Q"r,;4 U echo ;Ketched d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, ?ou can also use the constant M;S$%8),M, as the second argument to P1P function mys-lHfetchHarray($. &his will cause the function to return an array with numeric inde(. Example: &ry out following e(ample to display all the records from tutorialsHtbl table using #?S+,H;*# argument. QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U As#l @ HS3L3M1 t*tori!l<id( t*tori!l<title( t*tori!l<!*thor( s*"mission<d!te KF.M t*tori!ls<t"lH4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not +et d!t!= H . mys#l<error8::4 U 7hile8Aro7 @ mys#l<)etch<!rr!y8Aret!l( MISQL<EGM:: T echo ;1*tori!l D' =TAro7[0]U Q"r, ;. ;1itle= TAro7[9]U Q"r, ;. ;0*thor= TAro7[&]U Q"r, ;. ;S*"mission '!te = TAro7[3]U Q"r, ;. ;--------------------------------Q"r,;4 U echo ;Ketched d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, All the abo%e three e(amples will produce same result. Releasing Memory: Its a good practice to release cursor memory at the end of each SE,E2& statement. &his can be done by using P1P function mys-l8#ree8result(). "elow is the e(ample to show how it has to be used. Example: &ry out following e(ample QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U As#l @ HS3L3M1 t*tori!l<id( t*tori!l<title( t*tori!l<!*thor( s*"mission<d!te KF.M t*tori!ls<t"lH4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not +et d!t!= H . mys#l<error8::4 U 7hile8Aro7 @ mys#l<)etch<!rr!y8Aret!l( MISQL<EGM:: T echo ;1*tori!l D' =TAro7[0]U Q"r, ;. ;1itle= TAro7[9]U Q"r, ;. ;0*thor= TAro7[&]U Q"r, ;. ;S*"mission '!te = TAro7[3]U Q"r, ;. ;--------------------------------Q"r,;4 U mys#l<)ree<res*lt8Aret!l:4 echo ;Ketched d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, /hile fetching data you can write as comple( S+, as you like. Procedure will remain same as mentioned abo%e. MySQL WHERE Clause Ad%ertisements /e ha%e seen S+, S+%+CT command to fetch data from #yS+, table. /e can use a conditional clause called 43+R+ clause to filter out results. *sing /1EE clause we can specify a selection criteria to select re-uired records from a table. Synta": 1ere is generic S+, synta( of SE,E2& command with /1EE clause to fetch data from #yS+, table' S3L3M1 )ield9( )ield&(...)ieldE t!"le<n!me9( t!"le<n!me&... [/-3F3 condition9 [0E' [.F]] condition&..... ?ou can use one or more tables separated by comma to include %arious condition using a /1EE clause. "ut /1EE clause is an optional part of SE,E2& command. ?ou can specify any condition using /1EE clause. ?ou can specify more than one conditions using 2)D or *R operators. A /1EE clause can be used alongwith !E,E&E or *P!A&E S+, command also to specify a condition. &he 43+R+ clause works like a if condition in any programming language. &his clause is used to compare gi%en %alue with the field %alue a%ailable in #yS+l table. If gi%en %alue from outside is e-ual to the a%ailable field %alue in #yS+, table then it returns that row. 1ere is the list of operators which can be used with 43+R+ clause. Assume field A holds <7 and field " holds =7 then' *erator Descrition +"amle . 2hecks if the %alue of two operands is e-ual or not, if yes then condition becomes true. (A . "$ is not true. P. 2hecks if the %alue of two operands is e-ual or not, if %alues are not e-ual then condition becomes true. (A P. "$ is true. C 2hecks if the %alue of left operand is greater than the %alue of right operand, if yes then condition becomes true. (A C "$ is not true. Q 2hecks if the %alue of left operand is less than the %alue of right operand, if yes then condition becomes true. (A Q "$ is true. C. 2hecks if the %alue of left operand is greater than or e-ual to the %alue of right operand, if yes then condition becomes true. (A C. "$ is not true. Q. 2hecks if the %alue of left operand is less than or e-ual to the %alue of right operand, if yes then condition becomes true. (A Q. "$ is true. &he /1EE clause is %ery useful when you want to fetch selected rows from a table, Specially when you use MyS$% ?oin. 4oins are discussed in another chapter. It is a common practice to search records using Primary Key to make search fast. If gi%en condition does not match any record in the table then -uery would not return any row. Fetching Data from Command Prompt: &his will use S+, SE,E2& command with /1EE clause to fetch selected data from #yS+, table tutorialsHtbl +"amle: Eollowing e(ample will return all the records from tutorials8tbl table for which author name is San@ay' root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, S3L3M1 > )rom t*tori!ls<t"l /-3F3 t*tori!l<!*thor@HS!nY!yH4 5-------------5----------------5----------------- 5-----------------5 6 t*tori!l<id 6 t*tori!l<title 6 t*tori!l<!*thor 6 s*"mission<d!te 6 5-------------5----------------5----------------- 5-----------------5 6 3 6 X0%0 1*tori!l 6 S!nY!y 6 &00W- 05-&9 6 5-------------5----------------5----------------- 5-----------------5 9 ro7s in set 80.09 sec: mys#l, All the *nless performing a %!K+ comparison on a string, the comparison is not case sensiti%e. ?ou can make your search case sensiti%e using B!)2R; keyword as follows. root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, S3L3M1 > )rom t*tori!ls<t"l V /-3F3 2DE0FI t*tori!l<!*thor@Hs!nY!yH4 3mpty set 80.0& sec: mys#l, Fetching Data Using PHP Script: ?ou can use same S+, SE,E2& command with /1EE 2,A*SE into P1P function mys-l8-uery(). &his function is used to e(ecute S+, command and later another P1P function mys-l8#etc(8array() can be used to fetch all the selected data. &his function returns row as an associati%e array, a numeric array, or both. &his function returns EA,SE if there are no more rows. Example: Eollowing e(ample will return all the records from tutorials8tbl table for which author name is San@ay' QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U As#l @ HS3L3M1 t*tori!l<id( t*tori!l<title( t*tori!l<!*thor( s*"mission<d!te KF.M t*tori!ls<t"l /-3F3 t*tori!l<!*thor@;S!nY!y;H4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not +et d!t!= H . mys#l<error8::4 U 7hile8Aro7 @ mys#l<)etch<!rr!y8Aret!l( MISQL<0SS.M:: T echo ;1*tori!l D' =TAro7[Ht*tori!l<idH]U Q"r, ;. ;1itle= TAro7[Ht*tori!l<titleH]U Q"r, ;. ;0*thor= TAro7[Ht*tori!l<!*thorH]U Q"r, ;. ;S*"mission '!te = TAro7[Hs*"mission<d!teH]U Q"r, ;. ;--------------------------------Q"r,;4 U echo ;Ketched d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, &here may be a re-uirement where e(isting data in a #yS+, table need to be modified. ?ou can do so by using S+, ,PD2T+ command. &his will modify any field %alue of any #yS+, table. Synta": 1ere is generic S+, synta( of *P!A&E command to modify data into #yS+, table' G?'013 t!"le<n!me S31 )ield9@ne7-!l*e9( )ield&@ne7-!l*e& [/-3F3 Ml!*se] ?ou can update one or more field all together. ?ou can specify any condition using /1EE clause. ?ou can update %alues in a single table at a time. &he /1EE clause is %ery useful when you want to update selected rows in a table. Updating Data from Command Prompt: &his will use S+, *P!A&E command with /1EE clause to update selected data into #yS+, table tutorialsHtbl +"amle: Eollowing e(ample will update tutorial8title field for a record ha%ing tutorialHid as >. root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, G?'013 t*tori!ls<t"l -, S31 t*tori!l<title@HLe!rnin+ X0%0H -, /-3F3 t*tori!l<id@34 Q*ery .J( 9 ro7 !))ected 80.0N sec: Fo7s m!tched= 9 Mh!n+ed= 9 /!rnin+s= 0 mys#l, Updating Data Using PHP Script: ?ou can use S+, *P!A&E command with or without /1EE 2,A*SE into P1P function mys-l8-uery(). &his function will e(ecute S+, command in similar way it is e(ecuted at mys-lC prompt. Example: &ry out following e(ample to update tutorial8title field for a record ha%ing tutorialHid as >. QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U As#l @ HG?'013 t*tori!ls<t"l S31 t*tori!l<title@;Le!rnin+ X0%0; /-3F3 t*tori!l<id@3H4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not *pd!te d!t!= H . mys#l<error8::4 U echo ;Gpd!ted d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 If you want to delete a record from any #yS+, table then you can use S+, command D+%+T+ FR*M. ?ou can use this command at mys-lC prompt as well as in any script like P1P. Synta": 1ere is generic S+, synta( of !E,E&E command to delete data from a #yS+, table' '3L313 KF.M t!"le<n!me [/-3F3 Ml!*se] If /1EE clause is not specified then all the records will be deleted from the gi%en #yS+, table. ?ou can specify any condition using /1EE clause. ?ou can delete records in a single table at a time. &he /1EE clause is %ery useful when you want to delete selected rows in a table. Deleting Data from Command Prompt: &his will use S+, !E,E&E command with /1EE clause to delete selected data into #yS+, table tutorialsHtbl +"amle: Eollowing e(ample will delete a record into tutorialHtbl whose tutorialHid is >. root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, '3L313 KF.M t*tori!ls<t"l /-3F3 t*tori!l<id@34 Q*ery .J( 9 ro7 !))ected 80.&3 sec: mys#l, Deleting Data Using PHP Script: ?ou can use S+, !E,E&E command with or without /1EE 2,A*SE into P1P function mys-l8-uery(). &his function will e(ecute S+, command in similar way it is e(ecuted at mys-lC prompt. Example: &ry out following e(ample to delete a record into tutorialHtbl whose tutorialHid is >. QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U As#l @ H'3L313 KF.M t*tori!ls<t"l /-3F3 t*tori!l<id@3H4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not delete d!t!= H . mys#l<error8::4 U echo ;'eleted d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, /e ha%e seen S+, S+%+CT command to fetch data from #yS+, table. /e can also use a conditional clause called 43+R+ clause to select re-uired records. A /1EE clause with e-ual sign (.$ works fine where we want to do an e(act match. ,ike if LtutorialHauthor . DSanBayDL. "ut there may be a re-uirement where we want to filter out all the results where tutorialHauthor name should contain LBayL. &his can be handled using S+, %!K+ clause alongwith /1EE clause. If S+, ,IJE clause is used along with R characters then it will work like a meta character (N$ in *ni( while listing out all the files or directories at command prompt. /ithout a R character ,IJE clause is %ery similar to e-ual sign alongwith /1EE clause. Synta": 1ere is generic S+, synta( of SE,E2& command along with ,IJE clause to fetch data from #yS+, table' S3L3M1 )ield9( )ield&(...)ieldE t!"le<n!me9( t!"le<n!me&... /-3F3 )ield9 LDJ3 condition9 [0E' [.F]] )iled& @ Hsome!l*eH ?ou can specify any condition using /1EE clause. ?ou can use ,IJE clause alongwith /1EE clause. ?ou can use ,IJE clause in place of e-ual sign. /hen ,IJE is used alongwith R sign then it will work like a meta character search. ?ou can specify more than one conditions using 2)D or *R operators A /1EE...,IJE clause can be used alongwith !E,E&E or *P!A&E S+, command also to specify a condition. Using LIKE clause at Command Prompt: &his will use S+, SE,E2& command with /1EE...,IJE clause to fetch selected data from #yS+, table tutorialsHtbl +"amle: Eollowing e(ample will return all the records from tutorials8tbl table for which author name ends with @ay' root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, S3L3M1 > )rom t*tori!ls<t"l -, /-3F3 t*tori!l<!*thor LDJ3 HZY!yH4 5-------------5----------------5----------------- 5-----------------5 6 t*tori!l<id 6 t*tori!l<title 6 t*tori!l<!*thor 6 s*"mission<d!te 6 5-------------5----------------5----------------- 5-----------------5 6 3 6 X0%0 1*tori!l 6 S!nY!y 6 &00W-05- &9 6 5-------------5----------------5----------------- 5-----------------5 9 ro7s in set 80.09 sec: mys#l, Using LIKE clause inside PHP Script: ?ou can use similar synta( of /1EE...,IJE clause into P1P function mys-l8-uery(). &his function is used to e(ecute S+, command and later another P1P function mys-l8#etc(8array() can be used to fetch all the selected data if /1EE...,IJE clause is used along with SE,E2& command. "ut if /1EE...,IJE clause is being used with !E,E&E or *P!A&E command then no further P1P function call is re-uired. Example: &ry out following e(ample to return all the records from tutorials8tbl table for which author name contains @ay' QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U As#l @ HS3L3M1 t*tori!l<id( t*tori!l<title( t*tori!l<!*thor( s*"mission<d!te KF.M t*tori!ls<t"l /-3F3 t*tori!l<!*thor LDJ3 ;ZY!yZ;H4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not +et d!t!= H . mys#l<error8::4 U 7hile8Aro7 @ mys#l<)etch<!rr!y8Aret!l( MISQL<0SS.M:: T echo ;1*tori!l D' =TAro7[Ht*tori!l<idH]U Q"r, ;. ;1itle= TAro7[Ht*tori!l<titleH]U Q"r, ;. ;0*thor= TAro7[Ht*tori!l<!*thorH]U Q"r, ;. ;S*"mission '!te = TAro7[Hs*"mission<d!teH]U Q"r, ;. ;--------------------------------Q"r,;4 U echo ;Ketched d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, /e ha%e seen S+, S+%+CT command to fetch data from #yS+, table. /hen you select rows, the #yS+, ser%er is free to return them in any order, unless you instruct it otherwise by saying how to sort the result. "ut you sort a result set by adding an O!E "? clause that names the column or columns you want to sort by. Synta": 1ere is generic S+, synta( of SE,E2& command along with O!E "? clause to sort data from #yS+, table' S3L3M1 )ield9( )ield&(...)ieldE t!"le<n!me9( t!"le<n!me&... .F'3F 2I )ield9( [)ield&...] [0SM ['3SM]] ?ou can sort returned result on any field pro%ided that filed is being listed out. ?ou can sort result on more than one field. ?ou can use keyword AS2 or !ES2 to get result in ascending or descending order. "y default its ascending order. ?ou can use /1EE...,IJE clause in usual way to put condition. Using ORDER BY clause at Command Prompt: &his will use S+, SE,E2& command with O!E "? clause to fetch data from #yS+, table tutorialsHtbl +"amle: &ry out following e(ample which returns result in ascending order. root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, S3L3M1 > )rom t*tori!ls<t"l .F'3F 2I t*tori!l<!*thor 0SM 5-------------5----------------5----------------- 5-----------------5 6 t*tori!l<id 6 t*tori!l<title 6 t*tori!l<!*thor 6 s*"mission<d!te 6 5-------------5----------------5----------------- 5-----------------5 6 & 6 Le!rn MySQL 6 0"d*l S 6 &00W-05- &N 6 6 9 6 Le!rn ?-? 6 Xohn ?o*l 6 &00W-05- &N 6 6 3 6 X0%0 1*tori!l 6 S!nY!y 6 &00W-05- 06 6 5-------------5----------------5----------------- 5-----------------5 3 ro7s in set 80.N& sec: mys#l, 5erify all the author names are listed out in ascending order. Using ORDER BY clause inside PHP Script: ?ou can use similar synta( of O!E "? clause into P1P function mys-l8-uery(). &his function is used to e(ecute S+, command and later another P1P function mys-l8#etc(8array() can be used to fetch all the selected data. Example: &ry out following e(ample which returns result in descending order of tutorial author. QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U As#l @ HS3L3M1 t*tori!l<id( t*tori!l<title( t*tori!l<!*thor( s*"mission<d!te KF.M t*tori!ls<t"l .F'3F 2I t*tori!l<!*thor '3SMH4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not +et d!t!= H . mys#l<error8::4 U 7hile8Aro7 @ mys#l<)etch<!rr!y8Aret!l( MISQL<0SS.M:: T echo ;1*tori!l D' =TAro7[Ht*tori!l<idH]U Q"r, ;. ;1itle= TAro7[Ht*tori!l<titleH]U Q"r, ;. ;0*thor= TAro7[Ht*tori!l<!*thorH]U Q"r, ;. ;S*"mission '!te = TAro7[Hs*"mission<d!teH]U Q"r, ;. ;--------------------------------Q"r,;4 U echo ;Ketched d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, Using MySQL Joins Ad%ertisements &hus far we ha%e only been getting data from one table at a time. &his is fine for simple takes, but in most real world #yS+, usage you will often need to get data from multiple tables in a single -uery. ?ou can use multiple tables in your single S+, -uery. &he act of Boining in #yS+, refers to smashing two or more tables into a single table. ?ou can use 4OI;S in SE,E2&, *P!A&E and !E,E&E statements to Boin #yS+, tables. /e will see an e(ample of ,EE& 4OI; also which is different from simple #yS+, 4OI;. Using Joins at Command Prompt: Suppose we ha%e two tables tcount8tbl and tutorials8tbl in &*&OIA,S. A complete listing is gi%en below' +"amle: &ry out following e(amples' root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, S3L3M1 > KF.M tco*nt<t"l4 5-----------------5----------------5 6 t*tori!l<!*thor 6 t*tori!l<co*nt 6 5-----------------5----------------5 6 m!hr!n 6 &0 6 6 m!hn!O 6 EGLL 6 6 Xen 6 EGLL 6 6 Lill 6 &0 6 6 Xohn ?o*l 6 9 6 6 S!nY!y 6 9 6 5-----------------5----------------5 6 ro7s in set 80.09 sec: mys#l, S3L3M1 > )rom t*tori!ls<t"l4 5-------------5----------------5----------------- 5-----------------5 6 t*tori!l<id 6 t*tori!l<title 6 t*tori!l<!*thor 6 s*"mission<d!te 6 5-------------5----------------5----------------- 5-----------------5 6 9 6 Le!rn ?-? 6 Xohn ?o*l 6 &00W-05- &N 6 6 & 6 Le!rn MySQL 6 0"d*l S 6 &00W-05- &N 6 6 3 6 X0%0 1*tori!l 6 S!nY!y 6 &00W-05- 06 6 5-------------5----------------5----------------- 5-----------------5 3 ro7s in set 80.00 sec: mys#l, ;ow we can write a S+, -uery to Boin these two tables. &his -uery will select all the authors from table tutorials8tbl and will pickup corresponding number of tutorials fromtcount8tbl. mys#l, S3L3M1 !.t*tori!l<id( !.t*tori!l<!*thor( ".t*tori!l<co*nt -, KF.M t*tori!ls<t"l !( tco*nt<t"l " -, /-3F3 !.t*tori!l<!*thor @ ".t*tori!l<!*thor4 5-------------5-----------------5----------------5 6 t*tori!l<id 6 t*tori!l<!*thor 6 t*tori!l<co*nt 6 5-------------5-----------------5----------------5 6 9 6 Xohn ?o*l 6 9 6 6 3 6 S!nY!y 6 9 6 5-------------5-----------------5----------------5 & ro7s in set 80.09 sec: mys#l, Using Joins in PHP Script: ?ou can use any of the abo%e mentioned S+, -uery in P1P script. ?ou only need to pass S+, -uery into P1P function mys-l8-uery() and then you will fetch results in usual way. Example: &ry out following e(ample' QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U As#l @ HS3L3M1 !.t*tori!l<id( !.t*tori!l<!*thor( ".t*tori!l<co*nt KF.M t*tori!ls<t"l !( tco*nt<t"l " /-3F3 !.t*tori!l<!*thor @ ".t*tori!l<!*thorH4 mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not +et d!t!= H . mys#l<error8::4 U 7hile8Aro7 @ mys#l<)etch<!rr!y8Aret!l( MISQL<0SS.M:: T echo ;0*thor=TAro7[Ht*tori!l<!*thorH]U Q"r, ;. ;Mo*nt= TAro7[Ht*tori!l<co*ntH]U Q"r, ;. ;1*tori!l D'= TAro7[Ht*tori!l<idH]U Q"r, ;. ;--------------------------------Q"r,;4 U echo ;Ketched d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, MySQL LET J!I"# A #yS+, left Boin is different from a simple Boin. A #yS+, ,EE& 4OI; gi%es e(tra consideration to the table that is on the left. If I do a ,EE& 4OI;, I get all records that match in the same way and I; A!!I&IO; I get an e(tra record for each unmatched record in the left table of the Boin 0 thus ensuring (in my e(ample$ that e%ery A*&1O gets a mention' Example: &ry out following e(ample to understand ,EE& 4OI;' root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, S3L3M1 !.t*tori!l<id( !.t*tori!l<!*thor( ".t*tori!l<co*nt -, KF.M t*tori!ls<t"l ! L3K1 X.DE tco*nt<t"l " -, .E !.t*tori!l<!*thor @ ".t*tori!l<!*thor4 5-------------5-----------------5----------------5 6 t*tori!l<id 6 t*tori!l<!*thor 6 t*tori!l<co*nt 6 5-------------5-----------------5----------------5 6 9 6 Xohn ?o*l 6 9 6 6 & 6 0"d*l S 6 EGLL 6 6 3 6 S!nY!y 6 9 6 5-------------5-----------------5----------------5 3 ro7s in set 80.0& sec: ?ou would need to do more practice to become familiar with 4OI;S. &his is a but comple( concept in #yS+,@S+, and will become more clear while doing real e(amples. Handling MySQL "ULL $alues Ad%ertisements /e ha%e seen S+, S+%+CT command along with 43+R+ clause to fetch data from #yS+, table. "ut when we try to gi%e a condition which compare field or column %alue to ),%% it does not work properly. &o handle such situation #yS+, pro%ides three operators !S ),%%: operator returns true of column %alue is ;*,,. !S )*T ),%%: operator returns true of column %alue is not ;*,,. ABC operator compare %alues, which (unlike the . operator$ is true e%en for two ;*,, %alues 2onditions in%ol%ing ;*,, are special. ?ou cannot use . ;*,, or P. ;*,, to look for ;*,, %alues in columns. Such comparisons always fail because itDs impossible to tell whether or not they are true. E%en ;*,, . ;*,, fails. &o look for columns that are or are not ;*,,, use IS ;*,, or IS ;O& ;*,,. Using NULL values at Command Prompt: Suppose a table tcount8tbl in &*&OIA,S database and it contains two columns tutorial8aut(or and tutorial8count, where a ;*,, tutorialHcount indicates that the %alue is unknown' +"amle: &ry out following e(amples' root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, cre!te t!"le tco*nt<t"l -, 8 -, t*tori!l<!*thor !rch!r8N0: E.1 EGLL( -, t*tori!l<co*nt DE1 -, :4 Q*ery .J( 0 ro7s !))ected 80.05 sec: mys#l, DES3F1 DE1. tco*nt<t"l -, 8t*tori!l<!*thor( t*tori!l<co*nt: !l*es 8Hm!hr!nH( &0:4 mys#l, DES3F1 DE1. tco*nt<t"l -, 8t*tori!l<!*thor( t*tori!l<co*nt: !l*es 8Hm!hn!OH( EGLL:4 mys#l, DES3F1 DE1. tco*nt<t"l -, 8t*tori!l<!*thor( t*tori!l<co*nt: !l*es 8HXenH( EGLL:4 mys#l, DES3F1 DE1. tco*nt<t"l -, 8t*tori!l<!*thor( t*tori!l<co*nt: !l*es 8HLillH( &0:4 mys#l, S3L3M1 > )rom tco*nt<t"l4 5-----------------5----------------5 6 t*tori!l<!*thor 6 t*tori!l<co*nt 6 5-----------------5----------------5 6 m!hr!n 6 &0 6 6 m!hn!O 6 EGLL 6 6 Xen 6 EGLL 6 6 Lill 6 &0 6 5-----------------5----------------5 N ro7s in set 80.00 sec: mys#l, ?ou can see that . and P. do not work with ;*,, %alues as follows' mys#l, S3L3M1 > KF.M tco*nt<t"l /-3F3 t*tori!l<co*nt @ EGLL4 3mpty set 80.00 sec: mys#l, S3L3M1 > KF.M tco*nt<t"l /-3F3 t*tori!l<co*nt S@ EGLL4 3mpty set 80.09 sec: &o find records where the tutorialHcount column is or is not ;*,,, the -ueries should be written like this' mys#l, S3L3M1 > KF.M tco*nt<t"l -, /-3F3 t*tori!l<co*nt DS EGLL4 5-----------------5----------------5 6 t*tori!l<!*thor 6 t*tori!l<co*nt 6 5-----------------5----------------5 6 m!hn!O 6 EGLL 6 6 Xen 6 EGLL 6 5-----------------5----------------5 & ro7s in set 80.00 sec: mys#l, S3L3M1 > )rom tco*nt<t"l -, /-3F3 t*tori!l<co*nt DS E.1 EGLL4 5-----------------5----------------5 6 t*tori!l<!*thor 6 t*tori!l<co*nt 6 5-----------------5----------------5 6 m!hr!n 6 &0 6 6 Lill 6 &0 6 5-----------------5----------------5 & ro7s in set 80.00 sec: Handling NULL Values in PHP Script: ?ou can use if...else condition to prepare a -uery based on ;*,, %alue. Example: Eollowing e(ample take tutorialHcount from outside and then compare it with the %alue a%ailable in the table. QRphp Ad"host @ Hloc!lhost=3036H4 Ad"*ser @ HrootH4 Ad"p!ss @ Hrootp!ss7ordH4 Aconn @ mys#l<connect8Ad"host( Ad"*ser( Ad"p!ss:4 i)8S Aconn : T die8HMo*ld not connect= H . mys#l<error8::4 U i)8 isset8At*tori!l<co*nt :: T As#l @ HS3L3M1 t*tori!l<!*thor( t*tori!l<co*nt KF.M tco*nt<t"l /-3F3 t*tori!l<co*nt = At*tori!l<co*ntH4 U else T As#l @ HS3L3M1 t*tori!l<!*thor( t*tori!l<co*nt KF.M tco*nt<t"l /-3F3 t*tori!l<co*nt IS At*tori!l<co*ntH4 U mys#l<select<d"8H1G1.FD0LSH:4 Aret!l @ mys#l<#*ery8 As#l( Aconn :4 i)8S Aret!l : T die8HMo*ld not +et d!t!= H . mys#l<error8::4 U 7hile8Aro7 @ mys#l<)etch<!rr!y8Aret!l( MISQL<0SS.M:: T echo ;0*thor=TAro7[Ht*tori!l<!*thorH]U Q"r, ;. ;Mo*nt= TAro7[Ht*tori!l<co*ntH]U Q"r, ;. ;--------------------------------Q"r,;4 U echo ;Ketched d!t! s*ccess)*llyVn;4 mys#l<close8Aconn:4 R, ?ou ha%e seen #yS+, pattern matching with %!K+ DDDE. #yS+, supports another type of pattern matching operation based on regular e(pressions and the R+7+5P operator. If you are aware of P1P or PE, then its %ery simple for you to understand because this matching is %ery similar to those scripting regular e(pressions. Eollowing is the table of pattern which can be used along with R+7+5P operator. Pattern 4(at t(e attern matc(es S "eginning of string O End of string . Any single character T...U Any character listed between the s-uare brackets TS...U Any character not listed between the s-uare brackets p<Vp=Vp> AlternationI matches any of the patterns p<, p=, or p> N Wero or more instances of preceding element 3 One or more instances of preceding element XnY n instances of preceding element Xm,nY m through n instances of preceding element Examples: ;ow based on abo%e table you can de%ice %arious type of S+, -ueries to meet your re-uirements. 1ere IDm listing few for your understanding. 2onsider we ha%e a table called personHtbl and its ha%ing a field called name' +uery to find all the names starting with DstD mys#l, S3L3M1 n!me KF.M person<t"l /-3F3 n!me F3L3[? H\stH4 +uery to find all the names ending with DokD mys#l, S3L3M1 n!me KF.M person<t"l /-3F3 n!me F3L3[? HoPAH4 +uery to find all the names which contains DmarD mys#l, S3L3M1 n!me KF.M person<t"l /-3F3 n!me F3L3[? Hm!rH4 +uery to find all the names starting with a %owel and ending with DokD mys#l, S3L3M1 n!me KF.M person<t"l /-3F3 n!me F3L3[? H\[!eio*]6oPAH4 MySQL Transa%tions Ad%ertisements A transaction is a se-uential group of database manipulation operations, which is performed as if it were one single work unit. In other words, a transaction will ne%er be complete unless each indi%idual operation within the group is successful. If any operation within the transaction fails, the entire transaction will fail. Practically you will club many S+, -ueries into a group and you will e(ecute all of them together as a part of a transaction. Properties of Transactions: &ransactions ha%e the following four standard properties, usually referred to by the acronym A2I!' 2tomicity: ensures that all operations within the work unit are completed successfullyI otherwise, the transaction is aborted at the point of failure, and pre%ious operations are rolled back to their former state. Consistency: ensures that the database properly changes states upon a successfully committed transaction. !solation: enables transactions to operate independently of and transparent to each other. Durability: ensures that the result or effect of a committed transaction persists in case of a system failure. In #yS+,, transactions begin with the statement "E)I; /OJ and end with either a 2O##I& or a O,,"A2J statement. &he S+, commands between the beginning and ending statements form the bulk of the transaction. COMMIT and ROLLBACK: &hese two keywords Commit and RollbacF are mainly used for #yS+, &ransactions. /hen a successful transaction is completed, the 2O##I& command should be issued so that the changes to all in%ol%ed tables will take effect. If a failure occurs, a O,,"A2J command should be issued to return e%ery table referenced in the transaction to its pre%ious state. ?ou can control the beha%ior of a transaction by setting session %ariable called 2,T*C*MM!T. If A*&O2O##I& is set to < (the default$, then each S+, statement (within a transaction or not$ is considered a complete transaction, and committed by default when it finishes. /hen A*&O2O##I& is set to 7, by issuing the SE& A*&O2O##I&.7 command, the subse-uent series of statements acts like a transaction, and no acti%ities are committed until an e(plicit 2O##I& statement is issued. ?ou can e(ecute these S+, commands in P1P by using mys-l8-uery() function. Generic Example on Transaction &his se-uence of e%ents is independent of the programming language usedI the logical path can be created in whiche%er language you use to create your application. ?ou can e(ecute these S+, commands in P1P by using mys-l8-uery() function. .D "egin transaction by issuing S+, command B+7!) 4*RK /D Issue one or more S+, commands like SE,E2&, I;SE&, *P!A&E or !E,E&E 0D 2heck if there is no error and e%erything is according to your re-uirement. GD If there is any error then issue O,,"A2J command otherwise issue a 2O##I& command. Transaction-Safe Table Types in MySQL: ?ou can not use transactions directly, you can but they would not be sa%e and guaranteed. If you plan to use transactions in your #yS+, programming then you need to create your tables in a special way. &here are many type of tables which support transactions but most popular one is !nnoDB. Support for Inno!" tables re-uires a specific compilation parameter when compiling #yS+, from source. If your #yS+, %ersion does not ha%e Inno!" support, ask your Internet Ser%ice Pro%ider to build a %ersion of #yS+, with support for Inno!" table types, or download and install the #yS+,0#a( binary distribution for /indows or ,inu(@*;IM and work with the table type in a de%elopment en%ironment. If your #yS+, installation supports Inno!" tables, simply add a T;P+B!nnoDB definition to the table creation statement. Eor e(ample, the following code creates an Inno!" table called tcountHtbl' root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, cre!te t!"le tco*nt<t"l -, 8 -, t*tori!l<!*thor !rch!r8N0: E.1 EGLL( -, t*tori!l<co*nt DE1 -, : TYPE=InnoDB4 Q*ery .J( 0 ro7s !))ected 80.05 sec: 2heck following link to know more about ' Inno!" ?ou can use other table type like 7+M!)! or BDB but it depends on your installation if it supports these two types. #yS+, 2%T+R command is %ery useful when you want to change a name of your table, any table field or if you want to add or delete an e(isting column in a table. ,ets begin with creation of a table called testalter8tbl root@host# mys#l -* root -p p!ss7ord4 3nter p!ss7ord=>>>>>>> mys#l, *se 1G1.FD0LS4 '!t!"!se ch!n+ed mys#l, cre!te t!"le test!lter<t"l -, 8 -, i DE1( -, c M-0F89: -, :4 Q*ery .J( 0 ro7s !))ected 80.05 sec: mys#l, S-./ M.LGMES KF.M test!lter<t"l4 5-------5---------5------5-----5---------5-------5 6 Kield 6 1ype 6 E*ll 6 Jey 6 'e)!*lt 6 3$tr! 6 5-------5---------5------5-----5---------5-------5 6 i 6 int899: 6 I3S 6 6 EGLL 6 6 6 c 6 ch!r89: 6 I3S 6 6 EGLL 6 6 5-------5---------5------5-----5---------5-------5 & ro7s in set 80.00 sec: Dropping, Adding, or Repositioning a Column: Suppose you want to drop an e(isting column i from abo%e #yS+, table then you will use DR*P clause along with 2%T+R command as follows mys#l, 0L13F 102L3 test!lter<t"l 'F.? i4 A DR*P will not work if the column is the only one left in the table. &o add a column, use A!! and specify the column definition. &he following statement restores the i column to testalterHtbl mys#l, 0L13F 102L3 test!lter<t"l 0'' i DE14 After issuing this statement, testalter will contain the same two columns that it had when you first created the table, but will not ha%e -uite the same structure. &hatDs because new columns are added to the end of the table by default. So e%en though i originally was the first column in mytbl, now it is the last one' mys#l, S-./ M.LGMES KF.M test!lter<t"l4 5-------5---------5------5-----5---------5-------5 6 Kield 6 1ype 6 E*ll 6 Jey 6 'e)!*lt 6 3$tr! 6 5-------5---------5------5-----5---------5-------5 6 c 6 ch!r89: 6 I3S 6 6 EGLL 6 6 6 i 6 int899: 6 I3S 6 6 EGLL 6 6 5-------5---------5------5-----5---------5-------5 & ro7s in set 80.00 sec: &o indicate that you want a column at a specific position within the table, either use EIS& to make it the first column, or AE&E colHname to indicate that the new column should be placed after colHname. &ry the following A,&E &A",E statements, using S1O/ 2O,*#;S after each one to see what effect each one has' 0L13F 102L3 test!lter<t"l 'F.? i4 0L13F 102L3 test!lter<t"l 0'' i DE1 KDFS14 0L13F 102L3 test!lter<t"l 'F.? i4 0L13F 102L3 test!lter<t"l 0'' i DE1 0K13F c4 &he EIS& and AE&E specifiers work only with the A!! clause. &his means that if you want to reposition an e(isting column within a table, you first must !OP it and then A!! it at the new position. Changing a Column Defnition or Name: &o change a columnDs definition, use M*D!F; or C32)7+ clause along with A,&E command. Eor e(ample, to change column c from 21A(<$ to 21A(<7$, do this' mys#l, 0L13F 102L3 test!lter<t"l M.'DKI c M-0F890:4 /ith 21A;)E, the synta( is a bit different. After the 21A;)E keyword, you name the column you want to change, then specify the new definition, which includes the new name. &ry out following e(ample' mys#l, 0L13F 102L3 test!lter<t"l M-0EL3 i Y 2DLDE14 If you now use 21A;)E to con%ert B from "I)I;& back to I;& without changing the column name, the statement be as e(pected' mys#l, 0L13F 102L3 test!lter<t"l M-0EL3 Y Y DE14 The Efect of ALTER TABLE on Null and Default Value Attributes: /hen you #O!IE? or 21A;)E a column, you can also specify whether or not the column can contain ;*,, %alues, and what its default %alue is. In fact, if you donDt do this, #yS+, automatically assigns %alues for these attributes. 1ere is the e(ample where ;O& ;*,, column will ha%e %alue <77 by default. mys#l, 0L13F 102L3 test!lter<t"l -, M.'DKI Y 2DLDE1 E.1 EGLL '3K0GL1 9004 If you donDt use abo%e command then #yS+, will fill up ;*,, %alues in all the columns. Changing a Column's Default Value: ?ou can change a default %alue for any column using A,&E command. &ry out following e(ample. mys#l, 0L13F 102L3 test!lter<t"l 0L13F i S31 '3K0GL1 90004 mys#l, S-./ M.LGMES KF.M test!lter<t"l4 5-------5---------5------5-----5---------5-------5 6 Kield 6 1ype 6 E*ll 6 Jey 6 'e)!*lt 6 3$tr! 6 5-------5---------5------5-----5---------5-------5 6 c 6 ch!r89: 6 I3S 6 6 EGLL 6 6 6 i 6 int899: 6 I3S 6 6 9000 6 6 5-------5---------5------5-----5---------5-------5 & ro7s in set 80.00 sec: ?ou can remo%e default constraint from any column by using !OP clause along with A,&E command. mys#l, 0L13F 102L3 test!lter<t"l 0L13F i 'F.? '3K0GL14 mys#l, S-./ M.LGMES KF.M test!lter<t"l4 5-------5---------5------5-----5---------5-------5 6 Kield 6 1ype 6 E*ll 6 Jey 6 'e)!*lt 6 3$tr! 6 5-------5---------5------5-----5---------5-------5 6 c 6 ch!r89: 6 I3S 6 6 EGLL 6 6 6 i 6 int899: 6 I3S 6 6 EGLL 6 6 5-------5---------5------5-----5---------5-------5 & ro7s in set 80.00 sec: Changing a Table Type: ?ou can use a table type by using T;P+ clause alongwith A,&E command. &ry out following e(ample to change testalterHtbl to M;!S2M table type. &o find out the current type of a table, use the S1O/ &A",E S&A&*S statement. mys#l, 0L13F 102L3 test!lter<t"l 1I?3 @ MIDS0M4 mys#l, S-./ 102L3 S101GS LDJ3 Htest!lter<t"lHVL >>>>>>>>>>>>>>>>>>>>>>>>>>> 9. ro7 >>>>>>>>>>>>>>>> E!me= test!lter<t"l 1ype= MyDS0M Fo7<)orm!t= Ki$ed Fo7s= 0 0+<ro7<len+th= 0 '!t!<len+th= 0 M!$<d!t!<len+th= &5W69803WW5 Dnde$<len+th= 90&N '!t!<)ree= 0 0*to<increment= EGLL Mre!te<time= &00W-06-03 08=0N=36 Gpd!te<time= &00W-06-03 08=0N=36 MhecP<time= EGLL Mre!te<options= Momment= 9 ro7 in set 80.00 sec: Renaming a Table: &o rename a table, use the R+)2M+ option of the A,&E &A",E statement. &ry out following e(ample to rename testalterHtbl to alterHtbl mys#l, 0L13F 102L3 test!lter<t"l F3E0M3 1. !lter<t"l4 ?ou can use A,&E command to create and drop I;!EM on a #yS+, file. /e will see this feature in ne(t chapter. A database inde( is a data structure that impro%es the speed of operations in a table. Inde(es can be created using one or more columns, pro%iding the basis for both rapid random lookups and efficient ordering of access to records. /hile creating inde( it should be considered that what are the columns which will be used to make S+, -ueries and create one or more inde(es on those columns. Practically, Inde(es are also type of tables which keeps primary key or inde( field and a pointer to each record in to the actual table. &he users cannot see the inde(es, they are Bust used to speed up -ueries and will be used by !atabase Search Engine to locate records %ery fast. I;SE& and *P!A&E statements takes more time on tables ha%ing inde(es where as SE,E2& statements become fast on those tables. &he reason is that while doing insert or update, database need to inert or update inde( %alues as well. Simple and Unique Index: ?ou can create a uni-ue inde( on a table. A uni-ue inde( means that two rows cannot ha%e the same inde( %alue. 1ere is the synta( to create an Inde( on a table MF3013 GEDQG3 DE'3[ inde$<n!me .E t!"le<n!me 8 col*mn9( col*mn&(...:4 ?ou can use one or more columns to create an inde(. Eor e(ample we can create an inde( on tutorialsHtbl using tutorialHauthor MF3013 GEDQG3 DE'3[ 0G1-.F<DE'3[ .E t*tori!ls<t"l 8t*tori!l<!*thor: ?ou can creates a simple inde( on a table. 4ust omit *;I+*E keyword from the -uery to create simple inde(. Simple inde( allows duplicate %alues in a table. If you want to inde( the %alues in a column in descending order, you can add the reser%ed word !ES2 after the column name' mys#l, MF3013 GEDQG3 DE'3[ 0G1-.F<DE'3[ .E t*tori!ls<t"l 8t*tori!l<!*thor '3SM: ALTER command to add and drop INDEX: &here are four types of statements for adding inde(es to a table' 2%T+R T2B%+ tbl8name 2DD PR!M2R; K+; (column8list) ' &his statement adds a PI#A? JE?, which means that inde(ed %alues must be uni-ue and cannot be ;*,,. 2%T+R T2B%+ tbl8name 2DD ,)!$,+ inde"8name (column8list): &his statement creates an inde( for which %alues must be uni-ue (with the e(ception of ;*,, %alues, which may appear multiple times$. 2%T+R T2B%+ tbl8name 2DD !)D+5 inde"8name (column8list): &his adds an ordinary inde( in which any %alue may appear more than once. 2%T+R T2B%+ tbl8name 2DD F,%%T+5T inde"8name (column8list): &his creates a special E*,,&EM& inde( that is used for te(t0searching purposes. 1ere is the e(ample to add inde( in an e(isting table. mys#l, 0L13F 102L3 test!lter<t"l 0'' DE'3[ 8c:4 ?ou can drop any I;!EM by using !OP clause along with A,&E command. &ry out following e(ample to drop abo%e created inde(. mys#l, 0L13F 102L3 test!lter<t"l 'F.? DE'3[ 8c:4 ?ou can drop any I;!EM by using !OP clause along with A,&E command. &ry out following e(ample to drop abo%e created inde (. ALTER Command to add and drop PRIMARY KEY: ?ou can add primary key as well in the same way. "ut make sure Primary Jey works on columns which are ;O& ;*,,. 1ere is the e(ample to add primary key in an e(isting table. &his will make a column ;O& ;*,, first and then add it as a primary key. mys#l, 0L13F 102L3 test!lter<t"l M.'DKI i DE1 E.1 EGLL4 mys#l, 0L13F 102L3 test!lter<t"l 0'' ?FDM0FI J3I 8i:4 ?ou can use A,&E command to drop a primary key as follows' mys#l, 0L13F 102L3 test!lter<t"l 'F.? ?FDM0FI J3I4 &o drop an inde( that is not a PI#A? JE?, you must specify the inde( name. Displaying INDEX Information: ?ou can use S1O/ I;!EM command to list out all the inde(es associated with a table. 5ertical0format output (specified by A)$ often is useful with this statement, to a%oid long line wraparound' &ry out following e(ample' mys#l, S-./ DE'3[ KF.M table_nameVL ........ MySQL Te&'orary Tables Ad%ertisements &he temporary tables could be %ery useful in some cases to keep temporary data. &he most important thing that should be knows for temporary tables is that they will be deleted when the current client session terminates. &emporary tables where added in #yS+, %ersion >.=>. If you use an older %ersion of #yS+, than >.=> you canDt use temporary tables, but you can use heap tables. As stated earlier temporary tables will only last as long as the session is ali%e. If you run the code in a P1P script, the temporary table will be destroyed automatically when the script finishes e(ecuting. If you are connected to the #yS+l database ser%er through the #yS+, client program, then the temporary table will e(ist until you close the client or manually destroy the table. Example 1ere is an e(ample showing you usage of temporary table. Same code can be used in P1P scripts using mys-l8-uery() function. mys#l, MF3013 13M?.F0FI 102L3 S!lesS*mm!ry 8 -, prod*ct<n!me %0FM-0F850: E.1 EGLL -, ( tot!l<s!les '3MDM0L89&(&: E.1 EGLL '3K0GL1 0.00 -, ( !+<*nit<price '3MDM0L8W(&: E.1 EGLL '3K0GL1 0.00 -, ( tot!l<*nits<sold DE1 GESDLE3' E.1 EGLL '3K0GL1 0 :4 Q*ery .J( 0 ro7s !))ected 80.00 sec: mys#l, DES3F1 DE1. S!lesS*mm!ry -, 8prod*ct<n!me( tot!l<s!les( !+<*nit<price( tot!l<*nits<sold: -, %0LG3S -, 8Hc*c*m"erH( 900.&5( 90( &:4 mys#l, S3L3M1 > KF.M S!lesS*mm!ry4 5--------------5-------------5---------------- 5------------------5 6 prod*ct<n!me 6 tot!l<s!les 6 !+<*nit<price 6 tot!l<*nits<sold 6 5--------------5-------------5---------------- 5------------------5 6 c*c*m"er 6 900.&5 6 90.00 6 & 6 5--------------5-------------5---------------- 5------------------5 9 ro7 in set 80.00 sec: /hen you issue a S1O/ &A",ES command then your temporary table would not be listed out in the list. ;ow if you will log out of the #yS+, session and then you will issue a SE,E2& command then you will find no data a%ailable in the database. E%en your temporary table would also not e(ist. Dropping Temporary Tables: "y default all the temporary tables are deleted by #yS+, when your database connection gets terminated. Still you want to delete them in between then you do so by issuing !OP &A",E command. Eollowing is the e(ample on dropping a temproary table. mys#l, MF3013 13M?.F0FI 102L3 S!lesS*mm!ry 8 -, prod*ct<n!me %0FM-0F850: E.1 EGLL -, ( tot!l<s!les '3MDM0L89&(&: E.1 EGLL '3K0GL1 0.00 -, ( !+<*nit<price '3MDM0L8W(&: E.1 EGLL '3K0GL1 0.00 -, ( tot!l<*nits<sold DE1 GESDLE3' E.1 EGLL '3K0GL1 0 :4 Q*ery .J( 0 ro7s !))ected 80.00 sec: mys#l, DES3F1 DE1. S!lesS*mm!ry -, 8prod*ct<n!me( tot!l<s!les( !+<*nit<price( tot!l<*nits<sold: -, %0LG3S -, 8Hc*c*m"erH( 900.&5( 90( &:4 mys#l, S3L3M1 > KF.M S!lesS*mm!ry4 5--------------5-------------5---------------- 5------------------5 6 prod*ct<n!me 6 tot!l<s!les 6 !+<*nit<price 6 tot!l<*nits<sold 6 5--------------5-------------5---------------- 5------------------5 6 c*c*m"er 6 900.&5 6 90.00 6 & 6 5--------------5-------------5---------------- 5------------------5 9 ro7 in set 80.00 sec: mys#l, 'F.? 102L3 S!lesS*mm!ry4 mys#l, S3L3M1 > KF.M S!lesS*mm!ry4 3FF.F 99N6= 1!"le H1G1.FD0LS.S!lesS*mm!ryH doesnHt e$ist &here may be a situation when you need an e(act copy of a table, and 2EA&E &A",E ... SE,E2& doesnDt suit your purposes because the copy must include the same inde(es, default %alues, and so forth. ?ou can handle this situation by following steps. <. *se S1O/ 2EA&E &A",E to get a 2EA&E &A",E statement that specifies the source tableDs structure, inde(es and all. =. #odify the statement to change the table name to that of the clone table and e(ecute the statement. &his way you will ha%e e(act clone table. >. Optionally, If you need the table contents copied as well, issue an I;SE& I;&O ... SE,E2& statement, too. Example: &ry out following e(ample to create a clone table for tutorials8tbl Ste .: )et complete structure about table mys#l, S-./ MF3013 102L3 t*tori!ls<t"l VL4 >>>>>>>>>>>>>>>>>>>>>>>>>>> 9. ro7 >>>>>>>>>>>>>>>>>>>>>>>>>>> 1!"le= t*tori!ls<t"l Mre!te 1!"le= MF3013 102L3 ]t*tori!ls<t"l] 8 ]t*tori!l<id] int899: E.1 EGLL !*to<increment( ]t*tori!l<title] !rch!r8900: E.1 EGLL de)!*lt HH( ]t*tori!l<!*thor] !rch!r8N0: E.1 EGLL de)!*lt HH( ]s*"mission<d!te] d!te de)!*lt EGLL( ?FDM0FI J3I 8]t*tori!l<id]:( GEDQG3 J3I ]0G1-.F<DE'3[] 8]t*tori!l<!*thor]: : 1I?3@MyDS0M 9 ro7 in set 80.00 sec: 3FF.F= Eo #*ery speci)ied Ste /: ename this table and create another table mys#l, MF3013 102L3 ]clone<t"l] 8 -, ]t*tori!l<id] int899: E.1 EGLL !*to<increment( -, ]t*tori!l<title] !rch!r8900: E.1 EGLL de)!*lt HH( -, ]t*tori!l<!*thor] !rch!r8N0: E.1 EGLL de)!*lt HH( -, ]s*"mission<d!te] d!te de)!*lt EGLL( -, ?FDM0FI J3I 8]t*tori!l<id]:( -, GEDQG3 J3I ]0G1-.F<DE'3[] 8]t*tori!l<!*thor]: -, : 1I?3@MyDS0M4 Q*ery .J( 0 ro7s !))ected 89.80 sec: Ste 0: After e(ecuting step = you will a clone table in your database. If you want to copy data from old table then you can do it by using I;SE& I;&O... SE,E2& statement. mys#l, DES3F1 DE1. clone<t"l 8t*tori!l<id( -, t*tori!l<title( -, t*tori!l<!*thor( -, s*"mission<d!te: -, S3L3M1 t*tori!l<id(t*tori!l<title( -, t*tori!l<!*thor(s*"mission<d!te( -, KF.M t*tori!ls<t"l4 Q*ery .J( 3 ro7s !))ected 80.0W sec: Fecords= 3 '*plic!tes= 0 /!rnin+s= 0 Einally you will ha%e e(act clone table as you wanted to ha%e. &here are three information which you would like to ha%e from #yS+,. !n#ormation about t(e result o# -ueries: &his includes number of records effected by any SE,E2&, *P!A&E or !E,E&E statement. !n#ormation about tables and databases: &his includes information pertaining to the structure of tables and databases. !n#ormation about t(e MyS$% ser'er: &his includes current status of database ser%er, %ersion number etc. Its %ery easy to get all these information at mys-l prompt. "*t while using PE, or P1P APIs then we need to call %arious APIs e(plicitely to obtain all these information. Eollowing section will show you how to obtain these information. Obtaining the Number of Rows Afected by a Query: P+R% +"amle: In !"I scripts, the affected0rows count is returned by do( $ or by e(ecute( $, depending on how you e(ecute the -uery' # Method 9 # e$ec*te A#*ery *sin+ do8 : my Aco*nt @ Ad"h-,do 8A#*ery:4 # report 0 ro7s i) !n error occ*rred print) ;Zd ro7s 7ere !))ectedVn;( 8de)ined 8Aco*nt: R Aco*nt = 0:4 # Method & # e$ec*te #*ery *sin+ prep!re8 : pl*s e$ec*te8 : my Asth @ Ad"h-,prep!re 8A#*ery:4 my Aco*nt @ Asth-,e$ec*te 8 :4 print) ;Zd ro7s 7ere !))ectedVn;( 8de)ined 8Aco*nt: R Aco*nt = 0:4 P3P +"amle: In P1P, in%oke the mys-lHaffectedHrows( $ function to find out how many rows a -uery changed' Ares*lt<id @ mys#l<#*ery 8A#*ery( Aconn<id:4 # report 0 ro7s i) the #*ery )!iled Aco*nt @ 8Ares*lt<id R mys#l<!))ected<ro7s 8Aconn<id: = 0:4 print 8;Aco*nt ro7s 7ere !))ectedVn;:4 Listing Tables and Databases: &his is %ery easy to list down all the databases and tables a%ailable with database ser%er. ?our result may be null if you donDt ha%e sufficient pri%ilege. Apart from the method I ha%e mentioned below you can use S1O/ &A",ES or S1O/ !A&A"ASES -ueries to get list of tables or databases either in P1P or in PE,. P+R% +"amle: # Let !ll the t!"les !!il!"le in c*rrent d!t!"!se. my @t!"les @ Ad"h-,t!"les 8 :4 )ore!ch At!"le 8@t!"les :T print ;1!"le E!me At!"leVn;4 U P3P +"amle: QRphp Acon @ mys#l<connect8;loc!lhost;( ;*serid;( ;p!ss7ord;:4 i) 8SAcon: T die8HMo*ld not connect= H . mys#l<error8::4 U Ad"<list @ mys#l<list<d"s8Acon:4 7hile 8Ad" @ mys#l<)etch<o"Yect8Ad"<list:: T echo Ad"-,'!t!"!se . ;Q"r B,;4 U mys#l<close8Acon:4 R, Getting Server Metadata: &here are following commands in #yS+, which can be e(ecuted either are mys-l prompt or using any script like P1P to get %arious important information about database ser%er. Command Descrition SE,E2& 5ESIO;( $ Ser%er %ersion string SE,E2& !A&A"ASE( $ 2urrent database name (empty if none$ SE,E2& *SE( $ 2urrent username S1O/ S&A&*S Ser%er status indicators S1O/ 5AIA",ES Ser%er configuration %ariables se-uence is a set of integers <, =, >, ... that are generated in order on demand. Se-uences are fre-uently used in databases because many applications re-uire each row in a table to contain a uni-ue %alue, and se-uences pro%ide an easy way to generate them. &his chapter describes how to use se-uences in #yS+,. Using AUTO_INCREMENT column: &he simplest way in #yS+, to use Se-uences is to define a column as A*&OHI;2E#E;& and lea%e rest of the things to #yS+, to take care. Example: &ry out following e(ample. &his will create table and after that it will insert few rows in this table where it is not re-uired to gi%e record I! because its auto incremented by #yS+,. mys#l, MF3013 102L3 insect -, 8 -, id DE1 GESDLE3' E.1 EGLL 0G1.<DEMF3M3E1( -, ?FDM0FI J3I 8id:( -, n!me %0FM-0F830: E.1 EGLL( # type o) insect -, d!te '013 E.1 EGLL( # d!te collected -, ori+in %0FM-0F830: E.1 EGLL # 7here collected :4 Q*ery .J( 0 ro7s !))ected 80.0& sec: mys#l, DES3F1 DE1. insect 8id(n!me(d!te(ori+in: %0LG3S -, 8EGLL(Hho*se)lyH(H&009-09-90H(HPitchenH:( -, 8EGLL(HmillipedeH(H&009-09-90H(Hdrie7!yH:( -, 8EGLL(H+r!sshopperH(H&009-09-90H(H)ront y!rdH:4 Q*ery .J( 3 ro7s !))ected 80.0& sec: Fecords= 3 '*plic!tes= 0 /!rnin+s= 0 mys#l, S3L3M1 > KF.M insect .F'3F 2I id4 5----5-------------5------------5------------5 6 id 6 n!me 6 d!te 6 ori+in 6 5----5-------------5------------5------------5 6 9 6 ho*se)ly 6 &009-09-90 6 Pitchen 6 6 & 6 millipede 6 &009-09-90 6 drie7!y 6 6 3 6 +r!sshopper 6 &009-09-90 6 )ront y!rd 6 5----5-------------5------------5------------5 3 ro7s in set 80.00 sec: Obtain AUTO_INCREMENT Values: ,AS&HI;SE&HI!( $ is a S+, function, so you can use it from within any client that understands how to issue S+, statements. otherwise PE, and P11 scripts pro%ide e(clusi%e functions to retrie%e auto incremented %alue of last record. P+R% +"amle: *se the mys-lHinsertid attribute to obtain the A*&OHI;2E#E;& %alue generated by a -uery. &his attribute is accessed through either a database handle or a statement handle, depending on how you issue the -uery. &he following e(ample references it through the database handle' Ad"h-,do 8;DES3F1 DE1. insect 8n!me(d!te(ori+in: %0LG3S8HmothH(H&009-09-9NH(H7indo7sillH:;:4 my Ase# @ Ad"h-,Tmys#l<insertidU4 P3P +"amle: After issuing a -uery that generates an A*&OHI;2E#E;& %alue, retrie%e the %alue by calling mys-lHinsertHid( $' mys#l<#*ery 8;DES3F1 DE1. insect 8n!me(d!te(ori+in: %0LG3S8HmothH(H&009-09-9NH(H7indo7sillH:;( Aconn<id:4 Ase# @ mys#l<insert<id 8Aconn<id:4 Renumbering an Existing Sequence: &here may be a case when you ha%e deleted many records from a table and you want to rese-uence all the records. &his can be done by using a simple trick but you should be %ery careful to do so if your table is ha%ing Boin with other table. If you determine that rese-uencing an A*&OHI;2E#E;& column is una%oidable, the way to do it is to drop the column from the table, then add it again. &he following e(ample shows how to renumber the id %alues in the insect table using this techni-ue' mys#l, 0L13F 102L3 insect 'F.? id4 mys#l, 0L13F 102L3 insect -, 0'' id DE1 GESDLE3' E.1 EGLL 0G1.<DEMF3M3E1 KDFS1( -, 0'' ?FDM0FI J3I 8id:4 Starting a Sequence at a Particular Value: "y default #yS+, will start se-uence from < but you can specify any other number as well at the time of table creation. Eollowing is the e(ample where #yS+, will start se-uence from <77. mys#l, MF3013 102L3 insect -, 8 -, id DE1 GESDLE3' E.1 EGLL 0G1.<DEMF3M3E1 @ 900( -, ?FDM0FI J3I 8id:( -, n!me %0FM-0F830: E.1 EGLL( # type o) insect -, d!te '013 E.1 EGLL( # d!te collected -, ori+in %0FM-0F830: E.1 EGLL # 7here collected :4 Alternati%ely, you can create the table and then set the initial se-uence %alue with A,&E &A",E. mys#l, 0L13F 102L3 t 0G1.<DEMF3M3E1 @ 9004 &ables or result sets sometimes contain duplicate records. Sometime it is allowed but sometime it is re-uired to stop duplicate records. Sometime it is re-uired to identify duplicate records and remo%e them from the table. &his chapter will describe how to pre%ent duplicate records occurring in a table and how to remo%e already e(isting duplicate records. Preventing Duplicates from Occurring in a Table: ?ou can use a PR!M2R; K+; or ,)!$,+ Inde( on a table with appropriate fields to stop duplicate records. ,ets take one e(ample, &he following table contains no such inde( or primary key, so it would allow duplicate records for firstHname and lastHname MF3013 102L3 person<t"l 8 )irst<n!me M-0F8&0:( l!st<n!me M-0F8&0:( se$ M-0F890: :4 &o pre%ent multiple records with the same first and last name %alues from being created in this table, add a PI#A? JE? to its definition. /hen you do this, itDs also necessary to declare the inde(ed columns to be ;O& ;*,,, because a PI#A? JE? does not allow ;*,, %alues' MF3013 102L3 person<t"l 8 )irst<n!me M-0F8&0: E.1 EGLL( l!st<n!me M-0F8&0: E.1 EGLL( se$ M-0F890: ?FDM0FI J3I 8l!st<n!me( )irst<n!me: :4 &he presence of a uni-ue inde( in a table normally causes an error to occur if you insert a record into the table that duplicates an e(isting record in the column or columns that define the inde(. *se !)S+RT !7)*R+ rather than !)S+RT. If a record doesnDt duplicate an e(isting record, #yS+, inserts it as usual. If the record is a duplicate, the I);OE keyword tells #yS+, to discard it silently without generating an error. Eollowing e(ample does not error out and same time it will not insert duplicate records. mys#l, DES3F1 DLE.F3 DE1. person<t"l 8l!st<n!me( )irst<n!me: -, %0LG3S8 HX!yH( H1hom!sH:4 Q*ery .J( 9 ro7 !))ected 80.00 sec: mys#l, DES3F1 DLE.F3 DE1. person<t"l 8l!st<n!me( )irst<n!me: -, %0LG3S8 HX!yH( H1hom!sH:4 Q*ery .J( 0 ro7s !))ected 80.00 sec: *se R+P%2C+ rather than I;SE&. If the record is new, itDs inserted Bust as with I;SE&. If itDs a duplicate, the new record replaces the old one' mys#l, F3?L0M3 DE1. person<t"l 8l!st<n!me( )irst<n!me: -, %0LG3S8 H0Y!yH( HJ*m!rH:4 Q*ery .J( 9 ro7 !))ected 80.00 sec: mys#l, F3?L0M3 DE1. person<t"l 8l!st<n!me( )irst<n!me: -, %0LG3S8 H0Y!yH( HJ*m!rH:4 Q*ery .J( & ro7s !))ected 80.00 sec: I;SE& I);OE and EP,A2E should be chosen according to the duplicate0handling beha%ior you want to effect. I;SE& I);OE keeps the first of a set of duplicated records and discards the rest. EP,A2E keeps the last of a set of duplicates and erase out any earlier ones. Another way to enforce uni-ueness is to add a *;I+*E inde( rather than a PI#A? JE? to a table. MF3013 102L3 person<t"l 8 )irst<n!me M-0F8&0: E.1 EGLL( l!st<n!me M-0F8&0: E.1 EGLL( se$ M-0F890: GEDQG3 8l!st<n!me( )irst<n!me: :4 Counting and Identifying Duplicates: Eollowing is the -uery to count duplicate records with firstHname and lastHname in a table. mys#l, S3L3M1 M.GE18>: !s repetitions( l!st<n!me( )irst<n!me -, KF.M person<t"l -, LF.G? 2I l!st<n!me( )irst<n!me -, -0%DEL repetitions , 94 &his -uery will return a list of all the duplicate records in personHtbl table. In general, to identify sets of %alues that are duplicated, do the following' !etermine which columns contain the %alues that may be duplicated. ,ist those columns in the column selection list, along with 2O*;&(N$. ,ist the columns in the )O*P "? clause as well. Add a 1A5I;) clause that eliminates uni-ue %alues by re-uiring group counts to be greater than one. Eliminating Duplicates from a Query Result: ?ou can use D!ST!)CT along with SE,E2& statement to find out uni-ue records a%ailable in a table. mys#l, S3L3M1 'DS1DEM1 l!st<n!me( )irst<n!me -, KF.M person<t"l -, .F'3F 2I l!st<n!me4 An alternati%e to !IS&I;2& is to add a )O*P "? clause that names the columns youDre selecting. &his has the effect of remo%ing duplicates and selecting only the uni-ue combinations of %alues in the specified columns' mys#l, S3L3M1 l!st<n!me( )irst<n!me -, KF.M person<t"l -, LF.G? 2I 8l!st<n!me( )irst<n!me:4 Removing Duplicates Using Table Replacement: If you ha%e duplicate records in a table and you want to remo%e all the duplicate records from that table then here is the procedure. mys#l, MF3013 102L3 tmp S3L3M1 l!st<n!me( )irst<n!me( se$ -, KF.M person<t"l4 -, LF.G? 2I 8l!st<n!me( )irst<n!me:4 mys#l, 'F.? 102L3 person<t"l4 mys#l, 0L13F 102L3 tmp F3E0M3 1. person<t"l4 An easy way of remo%ing duplicate records from a table is that add an I;!EM or PI#A? JE? to that table. E%en if this table is already a%ailable you can use this techni-ue to remo%e duplicate records and you will be safe in future as well. mys#l, 0L13F DLE.F3 102L3 person<t"l -, 0'' ?FDM0FI J3I 8l!st<n!me( )irst<n!me:4 If you take user input through a webpage and insert it into a #yS+, database thereDs a chance that you ha%e left yourself wide open for a security issue known as S+, InBection. &his lesson will teach you how to help pre%ent this from happening and help you secure your scripts and #yS+, statements. InBection usually occurs when you ask a user for input, like their name, and instead of a name they gi%e you a #yS+, statement that you will unknowingly run on your database. ;e%er trust user pro%ided data, process this data only after %alidationI as a rule, this is done by pattern matching. In the e(ample below, the username is restricted to alphanumerical chars plus underscore and to a length between : and =7 chars 0 modify these rules as needed. i) 8pre+<m!tch8;B\V7T8(&0UAB;( A<L31[H*sern!meH]( Am!tches:: T Ares*lt @ mys#l<#*ery8;S3L3M1 > KF.M *sers /-3F3 *sern!me@Am!tches[0];:4 U else T echo ;*sern!me not !ccepted;4 U &o demonstrate the problem, consider this e(cerpt' BB s*pposed inp*t An!me @ ;Q!dirH4 '3L313 KF.M *sers4;4 mys#l<#*ery8;S3L3M1 > KF.M *sers /-3F3 n!me@HTAn!meUH;:4 &he function call is supposed to retrie%e a record from the users table where the name column matches the name specified by the user. *nder normal circumstances, Oname would only contain alphanumeric characters and perhaps spaces, such as the string ilia. "ut here, by appending an entirely new -uery to Oname, the call to the database turns into disaster' the inBected !E,E&E -uery remo%es all records from users. Eortunately, if you use #yS+,, the mys-lH-uery($ function does not permit -uery stacking, or e(ecuting multiple -ueries in a single function call. If you try to stack -ueries, the call fails. 1owe%er, other P1P database e(tensions, such as S+,ite and PostgreS+,, happily perform stacked -ueries, e(ecuting all of the -ueries pro%ided in one string and creating a serious security problem. Preventing SQL Injection: ?ou can handle all escape characters smartly in scripting languages like PE, and P1P. &he #yS+, e(tension for P1P pro%ides the function mys-lHrealHescapeHstring($ to escape input characters that are special to #yS+,. i) 8+et<m!+ic<#*otes<+pc8:: T An!me @ stripsl!shes8An!me:4 U An!me @ mys#l<re!l<esc!pe<strin+8An!me:4 mys#l<#*ery8;S3L3M1 > KF.M *sers /-3F3 n!me@HTAn!meUH;:4 The LIKE Quandary: &o address the ,IJE -uandary, a custom escaping mechanism must con%ert user0supplied R and H characters to literals. *se addcslashes($, a function that letDs you specify a character range to escape. As*" @ !ddcsl!shes8mys#l<re!l<esc!pe<strin+8;Zsomethin+<;:( ;Z<;:4 BB As*" @@ VZsomethin+V< mys#l<#*ery8;S3L3M1 > KF.M mess!+es /-3F3 s*"Yect LDJ3 HTAs*"UZH;:4 &he simplest way of e(porting a table data into a te(t file is using SE,E2&...I;&O O*&EI,E statement that e(ports a -uery result directly into a file on the ser%er host. Exporting Data with the SELECT ... INTO OUTFILE Statement: &he synta( for this statement combines a regular SE,E2& with I;&O O*&EI,E filename at the end. &he default output format is the same as for ,OA! !A&A, so the following statement e(ports the tutorialsHtbl table into @tmp@tutorials.t(t as a tab0delimited, linefeed0terminated file' mys#l, S3L3M1 > KF.M t*tori!ls<t"l -, DE1. .G1KDL3 HBtmpBt*tori!ls.t$tH4 ?ou can change the output format using options to indicate how to -uote and delimit columns and records. &o e(port the tutorialHtbl table in 2S5 format with 2,E0terminated lines, use this statement' mys#l, S3L3M1 > KF.M p!ss7d DE1. .G1KDL3 HBtmpBt*tori!ls.t$tH -, KD3L'S 13FMDE013' 2I H(H 3EML.S3' 2I H;H -, LDE3S 13FMDE013' 2I HVrVnH4 &he S+%+CT DDD !)T* *,TF!%+ has the following properties' &he output file is created directly by the #yS+, ser%er, so the filename should indicate where you want the file to be written on the ser%er host. &here is no ,O2A, %ersion of the statement analogous to the ,O2A, %ersion of ,OA! !A&A. ?ou must ha%e the #yS+, EI,E pri%ilege to e(ecute the SE,E2& ... I;&O statement. &he output file must not already e(ist. &his pre%ents #yS+, from clobbering files that may be important. ?ou should ha%e a login account on the ser%er host or some way to retrie%e the file from that host. Otherwise, SE,E2& ... I;&O O*&EI,E likely will be of no %alue to you. *nder *ni(, the file is created world readable and is owned by the #yS+, ser%er. &his means that although youDll be able to read the file, you may not be able to delete it. Exporting Tables as Raw Data: &he mysqldump program is used to copy or back up tables and databases. It can write table output either as a raw datafile, or as a set of I;SE& statements that recreate the records in the table. &o dump a table as a datafile, you must specify a 00tab option that indicates the directory where you want the #yS+, ser%er to write the file. Eor e(ample, to dump the tutorialsHtbl table from the &*&OIA,S database to a file in the @tmp directory, use a command like this' A mys#ld*mp -* root -p --no-cre!te-in)o V --t!"@Btmp 1G1.FD0LS t*tori!ls<t"l p!ss7ord >>>>>> Exporting Table Contents or Defnitions in SQL Format: &o e(port a table in S+, format to a file, use a command like this' A mys#ld*mp -* root -p 1G1.FD0LS t*tori!ls<t"l , d*mp.t$t p!ss7ord >>>>>> &his will create file ha%ing content as follows' -- MySQL d*mp 8.&3 -- -- -ost= loc!lhost '!t!"!se= 1G1.FD0LS --------------------------------------------------------- -- Serer ersion 3.&3.58 -- -- 1!"le str*ct*re )or t!"le ]t*tori!ls<t"l] -- MF3013 102L3 t*tori!ls<t"l 8 t*tori!l<id int899: E.1 EGLL !*to<increment( t*tori!l<title !rch!r8900: E.1 EGLL de)!*lt HH( t*tori!l<!*thor !rch!r8N0: E.1 EGLL de)!*lt HH( s*"mission<d!te d!te de)!*lt EGLL( ?FDM0FI J3I 8t*tori!l<id:( GEDQG3 J3I 0G1-.F<DE'3[ 8t*tori!l<!*thor: : 1I?3@MyDS0M4 -- -- '*mpin+ d!t! )or t!"le ]t*tori!ls<t"l] -- DES3F1 DE1. t*tori!ls<t"l %0LG3S 89(HLe!rn ?-?H(HXohn ?o*lH(H&00W-05-&NH:4 DES3F1 DE1. t*tori!ls<t"l %0LG3S 8&(HLe!rn MySQLH(H0"d*l SH(H&00W-05-&NH:4 DES3F1 DE1. t*tori!ls<t"l %0LG3S 83(HX0%0 1*tori!lH(HS!nY!yH(H&00W-05-06H:4 &o dump multiple tables, name them all following the database name argument. &o dump an entire database, donDt name any tables after the database as follows' A mys#ld*mp -* root -p 1G1.FD0LS , d!t!"!se<d*mp.t$t p!ss7ord >>>>>> &o backup all the databases a%ailable on your host use the following' A mys#ld*mp -* root -p --!ll-d!t!"!ses , d!t!"!se<d*mp.t$t p!ss7ord >>>>>> &he 00all0databases option is a%ailable as of #yS+, >.=>.<=. &hese method can be used to implement a database backup stretegy. Co'ying Tables or (atabases to )not*er Host# If you want to copy tables or databases from one #yS+, ser%er to another then use mys-ldump with database name and table name. un the following command at source host. &his will dump complete database into dump.t(t file' A mys#ld*mp -* root -p d!t!"!se<n!me t!"le<n!me , d*mp.t$t p!ss7ord >>>>> ?ou can copy complete database without using a particular table name as e(plained abo%e. ;ow ftp dump.t(t file on another host and use the following command. "efore running this command, make sure you ha%e created databaseHname on destination ser%er. A mys#l -* root -p d!t!"!se<n!me Q d*mp.t$t p!ss7ord >>>>> Another way to accomplish this without using an intermediary file is to send the output of mys-ldump directly o%er the network to the remote #yS+, ser%er. If you can connect to both ser%ers from the host where the cookbook database resides, use this command' A mys#ld*mp -* root -p d!t!"!se<n!me V st!tes 6 mys#l -h other-host.com d!t!"!se<n!me &he mys-ldump half of the command connects to the local ser%er and writes the dump output to the pipe. &he mys-l half of the command connects to the remote #yS+, ser%er on otherhost.com. It reads the pipe for input and sends each statement to the other0host.com ser%er. &here are two simple ways in #yS+, to load data into #yS+, database from a pre%iously backed up file. Importing Data with LOAD DATA: #yS+, pro%ides a ,OA! !A&A statement that acts as a bulk data loader. 1ereDs an e(ample statement that reads a file dump.t(t from your current directory and loads it into the table mytbl in the current database' mys#l, L.0' '010 L.M0L DEKDL3 Hd*mp.t$tH DE1. 102L3 myt"l4 If the ,O2A, keyword is not present, #yS+, looks for the datafile on the ser%er host using looking into absolute pathname fully specifies the location of the file, beginning from the root of the filesystem. #yS+, reads the file from the gi%en location. "y default, ,OA! !A&A assumes that datafiles contain lines that are terminated by linefeeds (newlines$ and that data %alues within a line are separated by tabs. &o specify a file format e(plicitly, use a EIE,!S clause to describe the characteristics of fields within a line, and a ,I;ES clause to specify the line0ending se-uence. &he following ,OA! !A&A statement specifies that the datafile contains %alues separated by colons and lines terminated by carriage returns and new line character' mys#l, L.0' '010 L.M0L DEKDL3 Hd*mp.t$tH DE1. 102L3 myt"l -, KD3L'S 13FMDE013' 2I H=H -, LDE3S 13FMDE013' 2I HVrVnH4 ,OA! !A&A assumes the columns in the datafile ha%e the same order as the columns in the table. If thatDs not true, you can specify a list to indicate which table columns the datafile columns should be loaded into. Suppose your table has columns a, b, and c, but successi%e columns in the datafile correspond to columns b, c, and a. ?ou can load the file like this' mys#l, L.0' '010 L.M0L DEKDL3 Hd*mp.t$tH -, DE1. 102L3 myt"l 8"( c( !:4 Importing Data with mysqlimport #yS+, also includes a utility program named mysqlimport that acts as a wrapper around ,OA! !A&A so that you can load input files directly from the command line. &o load a data from dump.t(t into mytbl use following command at *;IM prompt. A mys#limport -* root -p --loc!l d!t!"!se<n!me d*mp.t$t p!ss7ord >>>>> If you use mys-limport, command0line options pro%ide the format specifiers. mys-limport commands that correspond to the preceding two ,OA! !A&A statements look like this' A mys#limport -* root -p --loc!l --)ields-termin!ted- "y@;=; V --lines-termin!ted-"y@;VrVn; d!t!"!se<n!me d*mp.t$t p!ss7ord >>>>> &he order in which you specify the options doesnDt matter for mys-limport, e(cept that they should all precede the database name. &he mys-limort statement uses the 00columns option to specify the column order' A mys#limport -* root -p --loc!l --col*mns@"(c(! V d!t!"!se<n!me d*mp.t$t p!ss7ord >>>>> Handling Quotes and Special Characters: &he EIE,!S clause can specify other format options besides &E#I;A&E! "?. "y default, ,OA! !A&A assumes that %alues are un-uoted, and interprets the backslash (A$ as an escape character for special characters. &o indicate the %alue -uoting character e(plicitly, use E;2,OSE! "?I #yS+, will strip that character from the ends of data %alues during input processing. &o change the default escape character, use ES2APE! "?. /hen you specify E;2,OSE! "? to indicate that -uote characters should be stripped from data %alues, itDs possible to include the -uote character literally within data %alues by doubling it or by preceding it with the escape character. Eor e(ample, if the -uote and escape characters are L and A, the input %alue LaLLbALcL will be interpreted as aLbLc. Eor mys-limport, the corresponding command0line options for specifying -uote and escape %alues are 00fields0enclosed0by and 00fields0escaped0by 1ere is the list of all important #yS+, functions. Each function has been e(plained along with suitable e(ample. #yS+, )roup "y 2lause 0 &he #yS+, )O*P "? statement is used along with the S+, aggregate functions like S*# to pro%ide means of grouping the result dataset by certain database table column(s$. #yS+, I; 2lause 0 &his is a clause which can be used alongwith any #yS+, -uery to specify a condition. #yS+, "E&/EE; 2lause 0 &his is a clause which can be used alongwith any #yS+, -uery to specify a condition. #yS+, *;IO; Jeyword 0 *se a *;IO; operation to combine multiple result sets into one. #yS+, 2O*;& Eunction 0 &he #yS+, 2O*;& aggregate function is used to count the number of rows in a database table. #yS+, #AM Eunction 0 &he #yS+, #AM aggregate function allows us to select the highest (ma(imum$ %alue for a certain column. #yS+, #I; Eunction 0 &he #yS+, #I; aggregate function allows us to select the lowest (minimum$ %alue for a certain column. #yS+, A5) Eunction 0 &he #yS+, A5) aggregate function selects the a%erage %alue for certain table column. #yS+, S*# Eunction 0 &he #yS+, S*# aggregate function allows selecting the total for a numeric column. #yS+, S+& Eunctions 0 &his is used to generate a s-uare root of a gi%en number. #yS+, A;! Eunction 0 &his is used to generate a random number using #yS+, command. #yS+, 2O;2A& Eunction 0 &his is used to concatenate any string inside any #yS+, command. #yS+, !A&E and &ime Eunctions 0 2omplete list of #yS+, !ate and &ime related functions. #yS+, ;umeric Eunctions 0 2omplete list of #yS+, functions re-uired to manipulate numbers in #yS+,. #yS+, String Eunctions 0 2omplete list of #yS+, functions re-uired to manipulate strings in #yS+,.