Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practical Database Programming With Java

.pdf
Скачиваний:
790
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

5.3 Exploring NetBeans IDE 6.8 289

Figure 5.134. The connection information.

1.

Launch NetBeans IDE and open the Services window.

2.

Expand the Drivers node and right click on MySQL icon; select the Connect Using

 

item from the pop-up menu to open the New Database Connection wizard.

3.On the opened wizard, enter the MySQL database-related information into the associated fields, as shown in Figure 5.134. Make sure to check both Show JDBC URL and Remember password checkboxes.The password you need to enter to the Password field is reback, which is created when we downloaded and configured the MySQL database in the last section.

Click on the OK button to complete this process. Immediately, you can find a new connection URL jdbc:mysql://localhost:3306/MySQL [root on Default schema] added into the Services window.

4.Right click on that connection URL and select the Execute Command item from the pop-up menu to open the SQL Command window.

5.In the opened SQL Command window, enter the codes shown below into this window:

CREATE USER ′php_user′@′localhost′ IDENTIFIED BY ′!php_user′

6.Highlight two lines of codes above and right click on them,and choose the Run Selection item from the popup menu to run these two coding lines. If the command is executed suc-

cessfully, the Status bar shows the message: “SQL Statement(s) executed successfully”. If another message is displayed, check the syntax and follow the message hints.

Step 6 is necessary since you must create a user before you can create a MySQL database. The user can grant the right to perform any operations on the database.

290 Chapter 5 Introduction to NetBeans IDE

Figure 5.135. The opened Create MySQL Database wizard.

Note: To run SQL statements in the SQL Command window, you can only run them one time. An error may be encountered if you try to run statements more than one time.

Now we have created our database user named php_user identified by !php_user, next, we need to create our MySQL sample database MySQLSample to be used in this PHP application project.

5.3.7.9 Creating Our Sample Database MySQLSample

Perform the following operations to create this sample database MySQLSample:

1. Navigate to the MySQL Server at localhost:3306 [root] node,which is under the Databases icon in the Services window, and from the context menu choose Create Database item. The Create MySQL Database dialog box appears, as shown in Figure 5.135. Fill in the fields:

A.In the Database Name field, enter MySQLSample.

B.Switch on the Grant Full Access To checkbox, and from the drop-down list select php_user@localhost, and then click on the OK button.

Your finished Create MySQL Database wizard should match one that is shown in Figure 5.135.

2.AnewdatabaseconnectionURL,jdbc:mysql://localhost:3306/MySQLSample [root on Default schema] has been created and added into the Services window.

We need to create two tables in this sample database: LogIn and Customer. The relationship between these two tables is shown in Figure 5.136.

Now let’s create these two tables in NetBeans IDE.

Right click on our MySQLSampledatabase URL jdbc:mysql://localhost:3306/ MySQLSample [root on Default schema] from the Services window and select

Execute Command from the pop-up menu to open a blank SQL Command window.

Enter the codes that are shown in Figure 5.137 into this SQL Command window. Click on the Run SQL button on the toolbar to execute this piece of SQL command to create our LogIn table.

In a similar way, create the second table Customer by entering the codes that are shown in Figure 5.138 into the blank SQL Command window.

5.3 Exploring NetBeans IDE 6.8 291

LogIn

PK id

custName passWord

Customer

PK id

FK customerId Address Email Phone

Figure 5.136. The relationship between two tables.

CREATE TABLE LogIn(

id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,

custName CHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL UNIQUE, passWord CHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL

)

Figure 5.137. The codes used to create the Login table.

CREATE TABLE Customer(

id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, customerId INT NOT NULL,

Address CHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, Email CHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, Phone CHAR(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, FOREIGN KEY (customerId) REFERENCES LogIn(id)

)

Figure 5.138. The codes used to create the Customer table.

Click on the Run SQL button on the toolbar to execute this piece of SQL command to create our Customer table.

Now let’s enter data into these two tables to complete this table creation process.

Perform the following operations to insert data for these two tables:

1. On the jdbc:mysql://localhost:3306/MySQLSample [root on Default schema] connection, click the right mouse button and choose Execute Command to open an empty SQL Command window.

2.Enter the codes shown below into this empty window:

INSERT INTO LogIn(custName, passWord) VALUES (White, ‘tomorrow);

INSERT INTO LogIn(custName, passWord) VALUES (Jerry, ‘test);

INSERT INTO LogIn(custName, passWord) VALUES (CameraBuyer, 12345);

3.Click on the Run SQL button on the toolbar to execute this piece of SQL command to insert these data into the LogIn table.

292 Chapter 5 Introduction to NetBeans IDE

These statements do not contain a value for the id field in the LogIn table, since these id values are entered automatically by the database engine because the field type is specified as AUTO_INCREMENT (refer to Fig. 5.137).

4. Perform a similar operation to insert the codes shown below into the Customer table:

INSERT INTO Customer (customerId, Address, Email, Phone)

VALUES (1, 101 Main Street, product@coming.org, 750-380-5577);

INSERT INTO Customer (customerId, Address, Email, Phone)

VALUES (1, 205 Morone Street, forsale@cat.net, 800-777-7788);

INSERT INTO Customer (customerId, Address, Email, Phone)

VALUES (2, 501 DeerField Beach, fish@see.net, 800-799-7600);

INSERT INTO Customer (customerId, Address, Email, Phone)

VALUES (3, 353 Linkfield Dr, field@vetcory.com, 700-777-2255);

5.Click on the Run SQL button on the toolbar to execute this piece of SQL command to insert these data into the Customer table.

Now go to the Services window and you should find two tables, LogIn and Customer, which have been added into our sample database MySQLSample. If not, right click on our sample database mysqlsample under the URL jdbc:mysql://localhost:3306/MySQLSample [root on Default schema] and select the Refresh item to get these two tables.

To see the detailed content of these two tables, right click on each of them and select the View Data item from the pop-up menu to open each of them. An opened Customer table is shown in Figure 5.139.

Next, let’s add the functions to this PHP project to perform desired data actions between our PHP project and our sample database MySQLSample we created in this section.

Figure 5.139. The content of the Customer table.

5.3 Exploring NetBeans IDE 6.8 293

5.3.7.10 Building the Functions for the PHP Project

In this PHP project, we want to use the index.php file and create another PHP file, customerDetails.php, to perform the following functions:

1.By using the index.php file, we can enter a desired customer name to try to find a matched customer ID in the Customer table in our sample database.

2.By using the customerDetails.php file, we can retrieve all details about the selected customerID from the index.php file.

3.An error message will be given if no matched customerID can be found from the

Customer table.

By using these two files, we can

Displaying a page with controls for entering customer ID.

Transferring the entered data to the customerDetails.php page.

Now let’s create our next PHP file customerDetails.php. Perform the following operations to complete this creation process:

1.Start the NetBeans IDE 6.8 if it is not started.

2.In the Projects window, browse to our new PHP project PHPCustomer, and right click

on the folder Source Files that is under our PHPCustomer project and choose New > PHP File menu item from the popup menu.

3.On the opened New PHP File wizard, enter customerDetails into the File Name

field and click on the Finish button.

Now that a new PHP file has been created, next, let’s handle the data transferring between the index.php page and the customerDetails.php page.

5.3.7.10.1 Transferring Data from index.php to the customerDetails.php The data (customerID) is received and processed on the destination page, customerDetails.php. In this application, the data is entered on the index page (index.php) and transferred to the customerDetails.php page.We need to implement data transferring in index.php and data reception in customerDetails.php.

Enter the codes that are shown in Figure 5.140 into the body of the index.php file. The newly added codes have been highlighted in gray background.

Let’s take a closer look at this piece of newly added codes to see how it works.

The opening <form> tag that contains the action field for entering the name of the file where the data must be transferred (customerDetails.php) and the method to be applied to transferring data (GET). PHP will creates a special array $_GET and populate there values of the fields from the original form.

• The text that appears on the page: Show customer Name of:

A text input field for entering the customer name that will be matched to a customerID in the Customer table. The name “user” is the key to pick up the data on the destination form.

294 Chapter 5 Introduction to NetBeans IDE

Figure 5.140. The added codes to the index.php file.

Figure 5.141. The running result of the index.php page.

An input field of the submit type with the text Go. The type of submit means that the input field appears on the page as a button, and the data is transferred when exactly this control is affected.

Now let’s test this starting page by right clicking on the index.php in the Projects window, and select the Run item from the popup menu. The running result is shown in Figure 5.141.

In the Show Customer Name of: edit box, enter Tom, and click on Go. An empty page with the following URL appears: http://localhost:800/PHPCustomer/ customerDetails.php?user=Tom. This URL indicates that your main page works properly.

5.3.7.10.2 Receiving and Processing Data in the customerDetails.php Page As you can see from Figure 5.140, the index.php file did not contain any PHP code, so we have removed the codes inside the <?php ... ?> block and replaced them with a set

5.3 Exploring NetBeans IDE 6.8 295

<html>

A<body>Customer Name of <?php echo $_GET["user"]."<br/>";?> <?php

B$con = mysql_connect("localhost", "php_user", "!php_user");

Cif (!$con) {

die('Could not connect: ' . mysql_error());

}

Dmysql_query("SET NAMES 'utf8'");

Emysql_select_db("MySQLSample", $con);

F$custId = mysql_query("SELECT id FROM LogIn WHERE custName='".mysql_real_escape_string($_GET["user"])."'");

Gif (mysql_num_rows($custId)<1) {

die("The person " .$_GET["user"]. " is not found. Please check the spelling and try again" );

}

H $customerID = mysql_result($custId, 0); ?>

</body>

</html>

Figure 5.142. The codes for the customerDetails.php page.

of HTML codes in a form. This means that all functions in the index.php page can be fulfilled by using the HTML codes.

However, in the destination page, customerDetails.php, we need to use PHP and HTML codes together to perform the receiving data (customer ID) and retrieving the details related to the received customer ID and displaying them in this page.

Perform the following operations to complete the coding for this page:

1.Double click the customerDetails.php file from the Projects window. The template that opens is different from index.php. Begin and end the file with <html> </html> and <body></body> tags as the file will contain HTML code, too.

2.Enter the codes that are shown in Figure 5.142 into this page.

Let’s have a closer look at this piece of newly added codes to see how it works.

A.Starting from an HTML code block, the title of this page is displayed first. The echo and GET[] PHP commands are used to display the transferred customer name from the index.php page. This piece of PHP codes is embedded inside the HTML codes.

B.The database connection is executed inside a PHP block with the mysql_connect() PHP function being called. The returned connection is assigned to a PHP local variable $con. The point is that all variables in PHP start with a $ sign symbol. In fact, you can use the username and password to replace the last two arguments of this function to perform this connection, such as:

$con = mysql_connect(“localhost”, “root”, “reback”);

C.If any error occurred during this connection process, the PHP die() function is called to display this situation and exit this script. Generally, the functionality of the die() function is to print a message and exits the current script. The PHP function mysql_error() is called to display the error source.

D.The PHP function mysql_query() is executed to perform a query to set up the customer’s name in a utf8 format.

E.The PHP function mysql_select_db() is executed to select our target database MySQLSample we built in Section 5.3.7.9.

296Chapter 5 Introduction to NetBeans IDE

F.A MySQL query is executed to get matched id from the LogIn table based on the customer name entered by the user in the index.php page.A PHP MySQL-related function, mysql_real_escape_string(), is executed to pick up the customer name using the GET[] function. The mysql_real_escape_string() function escapes special characters in a string for use in an SQL statement. Since this function returns a string, a single quotation mark must be used to cover this string. The returned id is assigned to a local variable $cusId.

G.If this execution returns nothing, the PHP function mysql_num_rows() will return a 0, which means that this query has something wrong, the die() function is called to display this situation.

H.The queried id is assigned to another local variable $customerID if this query is successful.

For more detailed information about PHP and related MySQL functions in PHP, refer to the site: http://www.w3schools.com/php/default.asp.

You can compile and build the project by clicking on the Clean and Build Main Project button from the toolbar. A successful building result will be displayed in the Output window if everything is fine.

Now let’s add the additional codes to this page to display the running result for this data transferring. Insert the codes that are shown in Figure 5.143 into this customerDetails.php, exactly, between the PHP ending mark ?> and the body ending mark </body>,as shown in Figure 5.143.The newly inserted codes have been highlighted in bold.

Let’s have a closer look at this piece of inserted codes to see how it works.

A.A table HTML tab is used to create a table with the black color as the border.

B.This table has four columns with headers of CustomerID, Address, Email, and Phone, which are matched to four columns in our Customer table in our MySQLSample database.

C.Starting a PHP block, the mysql_query() function is executed to perform a query to select and pick up all records from our Customer table based on the customerID retrieved from the top part of this page. The returned query result is assigned to a local variable $result.

D.A while loop is used to pick up each row based on each column’s name. The PHP function mysql_fetch_array() returns a row from a recordset as an associative array and/or a numeric array. This function gets a row from the mysql_query() function and returns an array if it is success, or FALSE on failure or when there are no more rows.

E.The <tr></tr> tags form rows, the <td></td> tags form cells within rows, and \n starts a new line.The echo script and strip_tags() functions are used to display each column

in a normal table format. The strip_tags() function removes any HTML tags from the displayed columns. Note that <br>, <p>, and <h1> tags are allowed in all columns. The strip_tags() function cannot accept a variable passed as a reference, which is why the variables $cID, $addr, $email, and $phone are created and used here.

F.The mysql_close() function is called to close this database connection.

G.The ending tag of </table> indicates that the table is complete.

Compile and build the project by clicking on the Clean and Build Main Project button from the toolbar. A successful building result will be displayed in the Output window if everything is fine. Next, let’s run our PHP project to test its functionalities.

5.3 Exploring NetBeans IDE 6.8 297

html>

<body>Customer Name of <?php echo $_GET["user"]."<br/>";?> <?php

$con = mysql_connect("localhost", "php_user", "!php_user"); if (!$con) {

die('Could not connect: ' . mysql_error());

}

mysql_query("SET NAMES 'utf8'"); mysql_select_db("MySQLSample", $con);

$custId = mysql_query("SELECT id FROM LogIn WHERE custName='".mysql_real_escape_string($_GET["user"])."'"); if (mysql_num_rows($custId)<1) {

die("The person " .$_GET["user"]. " is not found. Please check the spelling and try again" );

}

$customerID = mysql_result($custId, 0); ?>

A<table border="black"> <tr>

B<th>CustomerID</th>

<th>Address</th>

<th>Email</th>

<th>Phone</th>

</tr>

<?php

C$result = mysql_query("SELECT * FROM Customer WHERE customerId=". $customerID);

Dwhile($row = mysql_fetch_array($result)) {

$cID = $row["customerId"]; $addr = $row["Address"]; $email = $row["Email"]; $phone = $row["Phone"];

Eecho "<tr><td>" . strip_tags($cID,'<br><p><h1>')."</td>"; echo "<td>". strip_tags($addr,'<br><p><h1>')."</td>";

echo "<td>". strip_tags($email,'<br><p><h1>')."</td>"; echo "<td>". strip_tags($phone)."</td></tr>\n";

}

Fmysql_close($con);?>

G</table>

</body>

</html>

Figure 5.143. The newly inserted codes to the customerDetails.php page.

5.3.7.11 Running and Testing the PHP Project

First, make sure that the Apache HTTP Server has been started and run on your computer. If not, go to the Start\All Programs\Apache HTTP Server 2.2\Control Apache Server\Start menu item to start this Web server. Then from the Projects window, right click on the index.php page and select the Run menu item from the popup menu to run the project.

In the opened page, enter White into the Customer Name field, and click on the Go button. The customerDetails.php page is called and the running result is shown in Figure 5.144.

Click on the Back button to return to the index.php page and replace White with Jerry in the Customer Name field, and click on the Go button again. The running result for the customer name Jerry is shown in Figure 5.145.

You can also try to enter other customer name, such as Tom, to this field in the index. php page. A running page that displays “cannot find the person” would be displayed since the customer name Tom is not existed in our LogIn table.

298 Chapter 5 Introduction to NetBeans IDE

Figure 5.144. The running result for the customer name of White.

Figure 5.145. The running result for the customer name of Jerry.

Our PHP project is successful.

A complete PHP project PHPCustomer can be found from the folder DBProjects\ Chapter 5 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1). You can download and run this application in your computer. However, before you can run this application in your computer, you need to have the following conditions met:

An Apache HTTP Web Server has been installed in your computer at the default location,

C:\Program Files\Apache Software Foundation\Apache 2.2.

A PHP engine has been installed in your computer at the default location, C:\Program Files\PHP.

The MySQL Server has been installed and run in your computer.

The MySQL sample database MySQLSample has been created and connected.

The Apache HTTP Web Server has been started and run in your computer.

Make sure that both Apache HTTP Web Server and PHP engine have been successfully tested and run in your computer.

Copy and save the PHP project PHPCustomer to the default location, C:\Program Files\Apache Software Foundation\Apache 2.2\htdocs\.

Next, let’s take care of creating and building a NetBeans Module project.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]