1 / 47

LIS651 lecture 2 mySQL and PHP mySQL function

Thomas Krichel 2005-11-04. LIS651 lecture 2 mySQL and PHP mySQL function. using mySQL. mySQL is installed on wotan. Normally this involves logging into wotan and issuing commands to a character interface. The command would be mysql -u user -p. create database.

karinep
Download Presentation

LIS651 lecture 2 mySQL and PHP mySQL function

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Thomas Krichel 2005-11-04 LIS651 lecture 2mySQL and PHP mySQL function

  2. using mySQL • mySQL is installed on wotan. • Normally this involves logging into wotan and issuing commands to a character interface. • The command would be • mysql -u user -p

  3. create database • This is a mySQL command to create a new database. • Example create database newbase; • creates a database newbase

  4. GRANT • This is a command to create users and give them privileges. A simplified general syntax is GRANT privileges [columns] ON item TO user_name [IDENTIFIED BY 'password'] [WITH GRANT OPTION] • If you use WITH GRANT OPTION, you allow the user to grant other users the privileges that you have given to her.

  5. user privileges I • SELECT allows users to select (read) records from tables. Generally select is a word used for read in databases. • INSERT allows users to insert new rows into tables. • UPDATE allows users to change values in existing table rows. • DELETE allows users to delete table rows (records) • INDEX allows user to index tables

  6. user privileges II • ALTER allows users to change the structure of the database. • adding columns • renaming columns or tables • changing the data types of tables • DROP allows users to delete databases or tables. In general, the word drop refers to deleting database or tables.

  7. user privileges III • CREATE allows users to create new databases or tables. If a specific table or database is mentioned in the GRANT statement, users can only create that database or table, which will mean that they have to drop it first. • USAGE allows users nothing. This is a useful point to start with if you just want to create a user.

  8. REVOKE • This is the opposite of GRANT.

  9. current setup • As the super user, I did create database user_name; GRANT * ON user_name TO user_name IDENTIFIED BY 'secret_word' WITH GRANT OPTION; • Here • user_name is your wotan user name • secret_word is your secret word • * means all rights

  10. create a web user • You do not want to give the same access rights to people coming in from the web as you have. • You do not want to do this. You personally have too many privileges. • I have yet to find out how you can create a web user by yourself.

  11. creating tables • before you do it, set up some examples on a sheet of paper. • Here is an example CREATE TABLE customers (custumer_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, name CHAR(50) NOT NULL, ADDRESS CHAR(100) not NULL, email CHAR(40), STATE char(2) not NULL);

  12. column data types • TINYINT can hold a number between -128 and 127 or between 0 to 255. BIT or BOOL are synonyms for the TINYINT. • SMALLINT can hold a number between -32768 and +32767 or 0 and 65535 • INT can hold a number between -2**31 and 2**31-1 or between 0 and 2**32-1. INTEGER is a synonym for INT. • BIGINT can hold a number between -2**63 and 2**61-1 or between 0 and 2**64-1.

  13. column data types: float • FLOAT is a floating number on 4 bytes • DOUBLE is a floating number on 8 bytes

  14. column data types: dates • DATE is a day from 1000-01-01 to 9999-12-31. • TIME is a time from -838:59:59 to 838:59:59 • DATETIME is a data and time, usually displayed as YYYY-MM-DD HH:MM:SS • TIMESTAMP is the number of seconds since 1970-01-01 at 0 hours. This number may run out in 2037.

  15. field options • PRIMARY KEY says that this column is a the primary key. There can be only one such column. Values in the column must be unique. • AUTO_INCREMENT can be used on columns that contain integer values.

  16. USE • USE database tells mySQL to start working with the database database. • If you have not issued a USE command, you can still address a table table by using database.table, i.e. using the dot to link the two together.

  17. addressing database tables columns • Let there by a database database with a table table and some column column. Then it is addressed as database.table.column. • Parts of this notation can be left out if it is clear what is meant, for example if you have issued USE database before, you can leave out the database part.

  18. INSERT • INSERT inserts values. In its simples form INSERT INTO table VALUES (value1, value2, ..); Example: INSERT INTO products VALUES ('','Neufang Pils',1.23); • Note that in the example, I insert the null string in the first column because it is an auto_increment.

  19. partial INSERT • If you are only giving a part of a record, or if you want to enter them in a different order you will have to give a list of column names. INSERT INTO products (name,id) VALUES ('Neufang Pils','');

  20. SELECT • This is the SQL statement to select rows from a table. Here is the full syntax: SELECT [options] columns [INTO file_details] FROM table [WHERE conditions] [GROUP BY group_type] [HAVING where_definitions] [ORDER BY order_type] [LIMIT limit_criteria] [PROCEDURE proc_name(arguments)] [lock_options]

  21. columns to SELECT • You can have a comma-separated list of columns SELECT name, price FROM products; • You can use the star to get all columns SELECT * FROM products;

  22. WHERE condition to SELECT • = means equality WHERE id = 3 • >, <, >=, <= and != also work as expected • IS NULL tests if the value is null • IS NOT NULL • IN allows you to give a set WHERE state IN ("NY","NJ","CT")

  23. SELECT using multiple tables • table1,table2 can be used to join both tables to build a big table that can be searched SELECT orders.id FROM customers, orders WHERE customers.id= 3 • This type of join is a Cartesian product aka a full join. For each row of the first table, it adds rows from the second table.

  24. complicated queries • who ordered Bruch Landbock? SELECT customer.id from customers, orders, orders_items, products WHERE customers.id=orders.customer_id AND orders.id=orders_items.order_id AND orders_items.item_id=products_id AND products.name='Bruch Landbock'

  25. left join • Another way to join tables is to join them "on" some column. SELECT customers.name FROM customers LEFT JOIN orders ON customers.id = orders.customerid AND orders.id IS NULL • The joint table is filled with NULL for those costumers who have not placed an order yet. It is also known as a left outer join.

  26. table example • Table A Table B A1 A2 B1 B2 B3 1 4 2 3 4 4 5 6 7 3 6 3 1 1 4 • Left outer join by A2 and B3 is A1 A2 B1 B2 B3 1 4 2 3 4 1 4 1 1 4 4 5 6 3 6 7 3

  27. aliases • You can use AS to create aliases. If you want to find out which customers live in the same city as another customer select c1.name, c2.name, c1.city FROM customers AS c1, customers AS c2 WHERE c1.city = c2.city AND c1.name != c2.name

  28. ORDER • You can order by a field by saying ORDER BY. • You can add ASC or DESC to achieve ascending or descending order. SELECT name, address FROM customers ORDER BY name ASC

  29. column functions • AVG(column) give average of the column • COUNT(column) gives you a count of non NULL values • COUNT(DISTINCT column) gives a count of distinct values • MIN(column), MAX(column) • STD(column) gives the standard deviation • SUM(column) gives the sum of the items

  30. column functions and grouping • You can use the function on the columns SELECT AVG(amount) FROM orders; • You can group the selection. For example, find the minimum for each customer SELECT MIN(amount) FROM orders GROUP BY customerid; • You can use them in conditions with HAVING, such as SELECT customerid FROM orders HAVING AVG(amount) > 10;

  31. LIMIT • This can be used to limit the amount of rows. LIMIT 10 19 • This is useful it web sites where you show a selection of the results. • This ends the discussion of the SELECT command.

  32. UPDATE • The general syntax is UPDATE [LOW_PRIORITY] [IGNORE] table SET column1=expession1, column2=expression2... [WHERE condition] [ORDER BY order_criteria] [LIMIT number]. An example is UPDATE students SET email= 'phpguru@gmail.com' WHERE name='Janice Insinga'; • IGNORE instructs to ignore errors. • LOW_PRIORITY instructs to delay if the server is busy.

  33. DELETE • The general syntax is DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM table [WHERE condition] [ORDER BY order_criteria] [LIMIT number] • Bad example DELETE FROM customers; • Good example DELETE FROM customers WHERE customer.name='Thomas Krichel'

  34. PHP mySQL functions • We are using here the new version of PHP mySQL function, starting with mysqli_ • The "i" stands for improved. • The interface is object-oriented, but can also be accessed in a non-object-oriented way. This is knows as the procedural style, in the documentation. • You should use the online documentation.

  35. mysqli_connect() • This is used to establish a connection to the mySQL server. It is typically of the form mysql_connect('host', 'user', 'password'); • Example $link= mysql_connect('localhost','boozer','heineken'); • You can use localhost as the host name for wotan talking to itself, but you could also connect to other Internet hosts, if you have permission. • The function returns a variable of type “resource”. If there is a mistake, it returns false.

  36. mysqli_connect_error () • This function returns a string with the last connection error. $link = mysqli_connect("localhost", "bad_user", "");if (!$link) {print "Can't connect to localhost. The error is<br>"; print mysqli_connect_error(); print "<br/>"; }

  37. mysqli_error() • This function return the error from the last mySQL command. You have to give the resource that represents the connection as an argument to the function $error=mysqli_error($link); if($error) { print "mySQL error: $error<br/>"; } • The value returned from that function is a simple string. • It is a good idea to check out error messages.

  38. mysqli_select_db() • This command has the syntax mysql_select_db('database') where database is the name of a database. • It returns a Boolean. • This tells mySQL that you now want to use the database database. mysqli_select_db('beer_shop'); • It has the same effect as issuing USE beer_shop; within mySQL.

  39. mysqli_query() • mysqli_query(link,query) send the query query to the connection identified by link. link is the value returned by a mySQL connection established earlier. $link = mysqli_connect("localhost", "shop_owner", "bruch"); // you may then add some connection checks $query="SELECT * FROM beer_shop.customers"; $result=mysqli_query($link,$query); • Note that the query itself does not require a terminating semicolon. • The result is in $result.

  40. result of mysqli_query() • For SELECT, SHOW, DESCRIBE or EXPLAIN mySQL queries, mysqli_query() returns a resource that can be further examined with mysqli_fetch_array(). • For UPDATE, DELETE, DROP and others, mysqli_query() returns a Boolean value.

  41. mysqli_fetch_array() • mysqli_fetch_array(resource) returns an array that is the result row for the resource resource representing the most recent, or NULL if it the last result is reached. Its results in an array that contains the columns requested both by number and by column name: while($columns=mysqli_fetch_array($result)) { print 'name: '.$columns['name']; print 'first column: $columns[0]; }

  42. utility function from php.net function mysqli_fetch_all($query) { $r=@mysqli_query($query); if($err=mysqli_error()) { return $err;} if(mysqli_num_rows($r)) { while($row=mysqli_fetch_array($r)) {$result[]=$row; } return $result;}} // usage if(is_array($rows=mysqli_fetch_all($query)) { // do something } else { if (! is_null($rows)) { die("Query failed!");} }

  43. mysqli_data_seek(); • mysqli_data_seek(result, number) sets the array that is returned by mysqli_fetch_array to a number number. while($row=mysqli_fetch_array($result)) { print 'first column: '.$row[0]; } mysqli_data_seek($result,0); // otherwise the second loop would not work while($row=mysqli_fetch_array($result)) { print 'first column: '.$row[0]; }

  44. mysqli_real_escape_string() • mysqli_real_escape_string(string) returns a string escaped for the using in mySQL. $name="John O'Guiness"; $s_name=mysqli_real_escape_string($name); print $s_name; // prints: John O\'Guiness • Note that this function makes a call to mySQL, therefore a connection must be established before the function can be used. • This function guards against SQL injections.

  45. mysqli_close() • This command connection. When it is invoked without an argument, it closes the current connection. • This is the happiest command there is, because it means that we have finished. • Unfortunately it is not used very often because the mySQL connection is closed automatically when the script finishes running.

  46. extra: sha1() • This is a function that calculates a combination of 40 characters from a string. • The result of sha1() can not be translated back into the original string. • This makes it a good way to store password. • $s_password=sha1($password);

  47. Thank you for your attention! Please switch off machines b4 leaving! http://openlib.org/home/krichel

More Related