Beginning PHP6, Apache, MySQL Web Development- P5 potx

30 2K 0
Beginning PHP6, Apache, MySQL Web Development- P5 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 3: Using PHP with My SQL 91 Querying the Database Now that you have some data in the database, you probably want to retrieve it. You use the SELECT statement to choose data that fits your criteria. Typical syntax for this command is as follows: SELECT [ field names ] AS [ alias ] FROM [ tablename ] WHERE [ criteria ] ORDER BY [ fieldname to sort on ] [ASC|DESC] LIMIT [ offset , maxrows ] You can set numerous other parameters, but these are the most commonly used: SELECT [field names] : First decide what specific field names you want to retrieve. If you want to see them all, you can use * in place of the field names. AS : You use alias field names so that you can reference them later as different names. An example would be: SELECT movie_name, movie_year AS relase_year FROM movie FROM : You need to name the table or tables from which you are pulling the data. WHERE : List your criteria for filtering out the data, as described in the following section. ORDER BY : Use this parameter if you want the data sorted on a particular field. The results are returned in ascending order by default, though you can explicitly request ascending order with ASC . If you want the results returned in descending order, use DESC . LIMIT : This enables you to limit the number of results returned and offset the first record returned to whatever number you choose. An example would be: LIMIT 9, 10 This would show records 10 through 19. This is a useful feature for pagination (showing only a certain number of records on a page and then allowing the user to click a Next page link to see more). For a complete reference, we refer you to the official documentation at www.mysql.com . WHERE , oh WHERE The beast clause called WHERE deserves its own little section because it ’ s really the meat of the query. (No offense to the other clauses, but they are pretty much no brainers.) WHERE is like a cool big brother who can really do some interesting stuff. While SELECT tells MySQL which fields you want to see, WHERE tells it which records you want to see. It is used as follows: // retrieves all information about all customers SELECT * FROM customers; // retrieves all information about male customers SELECT * FROM customers WHERE gender = “Male” ❑ ❑ ❑ ❑ ❑ ❑ c03.indd 91c03.indd 91 12/10/08 5:46:09 PM12/10/08 5:46:09 PM 92 Part I: Movie Review Web Site Let ’ s look at the WHERE clause in a little more detail: Comparison operators are the heart of a WHERE clause and include the following: ❑ = is used to test if two values are equal ❑ != is used to test if two values are not equal ❑ < is used to test if one value is less than the second ❑ < = is used to test if one value is less than or equal to the second ❑ > is used to test if one value is greater than the second ❑ > = is used to test if one value is greater than or equal to the second ❑ LIKE lets you compare text and allows you to use % and _ as wildcards. Wildcards allow you to search even if you know a piece of what ’ s in the field but don ’ t know the entire value, or you don ’ t want an exact match. For example: SELECT * FROM products WHERE description LIKE “%shirt%” ❑ The WHERE clause in this query matches any records that have the text pattern “ shirt ” in the description column, such as “ t - shirt, ” “ blue shirts, ” or “ no shirt, no shoes, no service. ” Without the % wildcard, you would have those products that have a description of just “ shirt ” returned, and nothing else. Logical operators such as AND , NOT , OR , and XOR are also accepted in the WHERE clause: SELECT * FROM products WHERE description LIKE “%shirt%” AND price < = 24.95 This gives you all the products that have the word or text pattern of “ shirt ” in the description and that have a price of less than or equal to $24.95. Now that you understand how a SELECT query is written, let ’ s look at it in action, shall we? Try It Out Using the SELECT Query In this exercise, you ’ ll create a short script that demonstrates how the SELECT query works. 1. Open your text editor, and type this code: < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); // select the movie titles and their genre after 1990 $query = ‘SELECT movie_name, movie_type FROM movie WHERE ❑ ❑ c03.indd 92c03.indd 92 12/10/08 5:46:09 PM12/10/08 5:46:09 PM Chapter 3: Using PHP with My SQL 93 movie_year > 1990 ORDER BY movie_type’; $result = mysql_query($query, $db) or die(mysql_error($db)); // show the results while ($row = mysql_fetch_array($result)) { extract($row); echo $movie_name . ‘ - ‘ . $movie_type . ‘ < br/ > ’; } ? > 2. Save this file as select1.php , and then run it from your browser. How It Works You should see the screen shown in Figure 3 - 1 after running select1.php . Figure 3-1 First you had to connect to the MySQL server and the specific database. Then you planned out your query and assigned it to the $query variable. c03.indd 93c03.indd 93 12/10/08 5:46:09 PM12/10/08 5:46:09 PM 94 Part I: Movie Review Web Site You wanted to choose only the movie_name and movie_type fields from the movie table because you don ’ t care about seeing the rest of the information contained in the table at this time. If you had wanted to retrieve everything, you simply could have written: SELECT movie_id, movie_name, movie_type, movie_year, movie_leadactor, movie_ director FROM movie or even: SELECT * FROM movie The WHERE condition in your query limited the results to only movies filmed after 1990. You also asked the server to sort the results by movie type, with the ORDER clause. Then you issued the query to the MySQL server and stored the response in a variable, $result . $result = mysql_query($query, $db) or die(mysql_error($db)); Then, you looped through the results with a while loop: while ($row = mysql_fetch_array($result)) { extract($row); echo $movie_name . ‘ - ‘ . $movie_type . ‘ < br/ > ’; } You retrieved the row ’ s data as an array named $row for each row in the returned result set, using the mysql_fetch_array() function. You then extracted all the variables in $row , using the extract() function to find variables with the same name as the array ’ s keys; echo ed out what you needed; and then went on to the next row of results from your query. When there were no more rows that matched your criteria, the while loop ended. Pretty easy, eh? Let ’ s try using the foreach loop instead of the while function, and see how it works. Working with PHP and Arrays of Data: foreach The foreach loop is similar to the while loop, if you ’ re using while to loop through a list of results from your query. Its purpose is to apply a block of statements to every row in your results set. It is used in this way: foreach ($row as $value) { echo $value; echo ‘ < br > ’; } The preceding code would take all the variables in the $row array and list each value, with a line break in between them. You can see this in action in Chapters 4 and 5 and get a better idea of how it can be used. c03.indd 94c03.indd 94 12/10/08 5:46:11 PM12/10/08 5:46:11 PM Chapter 3: Using PHP with My SQL 95 Try It Out Using foreach This exercise contrasts foreach with the while you used in the previous exercise. 1. In your select1.php file, make the following highlighted changes: < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); // select the movie titles and their genre after 1990 $query = ‘SELECT movie_name, movie_type FROM movie WHERE movie_year > 1990 ORDER BY movie_type’; $result = mysql_query($query, $db) or die(mysql_error($db)); // show the results while ($row = mysql_fetch_assoc($result)) { foreach ($row as $value) { echo $value . ‘ ‘; } echo ‘ < br/ > ’; } ? > How It Works You should see the same results as before, except that there is now no dash between the elements. Pretty sneaky, huh? mysql_fetch_array actually returns two sets of arrays (one with associative indices, one with numerical indices), so you see duplicate values if you use foreach without first isolating one of the arrays. You can do this by using either mysql_fetch_array($result, MYSQL_ ASSOC) or mysql_fetch_assoc($result) to perform the same thing and return only one of the arrays. You still need to use the while function to proceed through the selected rows one at a time, but you can see that using foreach applies the same sets of commands to each value in the array, regardless of their contents. Sometimes you will need to have more control over a specific value, and therefore you can ’ t apply the same formatting rules to each value in the array, but the foreach function can also come in handy when using formatting functions, such as creating tables. In the following exercise, you ’ ll create another version of the select1.php program that illustrates this. c03.indd 95c03.indd 95 12/10/08 5:46:12 PM12/10/08 5:46:12 PM 96 Part I: Movie Review Web Site Try It Out Using foreach to Create a Table In this exercise, you ’ ll use foreach to apply some formatting rules to the results of your query. 1. Open your text editor, and enter the following script: < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); // select the movie titles and their genre after 1990 $query = ‘SELECT movie_name, movie_type FROM movie WHERE movie_year > 1990 ORDER BY movie_type’; $result = mysql_query($query, $db) or die(mysql_error($db)); // show the results echo ‘ < table border=”1” > ’; while ($row = mysql_fetch_assoc($result)) { echo ‘ < tr > ’; foreach ($row as $value) { echo ‘ < td > ’ . $value . ‘ < /td > ’; } echo ‘ < /tr > ’; } echo ‘ < /table > ’; ? > 2. Save this script as select2.php , and then open it in your browser. You should see something like Figure 3 - 2 . c03.indd 96c03.indd 96 12/10/08 5:46:12 PM12/10/08 5:46:12 PM Chapter 3: Using PHP with My SQL 97 Figure 3-2 How It Works You used the mysql_query() function and while loop to retrieve your desired records and fields. Then for each value you retrieved, you placed it in a separate table cell, using a foreach loop. You can see that this script would easily output a long string of array variables with a few lines of code, whereas if you had to echo out each separate variable with the accompanying HTML code, this script would be quite lengthy. A Tale of Two Tables The preceding code is all nice and neat and pretty, but it doesn ’ t do you a whole lot of good if you don ’ t have a secret decoder ring to tell you what those cryptic “ movie type ” numbers correspond to in plain English. That information is all stored in a separate table, the movietype table. So how do you get this information? You can get information from more than one table in two ways: Reference the individual tables in your query and link them temporarily through a common field. Formally JOIN the individual tables in your query. Let ’ s try out these methods and then talk about each of them in more detail. ❑ ❑ c03.indd 97c03.indd 97 12/10/08 5:46:12 PM12/10/08 5:46:12 PM 98 Part I: Movie Review Web Site Referencing Two Tables You can distinguish between two tables in your database by referencing them in the SELECT statement, as follows: // retrieves customers’ names from customers table and order_total from // orders table where the cust_ID field in the customers table equals the // cust_ID field in the orders table. SELECT customers.name, orders.order_total FROM customers, orders WHERE customers.cust_ID = orders.cust_ID If a customer ’ s ID is 123, you will see all the order_totals for all the orders for that specific customer, enabling you to determine all the money customer 123 has spent at your store. Although you are linking the two tables through the cust_ID field, the names do not have to be the same. You can compare any two field names from any two tables. An example would be: // retrieves customers’ names from customers table and order_total from // orders table where the email field in the customers table equals the // shiptoemail field in the orders table. SELECT customers.name, orders.order_total FROM customers, orders WHERE customers.email = orders.shiptoemail This would link your tables through the email and shiptoemail fields from different tables. Try It Out Referencing Individual Tables This exercise will show you how to reference multiple tables in your query. 1. Change your select2.php program as shown here (changes are highlighted): < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); // select the movie titles and their genre after 1990 $query = ‘SELECT movie.movie_name, movietype.movietype_label FROM movie, movietype WHERE c03.indd 98c03.indd 98 12/10/08 5:46:13 PM12/10/08 5:46:13 PM Chapter 3: Using PHP with My SQL 99 movie.movie_type = movietype.movietype_id AND movie_year > 1990 ORDER BY movie_type’; $result = mysql_query($query, $db) or die(mysql_error($db)); // show the results echo ‘ < table border=”1” > ’; while ($row = mysql_fetch_assoc($result)) { echo ‘ < tr > ’; foreach ($row as $value) { echo ‘ < td > ’ . $value . ‘ < /td > ’; } echo ‘ < /tr > ’; } echo ‘ < /table > ’; ? > 2. Save your script and run it. Your screen should look something like Figure 3 - 3 . Figure 3-3 c03.indd 99c03.indd 99 12/10/08 5:46:13 PM12/10/08 5:46:13 PM 100 Part I: Movie Review Web Site How It Works Now you can see a table with the movie names and actual words for the type of movie, instead of your cryptic code, as was the case in Figure 3 - 2 . The common fields were linked in the WHERE portion of the statement. ID numbers from the two different tables (fieldname movie_type in the movie table and fieldname movietype_id in the movietype table) represented the same thing, so that ’ s where you linked them together. Joining Two Tables In life as in code, regardless of the circumstances under which two things join together, it is rarely a simple thing. More often than not, it comes with conditions and consequences. In the world of MySQL, joins are also complex things. We will discuss joins in greater detail in Chapter 10 ; meanwhile, we walk you through a very simple and commonly used join so you can get a taste of what joining is all about. The JOIN function gives you greater control over how your database tables relate to and connect with each other, but it also requires a greater understanding of relational databases (another topic covered in Chapter 10 ). Try It Out Joining Two Tables In this exercise, you ’ ll link the two tables with a JOIN . 1. Make the following highlighted changes to select2.php : < ?php $db = mysql_connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_select_db(‘moviesite’, $db) or die(mysql_error($db)); // select the movie titles and their genre after 1990 $query = ‘SELECT movie_name, movietype_label FROM movie LEFT JOIN movietype ON movie_type = movietype_id WHERE movie.movie_type = movietype.movietype_id AND movie_year > 1990 ORDER BY movie_type’; $result = mysql_query($query, $db) or die(mysql_error($db)); // show the results echo ‘ < table border=”1” > ’; c03.indd 100c03.indd 100 12/10/08 5:46:15 PM12/10/08 5:46:15 PM [...]... documentation Once again, you can find the manual at www .mysql. com Using MySQL Query Browser Now that you’ve been given the task of learning MySQL and PHP on your own from scratch, we’re going to let you in on a dirty little secret called MySQL Query Browser MySQL Query Browser is another wonderful open source project that enables you to access your MySQL databases through a GUI desktop application It’s... fields ❑ Enter any MySQL statements ❑ View and print table structure ❑ Generate PHP code ❑ View data in table format You can download the software by visiting http://dev .mysql. com/downloads/ gui-tools/5.0.html MySQL Query Browser is part of the MySQL Tools package Figure 3-4 shows what MySQL Query Browser looks like 102 c03.indd 102 12/10/08 5:46:15 PM Chapter 3: Using PHP with MySQL Figure 3-4 Summar... $result = mysql_ query($query, $db) or die (mysql_ error($db)); $row = mysql_ fetch_assoc($result); extract($row); return $people_fullname; } // take in the id of a movie type and return the meaningful textual // description function get_movietype($type_id) { global $db; $query = ‘SELECT movietype_label FROM movietype WHERE movietype_id = ‘ $type_id; $result = mysql_ query($query, $db) or die (mysql_ error($db));... mysql_ query($query, $db) or die (mysql_ error($db)); $row = mysql_ fetch_assoc($result); extract($row); return $movietype_label; } //connect to MySQL $db = mysql_ connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect Check your connection parameters.’); // make sure you’re using the right database mysql_ select_db(‘moviesite’, $db) or die (mysql_ error($db)); // retrieve information $query = ‘SELECT... DECIMAL(4,1) NULL)’; mysql_ query($query, $db) or die (mysql_ error($db)); //insert new data into the movie table for each movie $query = ‘UPDATE movie SET movie_running_time = 101, movie_cost = 81, movie_takings = 242.6 WHERE movie_id = 1’; mysql_ query($query, $db) or die (mysql_ error($db)); $query = ‘UPDATE movie SET movie_running_time = 89, movie_cost = 10, movie_takings = 10.8 WHERE movie_id = 2’; mysql_ query($query,... records Then, output the number of movie records after the closing table tag Movie Review Database . < ?php $db = mysql_ connect(‘localhost’, ‘bp6am’, ‘bp6ampass’) or die (‘Unable to connect. Check your connection parameters.’); mysql_ select_db(‘moviesite’, $db) or die (mysql_ error($db)); . movie_year > 1990 ORDER BY movie_type’; $result = mysql_ query($query, $db) or die (mysql_ error($db)); // show the results while ($row = mysql_ fetch_array($result)) { extract($row); echo. clause. Then you issued the query to the MySQL server and stored the response in a variable, $result . $result = mysql_ query($query, $db) or die (mysql_ error($db)); Then, you looped through

Ngày đăng: 03/07/2014, 07:20

Từ khóa liên quan

Mục lục

  • cover.pdf

  • page_c1.pdf

  • page_r01.pdf

  • page_r02.pdf

  • page_r03.pdf

  • page_r04.pdf

  • page_r05.pdf

  • page_r06.pdf

  • page_r07.pdf

  • page_r08.pdf

  • page_r09.pdf

  • page_r10.pdf

  • page_r11.pdf

  • page_r12.pdf

  • page_r13.pdf

  • page_r14.pdf

  • page_r15.pdf

  • page_r16.pdf

  • page_r17.pdf

  • page_r18.pdf

Tài liệu cùng người dùng

Tài liệu liên quan