Chapter 7. Migrating to a Host and Backing Up Your Web Site Database

You might think that the database-driven web site created in Chapter 6 is finished and ready for migrating to the host. However, in a real-world situation the client has had time to think about the site and will ask for some last-minute changes. A web designer/developer cannot anticipate everything that a client might expect to achieve with a database driven web site. Also, last-minute changes might be necessary when new laws require the database to exclude certain information or to include additional information.

This chapter contains the following sections:

· Making last-minute changes

· Include members’ titles in the paginated display

· Allow members to update their own details

· Provide for safe e-mailing

· Create a secure feedback form

· Migrating the database to a remote host

· Backing up your database

Making Last-Minute Changes

In our example, we assume that the client asked for some last-minute changes as follows:

· In the database in Chapter 6, the membership secretary noticed that, although the title column was present in the administrator’s individual record display, the title was absent from the paginated table display. We will correct this omission.

· To reduce the workload of the membership secretary, he asked us to allow registered members to update their own details. For instance, telephone numbers and e-mail addresses can change. If a woman is recorded as “Miss,” her title and last name might need changing when she gets married. We will therefore allow members to update their titles, last names, addresses, telephone numbers and e-mail addresses.

· The client asked for a live but secure e-mail address to be displayed on the web site. This will allow users to contact the organization and the webmaster.

· The client asked for an inquiry form so that users can ask for more information about the organization before registering as members.

We will begin by creating a new database and table.

Create a New Database

The last-minute changes were requested for the database that we created in the last chapter, but to avoid confusion we will implement the changes in a new version of the database called lmnmigrate, short for Last Minute and Migrate. (The first letter of the name is a lowercase L, not an uppercase I.) In the htdocs folder within the xampp folder, create a new folder called lmnmigrate.

Download the files for Chapter 7 from the book’s page at www.apress.com, and load them into the new lmnmigrate folder:

1. Use a browser to access phpMyAdmin, click the Databases tab, and create a new database called lmnmigrate.

2. Scroll down and find the newly created database, and select the box next to it.

3. Click Check Privileges and then click Add User. Add a new user and password as follows:

1. User name: trevithick

2. Host: select Local,

3. Password: locomotive

4. Scroll down to the item named Global Privileges, and click Check All.

Scroll to the bottom, and click Add User (or Go in some versions)to save the database user’s details.

Details of the Downloaded File for Connecting to the Database

The file mysqli_connect.php is already created for you in the download files for this chapter.

I already compiled the table for you and exported it into a file called users.sql. You will find this among the downloaded files you just installed in the folder lmnmigrate.

In phpMyAdmin, open the database lmnmigrate.

In the home page of phpMyAdmin, click the database lmnmigrate. Then use the import tab to import the file users.sql you downloaded and installed in htdocs.

To locate the users.sql file in the Import interface, click the Browse button shown circled in Figure 7-1.

Figure 7-1. The Import interface in phpMyAdmin

The Browse button will allow you to navigate to the downloaded file users.sql. Open the file and then click the Go button. The file will be imported. If you now open the users table in phpMyAdmin, you will be able to view the table and its data by clicking, in turn, the Structure tab and the Browse tab.

Note The PHP files in this chapter make no attempt to accommodate styling for Internet Explorer 8; for this a ­conditional style sheet would be required. The files work in all the most popular browsers, but make sure your copy of Mozilla FireFox is the latest version; otherwise, you will not be able to access the administration pages with FireFox. In fact, FireFox is rather picky, and unlike the other browsers, it will detect the tiniest error in the PHP code and throw the user back to the login page.

Displaying the Members’ Titles in the Paginated Table

In Chapter 6, the members’ titles were included in some screen displays but not in the paginated table display. The membership secretary has requested that members’ titles also be displayed in the paginated table display.

This is easily achieved by adding one extra column in the file php view-members.php and saving the file as admin_view_users_title.php. The Title column is added in front of the Last name column. The result is shown in Figure 7-2.

Figure 7-2. The members’ titles are now visible in the paginated table

The records are displayed in descending order of the registration date so that the administrator can quickly view the latest registrations. This helps him to update the Paid field when PayPal notifies him that a registrant has paid the membership fee.

To achieve the change, the file view-members.php has been amended and renamed as admin_view_users_title.php. Listing 7-1 gives a snippet of the code.

The file named admin_view_users.php was modified by inserting the items shown in bold type in the following snippet. The file was saved as admin_view_users_title.php.

Partial Listing 7-1. Adding the Title to the Members’ Paginated Table View (admin_view_users_title.php)

For you to be able to access the amended file, the menu button link in the file header_admin.php has been changed from admin_view_users.php to admin_view_users_title.php.

Caution Remember to log in as administrator to view the table of members.

The login details are e-mail:jsmith@outcook.com and password: dogsbody.

The membership secretary has asked for a change so that members can update their own records to a limited extent. This is a common feature in database-driven web sites. For instance, in PayPal, members can update their profile (their own account details). A provision was already made for members to change their password; therefore, this feature will not be included again in the members’ update interface that follows.

Allow Members to Update Their Own Records

When members have logged in, they can be permitted to update their own accounts. They have no access to any other member’s account; this is controlled by means of a session and a LIMIT that allows only one record to be displayed by the member. The member’s amendments are validated and sanitized. If members want to change a password, they must use the New Password button on the header menu. The items that can be amended are limited for security reasons, and they are as follows: title, first name, last name, e-mail address, postal address, and telephone number.

Tip The membership secretary might ask the member to send an e-mail notifying the secretary that an amendment has been made. If so, this must be stipulated clearly on the edit page. The member should be asked to use the Contact Us button on the menu. This will open the feedback form described later in this chapter.

The first step consists of changing the header for the “members’ only” page so that registered members can view and amend their records. The header shown in Figure 7-3 is modified to allow this.

Figure 7-3. The new “Your Account” button in the header for the members’ page

The code for the revised header is shown in Listing 7-2. This is in the includes folder in the download code.

Listing 7-2. Creating the New Header for the Members’ Page (header_members_account.php)

When the Your Account button is clicked, a new page is displayed as shown in Figure 7-4.

Figure 7-4. This screen shot shows the data that a registered member is allowed to update

The importance of logging out is stressed on the members’ page and on the update screens. When fields are edited and the Edit button is clicked, the confirmation message appears as shown in Figure 7-4a.

Figure 7-4a. The update is confirmed

The code for the screens shown in Figures 7-4 and 7-4a is given in Listing 7-3 as follows:

Listing 7-3. Creating an Interface for Members to Edit Their Accounts (edit_your_account.php)

The member must log in to access this page; therefore, it begins with session statements.

We saw this code before in the safer registration page in Chapter 6. It prevents HTML tags and JavaScript from being inserted into the database table. This sanitizing format is applied many times in this listing. This test applies only if the user has altered the title in an unacceptable manner, or the user has cleared the field and then forgotten to enter a new title.

//Set the email variable to FALSE #3$e = FALSE;// Check that an email address has been enteredif (empty($_POST['email'])) {$errors[] = 'You forgot to enter your email address.';}//remove spaces from beginning and end of the email address and validate itif (filter_var((trim($_POST['email'])), FILTER_VALIDATE_EMAIL)) {//A valid email address is then registered$e = mysqli_real_escape_string($dbcon, (trim($_POST['email'])));}else{$errors[] = 'Your email is not in the correct format.';}

This method of validating an email address was demonstrated in Chapter 6 and is repeated here.

Caution Carefully check the array items shown bold in the block of code beginning with reference line #7 in the ­preceding code. They must be in numerical order. In this table display, they are numbered from 0 to 9 because there are 10 fields. When inserting an extra field or deleting a field, it is only too easy to forget to renumber the array items in square brackets. This would result in either the same data appearing in two adjacent fields or inappropriate data ­appearing in some fields.

That concludes the tutorial on the database lmnmigrate. Some useful additions to a database-driven web site (or any web site) will now be described.

To enable users to contact the web site’s owner, the client has asked for a live e-mail address to be included in one of the web site pages. This could be a magnet for spammers. The webmaster should encode the live e-mail address so that spam spiders cannot harvest it.

Safe E-mailing

This useful item is for information only. A live but secure e-mail link is not included in any page of this chapter’s example web site. An influx of spam will cause distress to the site owner, and this breach of privacy can sow seeds of doubt about the security of the rest of the web site, especially the security of the database. This also damages the reputation of the web designer. This section describes a method for preventing spam.

Escrambler is a free, anti-spam device. It was originally produced as a plain, clickable e-mail link, and it was later enhanced by the addition of an image of the e-mail address by InnerPeace.org. Their web page is at http://innerpeace.org/escrambler.shtml. The web site will quickly generate the code for you, or you can adapt the JavaScript snippet that follows.

The JavaScript code allows for two conditions:

· The full e-mail address appears on the screen in the form of an image that is clickable but invisible to spam spiders.

· If no image is available, a link having the words E-mail Me appears on the web page.

Clicking either the image or the words E-mail Me causes the user’s default e-mail program to open with the e-mail address already filled in. Users might need to be told that the e-mail might go into their Outbox and, therefore, the user must send it by clicking the Send/Receive button.

I usually create the image of the e-mail address in MS Paint, and then I import it into my image-manipulation program, crop it, and export it as a transparent .gif or .png file.

Insert the following JavaScript snippet into the <body> section where you want the e-mail address to appear. The JavaScript code also places a picture of the e-mail address on the page so that the user can click it or make note of it for future use. For your own e-mail scrambler, just change the items in bold type in the following example, which hides the address fredbloggs@aol.com:

The JavaScript breaks down the traditional email address into little bits and then reassembles it. Spam spiders have great difficulty reading JavaScript and images; even if they could read JavaScript, the email address is so fragmented that spam spiders would not make sense of it.

Caution The variable f is followed by two single quotes, not a double quote. The line g=‘<img src=\”’ ends in a double quote followed by a single quote.

A Minor Problem

Your client might decide not to put her e-mail address on the web site. She might prefer to use a feedback form because it is a more secure approach. However, there is nothing to prevent someone from ignoring the form and contacting her directly by guessing her e-mail address. This very rarely happens, and the sender is not necessarily a mass spammer. This is known as link exchange spam, so tell your client not to be alarmed. I have personally received only a handful of these e-mails in a decade. This is a minor problem and can be ignored.

So how does the sender know your client’s e-mail address? He knows because he found her web site. Why does he try to contact her? He wants to establish a reciprocal link from her web site to his web site. Because the secure feedback form (described in the next section) is designed to prevent the sender from entering URLs, he must use a normal e-mail; therefore, he makes an intelligent guess.

He tries info@clientswebsite.co.uk or sales@clientswebsite.co.uk, and so on. Link exchange spam can be the result of viewing the web site’s e-mail address posted in Whois, a directory of web-site owners. If your client has a catchall e-mail address, the person could also type something like postmaster@clientswebsite.co.uk and it might reach your client. His e-mail would then include his URL. He normally won’t include a dodgy URL because he could be traced through his e-mail. By requesting and establishing a reciprocal link, he is hoping to improve his search engine ranking by having as many external links as possible that link to his site. Your client should not click a link in the e-mail to look at the person’s web site(s); if she did take the risk, she would usually find that his content is in no way related to her own web site, so she should not agree to a reciprocal link. Also, she will most likely find that his link page has between 50 and 150 links on it. If she agrees to a reciprocal link, search engines will assume she is using a link farm and, as a consequence, they might penalize her web site.

If your client is receiving this type of e-mail, she can avoid it by using a different e-mail address in the feedback form handler. She could use her home address, clientsemailaddress@herisp.co.uk. No one will be able to guess her home e-mail address by looking at her web site, but the downside is that her business replies won’t be distinguished from her personal e-mails.

A Secure Feedback Form

A Contact Us form is not strictly related to databases; however, it is an interactive element and provides an excellent application of PHP code.

E-mails and feedback forms are the most popular contact methods for allowing users to communicate easily with web-site owners. Unfortunately, both contact methods can be abused. E-mail addresses are harvested and sold to spammers. Both actions cause distress and an influx of spam to the site owner, and they don’t enhance the reputation of the web designer. Hackers can hijack a form and use it to send frequent nonsense messages to the web-site owner. These usually contain malware that can be activated via a link in the text area. This section describes some options to prevent these risks.

When designing feedback forms, we need to consider the following three points:

· Because layout tables are deprecated, CSS must be used to align the input fields neatly.

· Blind and severely visually-impaired users can use screen readers to read and reply to forms. Accessibility rules must be observed

· Filters must be built into the form handler to prevent the form from being hijacked for nefarious purposes.

Bogus Replies

Concerning the third point, when I first began to design web sites, I added feedback forms to many of my clients’ web sites and all of them were plagued by people using robots to send bogus replies to the site owners. The replies contained gobbledygook and dodgy URLs. These e-mails were often sent once or twice a week. The site owners were naturally disappointed and puzzled because they thought they had received an order. Fortunately, they did not click a link on these bogus replies, but they contacted me immediately for a solution. What do bogus replies look like?

A typical bogus reply is shown next. For your security, I altered the URLs and the e-mail address. The replies contain gobbledygook as well as live URL links that lead to dodgy web sites. A web-site owner unfamiliar with the weird behavior of hackers might be tempted to click a link, which could lead to all sorts of mayhem. Note the large number of live URLs:

The robot is designed to send URLs; therefore, the way to kill the replies—and also cause the robot to have hysterics and crash—is to put a URL filter in the form handler.

What Does a Genuine Reply Look Like?

The following is a genuine e-mail received from a secure form and its handler:

This message was sent from:

http://www.my-website.co.uk/feedbackform.html

------------------------------------------------------------

Name of sender: Andrew Eastman

Email of sender: aeastman@myisp.co.uk

Telephone No: 01111 222333

XP?: No

Vista?: No

Windows7?: No

Windows 8: Yes

Laptop?: Yes

Desktop?; No

------------------------- MESSAGE ----------------------------

How can I change back to Windows 7?

-------------------------------------------------------------------

The Feedback Form

Figure 7-5 shows a typical feedback form.

Figure 7-5. The feedback form. In this screenshot, the header and footer are cropped away to save space

The code for the feedback page concentrates on preventing URLs from being entered because these are the main concern with forms filled in by robots.

The formatting of a form can be rather time consuming, and you will need a conditional style sheet for Internet Explorer 8. The Listing 7-4a that follows contains an additional link to a style sheet for the feedback form and also a link to a conditional style sheet for Internet Explorer 8. Conditional style sheets must always be listed after the other style sheets. The code [if lt IE 9] means “if less than Internet Explorer 9.” Note the space between IE and 9.

Bogus feedback from the feedback form can be stopped by means of a PHP handler file. If a URL has been entered into any text field, the form handler causes an error message to appear when the submit button is clicked. This stops bogus replies completely. Hackers do not hijack a form to send advertisements for Viagra; they are hoping the site owner will click the URL link and fire up the sender’s dodgy web site(s). The web sites usually contain malware such as a Trojan horse that would take control of the site owner’s computer. The PHP code for the handler is shown inListing 7-4b.

The dummy email addresses and URLs will need to be replaced by real-world addresses and URLs. To test the feedback form, the webmaster will comment-out the client’s email address and remove the comment symbols from his own email address. When he is satisfied that the form works, he will reverse this process so that the client receives the feedback. In the last five lines, five files are assigned to short form variables. The last four lines refer to pages containing error messages.

The long variables are assigned to short variables to make the form easier to read and debug.

//check that no URLs have been inserted in the username text field #3if (strpos ($username, '://')||strpos($username, 'www') !==false){header( "Location: $errorsuggesturl" );exit ; }

The PHP function strpos() checks whether the URL symbols // and www are present within the string input by the user. The function actually finds the position of the first occurrence of a string within a string. If URL symbols are present, a page containing an error message is displayed. The function is used to check most of the fields in the form.

This block of code constructs the e-mail using the variables provided in the feedback form by the user. Note the full stops after each item; these are very important. The code \n inserts a line break (or Enter) between each item. The last two lines send the e-mail using the PHP functionmail().

The Style Sheets for the Feedback Form

Two style sheets are provided, one is a conditional to ensure that the fields format properly with Internet Explorer 8.

Listing 7-4c. Creating the Style Sheet for the Feedback Form (feedback_form.css)

The thank you page confirms that the e-mail was sent successfully. It would be a pity to lose the visitor, so add a Return to Home Page button. The thank you page is shown in Figure 7-6, and the code is Listing 7-5a. The page has a Go Back button with the text Return to Home Page, but you can replace this button with your main navigation menu. The styling for the button is incorporated in the style sheet feedback.css.

Figure 7-6. The “thank you” page message

Listing 7-5a. Creating the “Thank You” Page (thankyou.html)

<!doctype html><html lang=en><head><title>Thank you for your enquiry</title><meta charset=utf-8><link rel="stylesheet" type="text/css" href="feedback.css"></head><body><p> </p><div id="back-button"><a title="Return to the Home page" href="index.php">Return to Home Page</a></div><div><br><h2>Thank you for your enquiry</h2><h3>We will email an answer to you shortly.</h3></div></body></html>

If the e-mail message was not sent successfully, an explanatory error message will appear.

Why use error pages instead of echoing a piece of text to the screen? I found that many of my clients prefer the distinct message, and the help that a page provides, rather than the usual small error messages in red that can be overlooked or that are so often too brief. If you prefer to echo messages to the page, create an $error() array to hold the messages as we did in the registration page.

Listing 7-5d provides the code for the error message for empty fields.

Listing 7-5d. Creating the Page for Empty Field Errors (error.html)

<!doctype html><html lang=en><head><title>Error message. Missing essentials</title><meta charset=utf-8><link rel="stylesheet" type="text/css" href="error-style.css"></head><body><p> </p><p> </p><p>One or more of the essential items in the form has not been filled in.</p><p>Essential items have a red asterisk like this <span>*</span></p><p>Please return to the form<br> and then fill in the missing items</p><form method="post" action=" "><input type="button" value="Return to form" onclick="history.go(-1)"></form></body></html>

<!doctype html><html lang=en><head><title>Error message. Do not enter URLs</title><meta charset=utf-8><link rel="stylesheet" type="text/css" href="error-style.css"></head><body>Sorry, but website addresses are not allowed<br><br><p>Please click the Back button on your internet browser<br>and then remove any website addresses from the form.</p></body></html>

Note You will need to add one more button to the main menu (includes/nav.php). Label the button “Contact Us”, and link it to the file feedback_form.php.

Migrating the Database and Tables to a Remote Host

Having created a database and table(s) using XAMPP, how can we transfer them to a hosting company? The process for migrating a database from XAMPP (or any other WAMP) to a remote host worries beginners more than any other aspect of database development. This is because MySQL manuals and Internet tutorials rarely provide proper explanations for the procedure; in fact, the many manuals I possess (or have borrowed) either omit or hardly mention this important topic.

For this tutorial, I chose to use the admintable database from Chapter 4 simply because it is shorter than the databases in Chapters 5 and 6 and will take up less space in this chapter.

Caution You will need to determine which operating system is used in your chosen hosting package. Linux and Windows require a slightly different migration procedure.

A Puzzling Error Message

I experienced an occasional problem when trying to transfer a database to another computer. I use phpMyAdmin to create a new empty database in the destination computer, and then I try to import the SQL dump for the table(s). An error message sometimes appears saying that the table already exists. This is weird because there is definitely not a table in that empty database. The solution is to access the XAMPP folder on the first computer and drill down to the MySQL folder and then the Data folder. I then save a copy of the somefilename.frm file on a pen drive (memory stick). I copy that file into the same Data folder on the destination computer and the problem is solved. Being rather paranoid about backups, I regularly save copies of the *.frm files as well as the SQL dumps.

Creating and Exporting the SQL File

The first stage for migrating a database consists of creating an SQL file (the dump file). You will be able to export two types of dumps: (i) for the table(s) only or (ii) f or the database and table(s). We will be using the table(s) only file because dumps of whole databases can be fraught with snags when you import them. They can also be huge and therefore unacceptable to many hosts. Use phpMyAdmin to export a file. The exported SQL file for the table(s) is a simple text file of the type filename.sql, although other file types can be chosen for the exported file. The content of the file and the process will be explained next.

To Create a Dump File of a Table or Tables

Open a browser, and in the address bar, type http://localhost/phpmyadmin/.

In the left panel of phpMyAdmin, click the database containing the admintable tables to be exported. Then click the Export tab as shown in Figure 7-7.

Figure 7-7. The screen for dumping the database table

When the Export tab is selected, the next screen appears as shown in Figure 7-8.

Figure 7-8. Export the SQL file

Select the Quick option, and ensure that the format is SQL. Then click the Go button shown circled. Depending on your browser and settings, you will be asked whether to open or save the file as shown in Figure 7-9.

Figure 7-9. Choose to save the SQL file

Choose to save the file, and click OK. You will be taken to a screen where you can decide where to save it. Save the file in a folder where you can access it for uploading it to the host later with your FTP client. The default is the Downloads folder.

What Does an SQL Dump Look Like?

We will now examine the admintable.sql file in WordPad (or better still, use Notepad++).

You will see many commented-out lines. SQL supports three comment styles as follows:

· A line beginning with a hash symbol like this: #some text

· A line beginning with a double dash followed by a space like this: -- some text

· A block of text between tags like this:

/*some textsome textsome text*/

The dump for the table in the admintable database (from Chapter 4) is shown next. Note the commented-out code. The remaining code, shown in bold type, will re-create the table in the destination server (the host or another computer with XAMPP installed).

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

The next steps are to do the following:

· Examine the destination server (the host), and prepare it to receive the SQL file and the contents of the htdocs folder.

· Upload the SQL file and web-site files to the host.

· Import the SQL file using phpMyAdmin in the host.

Investigate the Remote Host’s Server

We will assume that you have reserved a space for the web site and registered the domain name with your remote host. Also, you should have determined whether your chosen hosting package uses Linux or Windows.

A remote host must have PHP and MySQL installed. If you are not sure whether PHP and MySQL are installed at the host, type the following in a text editor and save it as phpinfo.php:

<?phpphpinfo();?>

Use your FTP client to upload the file to the host and open it in a browser. You will see a table like the one in Figure 7-10. Scroll down the table, and you should see details of the MySQL and MySQLi installation on the host’s server.

Figure 7-10. The result of opening phpinfo.php in a server

Caution Some basic hosting packages do not accept databases. In this case, you will have to upgrade to a more expensive package. Check the product range on your intended host before proceeding further.

Using the GUIs on a Remote Host’s Server

Access the control panel of the host, and ensure that it allows you to upload a database. Scroll down the control panel until you see the section shown in Figure 7-11.

Figure 7-11. The database section of the control panel

If a database section is not shown in the control panel, it means that the hosting packet needs to be upgraded. Assuming that the host will accept databases, follow these steps:

· Click the phpMyAdmin icon, and create an empty database. In this example, we will pretend to create the admintable database.

When creating the admintable database, the resulting database will either have the name admintable or the host will add a prefix to the database name. Most hosts add a prefix, and it is nearly always the web-site owner’s username for accessing the control panel. Let’s assume that the owner’s username is mywebsite; the host will create the database name as mywebsite_admintable. In this example, we will assume that the database name has the prefix myusername.

· Now you must immediately protect the newly created database by giving it a user and a password. Do this by using phpMyAdmin as described in Chapter 1. (Some hosts will automatically provide the user name—if that’s the case, use that one.)

Create a user with the following details:

User: webmaster (or a name provided by the host)

Password: coffeepot

Host: localhost

The password in a real-world database must be much more complex than coffeepot. Make a careful note of the database name, password, and user.

Connecting to the Database on the Remote Host

Now that we know the name of the empty database (in this example, it is myusername_admintable), we can amend the connection file to suit the remote host. Do not create this in XAMPP’s htdocs folder on your computer. If you do, you will no longer be able to run the admintable databaseon your computer’s server. Use a text editor such as notepad++ to create the file and store the new mysqli_connect.php file anywhere except in the htdocs folder. The amended file is not included in the downloadable files because it would be unique for your database. The amendment might be as shown in bold type in the next snippet of code.

The Snippet of Code for Connecting to the New Database (msqli_connect.inc.php).

<?php// Create a connection to the admintable database and set the encoding// The user name might be provided by the host. If not, use the name from your XAMPP versionDEFINE ('DB_USER', 'webmaster');DEFINE ('DB_PASSWORD', 'coffeepot');DEFINE ('DB_HOST', 'localhost');DEFINE ('DB_NAME', 'myusername_admintable');// Make the connection$dbcon = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );// Set the encodingmysqli_set_charset($dbcon, 'utf8');

You now have all the items necessary for migrating the database-driven web site to the remote host as follows:

· An account and a domain name registered with the remote host.

· A newly created empty database located on the host’s server.

· The SQL dump files for the tables.

· The folder containing the includes, and the folder containing the images.

· The modified mysqli_connect.php file.

The main PHP and HTML files need an amendment before they can be uploaded, and this amendment is described in the next section.

Securely Upload the mysqli_connect.php File

For maximum security, the database connection file should be located outside the root folder. The file is then not directly accessible via the web site. We will also give it a name that would confuse a hacker who is searching for the file. Figure 7-12 shows an FTP window for viewing the folder structure on a remote host.

In Figure 7-12, the database connection file (circled) has been renamed as greenh.php and uploaded outside the public_html root folder (circled).

Having uploaded the connection file outside the root folder on the host, none of your interactive pages will be able to find it. To solve this, use your code editor to open every file that contains a mysqli_connect.php link and run a Find-and-Replace-All to amend its location as follows.

Find mysqli_connect.php and replace it with ../greenh.php. The symbols ../ tell the pages that the file is located one level above the current folder. For connecting to the database on your own computer/server, you have always used require ('mysqli_connect.php');

Now that the connection file is safely hidden from hackers and the interactive pages have been modified to match, you can upload the HTML and PHP pages to the remote host.

Uploading the Interactive Pages to the Host

The final steps are as follows:

· Most hosts will be using Linux. In this case, there will not be an htdocs folder in the public_html folder. Therefore, you need to use your FTP client to upload the HTML and PHP pages from your admintable’s htdocs folder into the public_html folder in the host’s server. Because you already uploaded an amended and renamed mysqli_connect.php file, take great care not to upload the unmodified version into the public_html folder.

· Use your FTP client to upload the SQL files for the tables into the public_html folder.

· Log in to the control panel at the host, and open phpMyAdmin.

· In the left panel, click the name of the newly created empty database, and then click the Import tab.

· You will be asked to name the SQL file to be imported. Browse to the public_html folder, and find each uploaded SQL file. Open them one at a time, and then click Go.

· At some earlier date, you might have uploaded a file named index.html. Your new index.php file must replace the html file; otherwise, index.html will load instead of your index.php file. Rename the index.html file at the host as old-index.html, or delete it.

Note Beginners are often puzzled by the lack of an htdocs folder on the host server because MySQL and Apache normally look for files in the htdocs folder. To explain the mystery, if the host is using Linux, then the host will have configured Apache and MySQL so that it looks in thepublic_html folder.

View your uploaded interactive web site online by typing your web site’s URL into the address field of a browser. You should see your home page, and from there you can test the database features. Be aware that you might have to wait a little while because some hosts might take time to update their server.

As with any computer work, backups are an essential precaution against hardware or software failure. Also, you might want to roll back to an earlier version when experimenting with files.

Back Up Your Database

While you are learning to create and use databases, four steps are essential:

1. Continue writing in your notebook.

2. Be sure to update your flow chart.

3. Use the Export tab in phpMyAdmin to back up your tables.

4. Back up your htdocs folder.

Recording important steps and details such as usernames and password has saved me a lot of grief. During my learning period, when I created many experimental databases and variations of those databases, I could not possibly remember the details of each one. Also, I recorded details of the stage that I had reached and what I intended to do next. This was especially important if I had to stop for two or three days to update some of my clients web sites. Clients never seem to request updates singly; they come in bunches, with four or five clients clamoring for updates at the same time.

I also recorded useful web-site URLs. If I came across a helpful tip in a manual, I made a note of the page number. This saved me from having to trawl though the manual to find the item again. I recorded the URLs, usernames, and password for the many forums that I contacted for help. A ring-back notebook is ideal because you can insert dividers to help you find where you wrote that vital bit of information.

For backups, I recommend using phpMyAdmin to export SQL dumps for the tables from each database. Then copy them to a CD or USB pen drive so that you can create a copy in another computer.

Make a copy of the htdocs folder on a CD or pen drive so that it can be copied to another computer. Having suffered the occasional hard disk or OS failure, I also make a complete copy of each database-driven web site on one or two other computers. The other computers each have XAMPP and an FTP program installed. Extra work is entailed in keeping each web site up to date, but if a computer dies, I can continue working on another computer. Peace of mind is a wonderful thing.

Summary

In this chapter, we added some last-minute improvements suggested by the client and the membership secretary. These included adding a title column to the paginated table display, allowing registered members to update their own details, and adding a live e-mail address to be displayed on the web site. The client also asked for an inquiry form for the web site. All these additions to the web site were described and listed. The chapter then gave a full description of the procedures for migrating a database to a host and backing up database tables.

In the next chapter, we will learn how to create a product catalog for a real estate agent.