Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

Creating an Include File for Common Functions

Previous chapters used an included file of common functions to make your scripts more concise and to help manage information that might change over time, such as a database username and password. The same thing is true in this chapter. Listing 21.1 contains the code shared by the scripts in this chapter.

Listing 21.1 Common Functions in an Included File

1: <?php
3: function doDB() { 
4:   global $mysqli;
6:   //connect to server and select database; you may need it
7:   $mysqli = mysqli_connect("localhost", "joeuser", 
8:     "somepass", "testDB");
10:   //if connection fails, stop script execution
11:   if (mysqli_connect_errno()) { 
12:     printf("Connect failed: %s\ n", mysqli_connect_error());
13:     exit();
14:   } 
15: } 
16: ?>

Lines 3–15 set up the database connection function, doDB. If the connection cannot be made, the script will exit when this function is called; otherwise, it will make the value of $mysqli available to other parts of your script.

Save this file as ch21_include.php and place it on your web server. The other code listings in this chapter will include this file within the first few lines of the script.

  • + Share This
  • 🔖 Save To Your Account