13.07.2015 Views

Download This PDF!

Download This PDF!

Download This PDF!

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Avoid Designs with Many Empty AttributesWeb Database ArchitectureMySQL’s Privilege SystemThe general sintax:GRANT privileges [columns]ON itemTO user_name [IDENTIFIED BY ‘password’][REQUIRE ssl_options][WITH [GRANT OPTION | limit_options] ]4


Privileges - comma-separated list of privilegesColumns - single column name or a comma-separated list of column names.Item - database or table to which the new privileges apply.*.* grant privileges on all the databases (global privileges)dbname.* - all tables in a databasedbname.tablename - single table asdbname.tablename & some specific columns in the columns placeholder- specific columns by specifyinguser_name - name you want the user to log in as in MySQL. The user_namein MySQL can also contain a hostname (laura-interpreted as laura@localhost)and laura@somewhere.com.password - password you want the user to log in with.REQUIRE clause - user must connect via Secure Sockets Layer (SSL) and specify otherSSL options.WITH GRANT OPTION - allows the specified user to grant her own privileges to others.For example:MAX_QUERIES_PER_HOUR nMAX_UPDATES_PER_HOUR nMAX_CONNECTIONS_PER_HOUR nPrivileges are stored in five system tables, in the database called mysql.These five tables arecalled :• mysql.user• mysql.db• mysql.host• mysql.tables_priv• mysql.columns_privAs an alternative to GRANT, you can alter these tables directly.5


Examples Using GRANT and REVOKETo set up an administrator, you can typemysql> grant all-> on *-> to fred identified by ‘mnb123’-> with grant option;<strong>This</strong> command grants all privileges on all databases to a user called Fred with the passwordmnb123 and allows him to pass on those privileges.Chances are you don’t want this user in your system, so go ahead and revoke him:mysql> revoke all privileges, grant-> from fred;6


MySQL then displays a list of all the tables in the database:+-----------------+| Tables in books |+-----------------+| book_reviews || books || customers || order_items || orders |+-----------------+5 rows in set (0.06 sec)You can also use show to see a list of databases by typingmysql> show databases;mysql> describe books;MySQL then displays the information you supplied when creating the database:+--------+------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+--------+------------+------+-----+---------+-------+| isbn | char(13) | NO | PRI | NULL | || author | char(50) | YES | | NULL | || title | char(100) | YES | | NULL | || price | float(4,2) | YES | | NULL | |+--------+------------+------+-----+---------+-------+4 rows in set (0.00 sec)These commands are useful to remind yourself of a column type or to navigate a databasethat you didn’t create.If you find that you are running many queries on a column that is not a key, you may want toadd an index on that column to improve performance.You can do this with the CREATEINDEX statement. The general form of this statement isCREATE [UNIQUE|FULLTEXT] INDEX index_nameON table_name (index_column_name [(length)] [ASC|DESC], ...])(FULLTEXT indexes are for indexing text fields)The optional length field allows you to specify that only the first length characters ofthe field will be indexed. You can also specify that an index should be ascending (ASC) ordescending (DESC); the default is ascending.9


String TypesString types fall into three groups. First, there are plain old strings—that is, short pieces oftext.These are the CHAR (fixed-length character) and VARCHAR (variable-length character)types.You can specify the width of each. Columns of type CHAR are padded with spaces tothe maximum width regardless of the size of the data, whereas VARCHAR columns vary inwidth with the data.Second, there are TEXT and BLOB types.These types, which come in various sizes, are forlonger text or binary data, respectively. BLOBs, or binary large objects, can hold anything youlike—for example, image or sound data.The third group has two special types: SET and ENUM.The SET type specifies that values inthis column must come from a particular set of specified values. Column values can containmore than one value from the set.You can have a maximum of 64 things in the specified set.ENUM is an enumeration. It is very similar to SET, except that columns of this type can haveonly one of the specified values or NULL, and you can have a maximum of 65,535 things inthe enumeration.12


Inserting Data into the DatabaseThe usual form of an INSERT statement isINSERT [INTO] table [(column1, column2, column3,...)] VALUES(value1, value2, value3,...);For example, to insert a record into Book-O-Rama’s customers table, you could typeinsert into customers values(NULL, 'Julie Smith', '25 Oak Street', 'Airport West');’’’If you want to fill in only some of the columns, or if you want to specify them in a differentorder, you can list the specific columns in the columns part of the statement. For example,insert into customers (name, city) values(‘Melissa Jones’, ‘Nar Nar Goon North’);You can also achieve the same effect with the following syntax:insert into customersset name = ’Michael Archer’,address = ’12 Adderley Avenue’,city = ’Leeton’;13


use books;insert into customers values(3, ‘Julie Smith’, ‘25 Oak Street’, ‘Airport West’),(4, ‘Alan Wong’, ‘1/47 Haines Avenue’, ‘Box Hill’),(5, ‘Michelle Arthur’, ‘357 North Road’, ‘Yarraville’);insert into orders values(NULL, 3, 69.98, ‘2007-04-02’),(NULL, 1, 49.99, ‘2007-04-15’),(NULL, 2, 74.98, ‘2007-04-19’),(NULL, 3, 24.99, ‘2007-05-01’);insert into books values(‘0-672-31697-8’, ‘Michael Morgan’,‘Java 2 for Professional Developers’, 34.99),(‘0-672-31745-1’, ‘Thomas Down’, ‘Installing Debian GNU/Linux’, 24.99),(‘0-672-31509-2’, ‘Pruitt, et al.’, ‘Teach Yourself GIMP in 24 Hours’, 24.99),(‘0-672-31769-9’, ‘Thomas Schenk’,‘Caldera OpenLinux System Administration Unleashed’, 49.99);insert into order_items values(1, ‘0-672-31697-8’, 2),(2, ‘0-672-31769-9’, 1),(3, ‘0-672-31769-9’, 1),(3, ‘0-672-31509-2’, 1),(4, ‘0-672-31745-1’, 3);insert into book_reviews values(‘0-672-31697-8’, ‘The Morgan book is clearly written and goes well beyondmost of the basic Java books out there.’);Retrieving Data from the DatabaseThe basic form of a SELECT isSELECT [options] items[INTO file_details]FROM tables[ WHERE conditions ][ GROUP BY group_type ][ HAVING where_definition ][ ORDER BY order_type ][LIMIT limit_criteria ][PROCEDURE proc_name(arguments)][lock_options];select name, cityfrom customers;<strong>This</strong> query has the following output, assuming that you’ve entered the sample data :14


+-----------------+--------------------+| name | city |+-----------------+--------------------+| Julie Smith | Airport West || Alan Wong | Box Hill || Michelle Arthur | Yarraville || Melissa Jones | Nar Nar Goon North || Michael Archer | Leeton |+-----------------+--------------------+Retrieving Data with Specific CriteriaTo access a subset of the rows in a table, you need to specify some selection criteria.Youcan do this with a WHERE clause. For example,select *from orderswhere customerid = 3;selects all the columns from the orders table, but only the rows with a customerid of3. Here’s the output:+---------+------------+--------+------------+| orderid | customerid | amount | date |+---------+------------+--------+------------+| 1 | 5 | 69.98 | 2007-04-02 || 4 | 5 | 24.99 | 2007-05-01 |+---------+------------+--------+------------+The WHERE clause specifies the criteria used to select particular rows.Retrieving Data from Multiple TablesOften, to answer a question from the database, you need to use data from more than one table.To put this information together in SQL, you must perform an operation called a join. <strong>This</strong>simply means joining two or more tables together to follow the relationships between thedata.select orders.orderid, orders.amount, orders.datefrom customers, orderswhere customers.name = ‘Julie Smith’and customers.customerid = orders.customerid;The output of this query is:+---------+--------+------------+| orderid | amount | date |+---------+--------+------------+| 1 | 69.98 | 2007-04-02 || 4 | 24.99 | 2007-05-01 |+---------+--------+------------+15


By listing two tables, you also specify a type of join, possibly without knowing it.The commabetween the names of the tables is equivalent to typing INNER JOIN or CROSS JOIN.<strong>This</strong> is a type of join sometimes also referred to as a full join, or the Cartesian product of thetables.Using Other Names for Tables: AliasesOther names for tables are called aliases. They are often handy as shorthand.16


select c.namefrom customers as c, orders as o, order_items as oi, books as bwhere c.customerid = o.customeridand o.orderid = oi.orderidand oi.isbn = b.isbnand b.title like ‘%Java%’;Retrieving Data in a Particular OrderIf you want to display rows retrieved by a query in a particular order, you can use the ORDERBY clause of the SELECT statement.<strong>This</strong> feature is handy for presenting output in a goodhuman-readable format.The ORDER BY clause sorts the rows on one or more of the columns listed in the SELECTclause. For example,select name, addressfrom customersorder by name;(= order by name asc;order by name desc;)<strong>This</strong> query returns customer names and addresses in alphabetical order by name, likethis:+-----------------+--------------------+| name | address |+-----------------+--------------------+| Alan Wong | 1/47 Haines Avenue || Julie Smith | 25 Oak Street || Michelle Arthur | 357 North Road |+-----------------+--------------------+17


Grouping and Aggregating Dataselect avg(amount)from orders;The output is something like this:+-------------+| avg(amount) |+-------------+| 54.985002 |+-------------+select customerid, avg(amount)from ordersgroup by customerid;When you use a GROUP BY clause with an aggregate function, it actually changes thebehavior of the function. Instead of giving an average of the order amounts across thetable,this query gives the average order amount for each customer (or, more specifically, for eachcustomerid):+------------+-------------+| customerid | avg(amount) |+------------+-------------+| 1 | 49.990002 || 2 | 74.980003 || 3 | 47.485002 |+------------+-------------+18


In addition to grouping and aggregating data, you can actually test the result of an aggregateby using a HAVING clause. It comes straight after the GROUP BY clause and is like aWHERE that applies only to groups and aggregates.To extend the previous example, if you want to know which customers have an average ordertotal of more than $50, you can use the following query:select customerid, avg(amount)from ordersgroup by customeridhaving avg(amount) > 50;Note that the HAVING clause applies to the groups.<strong>This</strong> query returns the following output:+------------+-------------+| customerid | avg(amount) |+------------+-------------+| 2 | 74.980003 |+------------+-------------+Using SubqueriesThe most common use of subqueries is to use the result of one query in a comparison inanother query. For example, if you wanted to find the order in which the amount ordered wasthe largest of any of the orders, you could use the following query:select customerid, amountfrom orderswhere amount = (select max(amount) from orders);<strong>This</strong> query gives the following results:+------------+--------+| customerid | amount |+------------+--------+| 2 | 74.98 |+------------+--------+One clause of the SELECT statement that can be particularly useful in Web applications isLIMIT. It is used to specify which rows from the output should be returned.<strong>This</strong> clause takestwo parameters: the row number from which to start and the number of rows to return.<strong>This</strong> query illustrates the use of LIMIT:select namefrom customerslimit 2, 3;<strong>This</strong> query can be read as, “Select name from customers, and then return 3 rows, starting fromrow 2 in the output.”19


Updating Records in the DatabaseIn addition to retrieving data from the database, you often want to change it.The usual form of an UPDATE statement isUPDATE [LOW_PRIORITY] [IGNORE] tablenameSET column1=expression1,column2=expression2,...[WHERE condition][ORDER BY order_criteria][LIMIT number]Let’s look at some examples. If you want to increase all the book prices by 10%, you can usean UPDATE statement without a WHERE clause:update booksset price = price*1.1;If, on the other hand, you want to change a single row—say, to update a customer’s address—you can do it like this:update customersset address = ‘250 Olsens Road’where customerid = 4;Altering Tables After CreationIn addition to updating rows, you might want to alter the structure of the tables within yourdatabase. For this purpose, you can use the flexible ALTER TABLE statement.Thebasic form of this statement is20


ALTER TABLE [IGNORE] tablename alteration [, alteration ...]21


Deleting Records from the DatabaseDeleting rows from the database is simple.You can do this using the DELETE statement,which generally looks like this:DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM table[WHERE condition][ORDER BY order_cols][LIMIT number]If you writedelete from table;on its own, all the rows in a table will be deleted, so be careful! Usually, you want to deletespecific rows, and you can specify the ones you want to delete with a WHERE clause:delete from customerswhere customerid=5;Dropping TablesAt times, you may want to get rid of an entire table.You can do this with the DROP TABLEstatement.<strong>This</strong> process is very simple, and it looks like this:22


DROP TABLE table;<strong>This</strong> query deletes all the rows in the table and the table itself, so be careful using it.Dropping a Whole DatabaseYou can go even further and eliminate an entire database with the DROP DATABASEstatement, which looks like this:DROP DATABASE database;<strong>This</strong> query deletes all the rows, all the tables, all the indexes, and the database itself, so it goeswithout saying that you should be somewhat careful using this statement.Accessing Your MySQL Database from the Web with PHPsearch.htmlBook-O-Rama Catalog SearchBook-O-Rama Catalog SearchChoose Search Type:AuthorTitleISBNEnter Search Term:results.phpBook-O-Rama Search ResultsBook-O-Rama Search Results


if (!$searchtype || !$searchterm) {echo 'You have not entered search details.Please go back and try again.';exit;}if (!get_magic_quotes_gpc()){$searchtype = addslashes($searchtype);$searchterm = addslashes($searchterm);}@ $db = new mysqli('localhost', 'bookorama', 'bookorama123','books');if (mysqli_connect_errno()) {echo 'Error: Could not connect to database. Please try againlater.';exit;}$query = "select * from books where ".$searchtype." like'%".$searchterm."%'";?>$result = $db->query($query);$num_results = $result->num_rows;echo "Number of books found: ".$num_results."";for ($i=0; $i fetch_assoc();echo "".($i+1).". Title: ";echo htmlspecialchars(stripslashes($row['title']));echo "Author: ";echo stripslashes($row['author']);echo "ISBN: ";echo stripslashes($row['isbn']);echo "Price: ";echo stripslashes($row['price']);echo "";}$result->free();$db->close();• You begin the script by stripping any whitespace that the user might haveinadvertently entered at the beginning or end of his search term.You do this byapplying the function trim().• You also use stripslashes() on the data coming back from the database. If themagic quotes feature is turned on, the data will have slashes in it when it comes backfrom the database, so you need to take them out.• If you prefer a procedural approach, mysqli allows for this, too. To connect in aprocedural fashion, you use24


@$db=mysqli_connect('localhost','bookorama','bookorama123','books');• If you want to change the default database, you can do so with themysqli_select_db() function. It can be accessed as either$db->select_db(dbname)or asmysqli_select_db(db_resource, db_name)• To actually perform the query, you can use the mysqli_query() function. Beforedoing this, however, it’s a good idea to set up the query you want to run:$query = "select * from books where ".$searchtype." like'%".$searchterm."%'";• You can now run the query:$result = $db->query($query);or, if you want to use the procedural interface, you use$result = mysqli_query($db, $query);• A large variety of functions is available to break the results out of the result object oridentifier in different ways.The result object or identifier is the key to accessing therows returned by the query. In this example, you counted the number of rows returnedand also used the mysqli_fetch_assoc() function. When you use the objectorientedapproach, the number of rows returned is stored in the num_rows memberof the result object, and you can access it as follows:$num_results = $result->num_rows;When you use a procedural approach, the function mysqli_num_rows() givesyou the number of rows returned by the query.You should pass it the result identifier,like this:$num_results = mysqli_num_rows($result);• It’s useful to know this if you plan to process or display the results, because you nowknow how many there are and can loop through them:for ($i=0; $i free();ormysqli_free_result($result);You can then use$db->close();ormysqli_close($db);to close a database connection.Putting New Information in the Database – na vježbamaTHE END ☺!25

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!