PHP How To’s

How do I migrate from MS SQL to ODBC in PHP?

See Migrating from MS SQL to ODBC in PHP

How do I make my site use the correct database depending on if it’s in Development, QA, or Production?

<?php
/** Find what TIER we're on and set host/password */
if (array_key_exists("TIER", $_SERVER)) {
    switch ($_SERVER['TIER']) {
        case "dev":
            $db_host = 'ldvdbamydv01.itap.purdue.edu';
            $db_name = 'DEV_DB_NAME_GOES_HERE';
            // Usually, db_name = db_username
            $db_username = $db_name;
            $db_password = 'DEV_DB_PASSWORD_GOES_HERE';
            $my_domain = 'dev.www.purdue.edu';
            break;
        case "qa":
            $db_host = 'ldvdbamydv01.itap.purdue.edu';
            $db_name = 'QA_DB_NAME_GOES_HERE';
            // Usually, db_name = db_username
            $db_username = $db_name;
            $db_password = 'QA_DB_PASSWORD_GOES_HERE';
            $my_domain = 'qa.www.purdue.edu';
            break;
        case "prod":
            $db_host = 'lppdbamys01.itap.purdue.edu';
            $db_name = 'PROD_DB_NAME_GOES_HERE';
            // Usually, db_name = db_username
            $db_username = $db_name;
            $db_password = 'PROD_DB_PASSWORD_GOES_HERE';
            $my_domain = 'www.purdue.edu';
            break;
        default:
            print "'TIER' set to unknown value \"".$_SERVER['TIER']."\"<br>\n$";
            $db_host = 'localhost';
            $db_password = '';
    }
}
else {
    print "'TIER' not set!<br>\n";
    $db_host = 'localhost';
    $db_password = '';
}

How to I make a database connection to MySQL in PHP?

You will first need to create directory called includes and then create a file named data.php. Put the following code in this file and save.

<?php
$hostname = "{Enter MySQL sever name here} ";
$dbname = "{Enter database name here} ";
$username = "{Enter database username here} ";
$password = "{Enter database password here} ";
?>

Now create another page outside the includes directory and put the following code in that file and save.

<html>
<head>
    <title>PHP - MySQL Connection</title>
</head>
<body>
    <?php include 'includes/data.php'; ?>
    <?php $dbconnect = mysql_connect($hostname , $username , $password)
        or DIE ("DATABASE FAILED TO RESPOND."); ?>
    <?php mysql_select_db($dbname, $dbconnect) or DIE ("Table Unavailable"); ?>
    <p><strong>PHP - MySQL Connection</strong></p>
    <TABLE bgcolor="#FFFFFF" width="100%" border="0"
        cellpadding="2" cellspacing="0" >
        <TR>
            <TH><FONT size="-1">First Name</FONT></TH>
            <TH><FONT size="-1">Last Name</FONT></TH>
        </TR>
        <?php
        $query = "SELECT lastname, firstname
                    FROM test
                ORDER BY lastname";
        $result = mysql_query($query);
        $number = mysql_num_rows($result);
        $i = 0;
        if ($number == 0) :
            print "<tr>";
            print "<td><i>No data?</i></td>";
            print "</tr>";
            elseif ($number > 0) :
                while ($i < $number) :
                    $lastname = chop(mysql_result($result, $i, "lastname"));
                    $firstname = chop(mysql_result($result, $i, "firstname"));
                    print "<tr>";
                    print "<td nowrap><font size=\"-1\">$firstname</font></td>";
                    print "<td nowrap><font size=\"-1\">$lastname</font></td>";
                    print "</tr>\n";
                    $i  ;
                endwhile;
            endif;
        endif;
        ?>
    </TABLE>
    <?php mysql_close($dbconnect); ?>
</body>
</html>

How to I create an Email Web Form in PHP?

<html>
<head><title>Feedback</title></head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<LINK href="http://dev.www.purdue.edu/itap" rel=index>
<LINK href="../itapstyle.css" rel="stylesheet" type="text/css">
<body bgcolor="#e0d5c5" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"><?php
    // Include our default top of page
    include '../includes/top.inc';
    <!-- Add Headers for HTML formatted email - 
         leave out the $headers variable for plain text emails. -->
    $headers = "MIME-Version: 1.0";
    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
    if (!$_POST) {
        ?>
        <!-- Form Section -->
        <!-- Email addresses should never be passed from the from section, 
             instead pass a variable that can be translated to an email address
             in the Post Section. -->
        <h1>Contact Us</h1>
            <form action="<?= $PHP_SELF ?>" method="post">
                <p>Your Name: <input type="text" name="name" /></p>
                <p>Your Email: <input type="text" name="email" /></p>
                <p>Comments: <textarea name="comments"></textarea></p>
                <p><input type="submit" value="Send Email"></p>
            </form>
        <?php
    }
    else {
        // Post Section
        // Define the recipient's email address(es).
        // The recipient's email address should always be defined in the POST section.
        $recipient = "sample@purdue.edu";
        
        // Define subject
        $subject = "Feedback";
        $callingurl = $_POST['$callingurl'];$name = $_POST['name'];
        $email = $_POST['email'];
        $comments = $_POST['comments'];
        
        // Compose message:
        $message = "Message from $name ($email)Comments: $comments";
        
        // Send the email format mail( mail to address, subject, message, headers)
        // Leave out $headers for plain text formatted email.
        // add from field to the headers
        // include name and email
        $headers .= "From: " . $_POST['name'];
        $headers .= "<" . $_POST['email'] . ">\r\n";
        
        // add reply-to field to the headers
        $headers .= "Reply-To: " . $_POST['email'] . "\r\n";
        mail($recipient, $subject, $message, $headers)
        ?><!-- Reply to the user -->
            <h1>Thank You </h1>
            <p>Your comments have been submitted.<br>
            Thank you for your input.</p>
        <?php
    }// insert our default bottom of page
    include '../includes/lower.inc';?>
</body>
</html>

Notice how the program does two things.

  • If not handling a POST request, display the feedback form.
  • Otherwise send the email and display a response to the user.

Why not put the email address in the Form Section?

Email addresses should never be passed from the Form Section. If recipient email addresses vary, pass a variable that can be translated to an email address in the Post Section. Spammers use robots to find email addresses in HTML code. Keeping email addresses out of the Form Section will make it harder for spammers to find your email address. Also, allowing an email address to be passed directly to the Post Section allows less scrupulous visitors to use your form to send email for unintended uses.

The POST Request

When you click on that submit button, what happens? The browser sends all the form fields to the server using a POST request. A POST simply means that all the submitted fields are sent in the body of the request. In a GET request, the submitted fields are appended to the URL e.g. feedback.php?name=Jason. The POST method is preferable here because the comments field might exceed the browser’s URL length limit if a GET request was used.

Using POST, the field names and values are sent to the server in the body of the request. When the PHP script handles the request, it puts these values into an associative array called $_POST, with the field names as the keys. The value of the name field, for example, could then be accessed using $_POST['name'].

Sending the Email

First we create a $message variable containing the body of the message. Then we call the mail() function with the appropriate parameters to send the actual email.

More Information

For more information, read about php’s mail() function.