0% found this document useful (0 votes)
67 views8 pages

Lab Manual: The PHP Contact Form Script

The document provides examples of PHP code for: 1. Connecting to a MySQL database and checking for connection errors. 2. Creating a MySQL database using the CREATE DATABASE statement. 3. Creating a MySQL table using the CREATE TABLE statement, including specifying column names, data types, and other optional attributes.

Uploaded by

ghazi members
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views8 pages

Lab Manual: The PHP Contact Form Script

The document provides examples of PHP code for: 1. Connecting to a MySQL database and checking for connection errors. 2. Creating a MySQL database using the CREATE DATABASE statement. 3. Creating a MySQL table using the CREATE TABLE statement, including specifying column names, data types, and other optional attributes.

Uploaded by

ghazi members
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 8

PHP Mannual

Lab Manual

The PHP contact form script

<?php 
$action=$_REQUEST['action']; 
if ($action=="")    /* display the contact form */ 
    { 
    ?> 
    <form  action="" method="POST" enctype="multipart/form-data"> 
    <input type="hidden" name="action" value="submit"> 
    Your name:<br> 
    <input name="name" type="text" value="" size="30"/><br> 
    Your email:<br> 
    <input name="email" type="text" value="" size="30"/><br> 
    Your message:<br> 
    <textarea name="message" rows="7" cols="30"></textarea><br> 
    <input type="submit" value="Send email"/> 
    </form> 
    <?php 
    }  
else                /* send the submitted data */ 
    { 
    $name=$_REQUEST['name']; 
    $email=$_REQUEST['email']; 
    $message=$_REQUEST['message']; 
    if (($name=="")||($email=="")||($message=="")) 
        { 
        echo "All fields are required, please fill <a href=\"\">the form</a> again."; 
        } 
    else{         
        $from="From: $name<$email>\r\nReturn-path: $email"; 
        $subject="Message sent using your contact form"; 
        mail("[email protected]", $subject, $message, $from); 
        echo "Email sent!"; 
        } 
    }   
?> 
PHP Mannual

OutPut

PHP - Validate Name


The code below shows a simple way to check if the name field only contains letters and
whitespace. If the value of the name field is not valid, then store an error message:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
  $nameErr = "Only letters and white space allowed"; 
}

PHP - Validate E-mail


The easiest and safest way to check whether an email address is well-formed is to use PHP's
filter_var() function.
In the code below, if the e-mail address is not well-formed, then store an error message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format"; 
}
PHP Mannual

PHP - Validate URL


The code below shows a way to check if a URL address syntax is valid (this regular expression
also allows dashes in the URL). If the URL address syntax is not valid, then store an error
message:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/
%=~_|]/i",$website)) {
  $websiteErr = "Invalid URL"; 
}

PHP - Validate Name, E-mail, and URL


Example
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed"; 
    }
 }

  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
 }
PHP Mannual

  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/
%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 
    }
 }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
 }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
 }
}
?>
PHP Mannual

MySQL-DATABASE
Open a Connection to MySQL
Before we can access data in the MySQL database, we need to be able to connect
to the server:
Example (MySQLi)
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

echo "Connected successfully";
?>

Create a MySQL Database Using MySQL


The CREATE DATABASE statement is used to create a database in MySQL.
The following examples create a database named "myDB":

SQL CREATE DATABASE Syntax


CREATE DATABASE dbname;

SQL CREATE DATABASE Example


The following SQL statement creates a database called "my_db":
PHP Mannual

CREATE DATABASE my_db;

Example
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} // Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . $conn->error; }
$conn->close();
?>

SQL CREATE TABLE Statement


The CREATE TABLE statement is used to create a table in a database.
Tables are organized into rows and columns; and each table must have a name.

SQL CREATE TABLE Syntax


CREATE TABLE table_name
(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);
The column_name parameters specify the names of the columns of the table.
The data_type parameter specifies what type of data the column can hold (e.g.
varchar, integer, decimal, date, etc.).
PHP Mannual

The size parameter specifies the maximum length of the column of the table.

SQL CREATE TABLE Example


Now we want to create a table called "Persons" that contains five columns: PersonID, LastName,
FirstName, Address, and City.
We use the following CREATE TABLE statement:

Example
CREATE TABLE Persons
(
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
The PersonID column is of type int and will hold an integer.
The LastName, FirstName, Address, and City columns are of type varchar and will
hold characters, and the maximum length for these fields is 255 characters.
The empty "Persons" table will now look like this:

PersonID LastName FirstName Address

       
PHP Mannual

Notes on the table above:


The data type specifies what type of data the column can hold. For a complete reference of all
the available data types, go to our Data Types reference.
After the data type, you can specify other optional attributes for each column:
 NOT NULL - Each row must contain a value for that column, null values are not allowed
 DEFAULT value - Set a default value that is added when no other value is passed

 UNSIGNED - Used for number types, limits the stored data to positive numbers and zero

 AUTO INCREMENT - MySQL automatically increases the value of the field by 1 each
time a new record is added

 PRIMARY KEY - Used to uniquely identify the rows in a table. The column with
PRIMARY KEY setting is often an ID number, and is often used with
AUTO_INCREMENT

Each table should have a primary key column (in this case: the "id" column). Its value must be
unique for each record in the table.

You might also like