1. Trang chủ
  2. » Công Nghệ Thông Tin

Sams Teach Yourself PHP, MySQL and Apache in 24 Hours phần 4 docx

73 250 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 73
Dung lượng 4,33 MB

Nội dung

Because the mysql_query function only returns a true or false result, the boring output of this script is 1 The 1 equals true , and indicates that the query was successfully executed. A 0 would have indicated failure. Access MySQL through the command-line interface to verify the creation of the testTable table: mysql> describe testTable; + + + + + + + | Field | Type | Null | Key | Default | Extra | + + + + + + + | id | int(11) | | PRI | NULL | auto_increment | | testField | varchar(75) | YES | | NULL | | + + + + + + + 2 rows in set (0.00 sec) Congratulations—you have successfully created a table in your MySQL database using PHP! Retrieving Error Messages Take some time to familiarize yourself with the mysql_error() function, as it will become your friend. When used in conjunction with the PHP die() function, which simply exits the script at the point at which it appears, the mysql_error() function will return a helpful error message when you make a mistake. For example, now that you have created a table called testTable , you won't be able to execute that script again without an error. Let's try to execute the script again, but modify it first to utilize the mysql_error() function (see Listing 8.5 ). Listing 8.5 The Script to Create a Table, with Error Messages 1: <?php 2: // open the connection 3: $conn = mysql_connect("localhost", "joeuser", "somepass"); 4: // pick the database to use 5: mysql_select_db("testDB",$conn); 6: // create the SQL statement 7: $sql = "CREATE TABLE testTable (id int not null primary key auto_increment, 8: testField varchar (75))"; 9: // execute the SQL statement 10: $result = mysql_query($sql, $conn) or die(mysql_error()); 11: // echo the result identifier 12: echo $result; 13: ?> When you execute the script, you should see something like the following in your Web browser: Table 'testTable' already exists How exciting! Move on to the next section to start inserting data into your table, and soon you'll be retrieving and formatting it via PHP. [ Team LiB ] [ Team LiB ] Working with MySQL Data Inserting, updating, deleting, and retrieving data all revolve around the use of the mysql_query() function to execute the basic SQL queries. For INSERT , UPDATE , and DELETE , no additional scripting is required after the query has been executed because you're not displaying any results (unless you want to). For SELECT , you have a few options for displaying the data retrieved by your query. Let's start with the basics and insert some data, so you'll have something to retrieve later on. Inserting Data with PHP The easiest method for inserting data is to simply hard-code the INSERT statement, as shown in Listing 8.6 . Listing 8.6 A Script to Insert a Record 1: <?php 2: // open the connection 3: $conn = mysql_connect("localhost", "joeuser", "somepass"); 4: // pick the database to use 5: mysql_select_db("testDB",$conn); 6: // create the SQL statement 7: $sql = "INSERT INTO testTable values ('', 'some value')"; 8: // execute the SQL statement 9: $result = mysql_query($sql, $conn) or die(mysql_error()); 10: // echo the result identifier 11: echo $result; 12: ?> You might wonder why you need to echo the result identifier if you're just inserting data. Well, you don't have to; it's just there for kicks. You can clean this script up a bit by replacing the query execution line so that it simply executes and prints a relevant statement if successful, as shown in Listing 8.7 . Listing 8.7 The Modified Insert Script 1: <?php 2: // open the connection 3: $conn = mysql_connect("localhost", "joeuser", "somepass"); 2: // open the connection 3: $conn = mysql_connect("localhost", "joeuser", "somepass"); 4: // pick the database to use 5: mysql_select_db("testDB",$conn); 6: // create the SQL statement 7: $sql = "INSERT INTO testTable values ('', '$_POST[testField]')"; 8: // execute the SQL statement 9: if (mysql_query($sql, $conn)) { 10: echo "record added!"; 11: } else { 12: echo "something went wrong"; 13: } 14: ?> Save the script as insert.php , and put it in the document root of your Web server. In your Web browser, access the HTML form that you created. It should look something like Figure 8.1 . Figure 8.1. The HTML form for adding a record. Enter a string in the "Text to add" field, as shown in Figure 8.2 . Figure 8.2. Text typed in the form field. Finally, press the Insert Record button to execute the insert.php script and insert the record. If successful, you will see results similar to Figure 8.3 . Figure 8.3. The record has been successfully added. To verify your work, you can use the MySQL command-line interface to view the records in the table: mysql> select * from testTable; + + + | id | testField | + + + | 1 | some value | | 2 | this is some text! | + + + 2 rows in set (0.00 sec) Next, you'll learn how to retrieve and format results with PHP. Retrieving Data with PHP Because you have a few rows in your testTable table, you can write a PHP script to retrieve that data. Starting with the basics, write a script that issues a SELECT query but doesn't overwhelm you with result data; let's just get the number of rows. To do this, use the mysql_num_rows() function. This function requires a result, so when you execute the query, put the result index in $result (see Listing 8.10 ). Listing 8.10 A Script to Retrieve Data 1: <?php 2: // open the connection 3: $conn = mysql_connect("localhost", "joeuser", "somepass"); 4: // pick the database to use 5: mysql_select_db("testDB",$conn); 6: // create the SQL statement 7: $sql = "SELECT * FROM testTable"; 8: // execute the SQL statement 9: $result = mysql_query($sql, $conn) or die(mysql_error()); 10: //get the number of rows in the result set 11: $number_of_rows = mysql_num_rows($result); 12: echo "The number of rows is $number_of_rows"; 13: ?> Save this script as count.php , place it in your Web server document directory, and access it through your Web browser. You should see a message like this: The number of rows is 2 The number should be equal to the number of records you inserted during testing. Now that you know there are some records in the table, you can get fancy and fetch the actual contents of those records. You can do this in a few ways, but the easiest method is to retrieve each row as an array. What you'll be doing is using a while statement to go through each record in the resultset, place the values of each field into a specific variable, then display the results onscreen. The syntax of mysql_fetch_array() is $newArray = mysql_fetch_array($result); Follow along using the sample script in Listing 8.11 . Listing 8.11 A Script to Retrieve Data and Display Results 1: <?php 2: // open the connection 3: $conn = mysql_connect("localhost", "joeuser", "somepass"); 4: // pick the database to use 5: mysql_select_db("testDB",$conn); 6: // create the SQL statement 7: $sql = "SELECT * FROM testTable"; 8: // execute the SQL statement 9: $result = mysql_query($sql, $conn) or die(mysql_error()); 10: //go through each row in the result set and display data 11: while ($newArray = mysql_fetch_array($result)) { 12: // give a name to the fields 13: $id = $newArray['id']; 14: $testField = $newArray['testField']; 15: //echo the results onscreen 16: echo "The ID is $id and the text is $testField <br>"; 17: } 18: ?> Save this script as select.php , place it in your Web server document directory, and access it through your Web browser. You should see a message for each record entered into testTable , as shown in Figure 8.4 . Figure 8.4. Selecting records from MySQL. Essentially, you can create an entire database-driven application using just four or five MySQL functions. This hour has barely scratched the surface of using PHP with MySQL; there are many more MySQL functions in PHP, as you'll learn in the next section. Additional MySQL Functions in PHP There are approximately 40 MySQL-specific functions in PHP. Most of these functions are simply alternate methods of retrieving data or are used to gather information about the table structure in question. For a complete list of functions, with practical examples, visit the MySQL section of the PHP Manual at http://www.php.net/manual/en/ref.mysql.php . [ Team LiB ] [ Team LiB ] Summary Using PHP and MySQL to create dynamic, database-driven Web sites is a breeze. Just remember that the PHP functions are essentially a gateway to the database server; anything you'd enter using the MySQL command-line interface, you can use with mysql_query(). To connect to MySQL with PHP, you need to know your MySQL username, password, and database name. Using mysql_connect() and mysql_select_db(), you can connect to and select a database to use throughout the life of the script. Once connected, you can issue standard SQL commands with the mysql_query() function. If you have issued a SELECT command, you can use mysql_numrows() to count the records returned in the resultset. If you want to display the data found, you can use mysql_fetch_array() to get all the results during a loop and display them onscreen. [ Team LiB ] [...]... multiple choices using the option elements on lines 15 through 18 We demonstrate that the user's choices are made available in an array in Listing 9.5 Listing 9.5 Reading Input from the Form in Listing 9 .4 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: Listing 9.5 Reading input from the form in Listing 9 .4 . be retrieving and formatting it via PHP. [ Team LiB ] [ Team LiB ] Working with MySQL Data Inserting, updating, deleting, and retrieving data all revolve around the use of the mysql_ query() function. server; anything you'd enter using the MySQL command-line interface, you can use with mysql_ query(). To connect to MySQL with PHP, you need to know your MySQL username, password, and database name 9.1. In this listing, we declare three variables (lines 7-9) and then loop through the built -in $GLOBALS associative array (lines 10 and 11), writing both array keys and values to the browser. In

Ngày đăng: 13/08/2014, 21:21