Sunday, August 11, 2013

PHP File Uploader

Let's see how to create a simple File Uploader into your php form or your web page.
As you use input types such as text, radio, password, etc..., there is a input type called "file".
And there is a small text should be included to ur html form as an attribute and value.
This is the code.

<form enctype="multipart/form-data">
      <input type="file" name="myuploader" id="myuploader1"><br/>
      <input type="submit" name="submit" value="Submit">
</form>

This is how it looks like...



You must set your form encrypt type as "multipart/form-data". Attribute name is "enctype".

To upload file, the action to be performed in form, you need to code it in another file. Assume its name is "uploadmyfile.php". Then your form with action and data parse method should be like this.

<form enctype="multipart/form-data" action="uploadmyfile.php" method="post">
      <input type="file" name="myuploader" id="myuploader1"><br/>
      <input type="submit" name="submit" value="Submit">
</form>

You must set your form method as "post". The file uploaders will not work on "get" method.
Now your "uploadmyfile.php" file code should be like this.

if ($_FILES["myuploader"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["myuploader"]["error"] ;
    }
  else
    {
   
    if (file_exists("upload/" . $_FILES["myuploader"]["name"]))
      {
      echo $_FILES["myuploader"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["myuploader"]["tmp_name"],
      "upload/" . $_FILES["myuploader"]["name"]);
      echo "Your File has been Stored in: " . "upload/" . $_FILES["myuploader"]["name"];
      }
    }
  }

By using this code, you can upload your files into folder called "upload" where your "uploadmyfile.php" file exists.

Tuesday, August 6, 2013

Displaying data using dynamic table.


Here I'm going to access data in the database and trying to display those data on the browser using a dynamic table. For that task I'll use simple interface to perform certain search operations. I apply these scenarios to create admin part of my project. Here is the snapshot of that sample interface.


Here we can perform date wise and type wise search. For that I'll publish sample php code with html5 design here..!


<html>
      <head>
                         //put certain external CSS link here to apply styles to  your interface as above.
       </head>

<body>


 <form id="membSearch" action="" method="post">


                <table width="800" height="140" border="0" align="center">
                 
                    <tr>
                        <td align="center">  <b>Search by Register Date    : </b> </td>
                    </tr>
                    <tr>
                        <td> <?php echo "<br>"; ?> </td>
                    </tr>
                    <tr>
                        <td width="120" align="center">Date:   <input type="date" name="regDate"
   id='regDate' class='datepicker' readonly/></td>

                        <td width="146">
                            <input type="submit" name="dateSearch" value="Search" onclick=""/>                      
                        </td>
                    </tr>
                    <tr>
                        <td> <?php echo "<br>"; ?> </td>
                    </tr>

                    <tr>
                        <td align="center"> <b>Search by Type    : </b> </td>
                    </tr>


                    <tr>
                       <td align="center">
                                    <select name="comboVolunType" id="comboVolunType">
                                        <option>Field Work</option>
                                        <option>Veterinary Work</option>
                                    </select>
                        </td>
                        <td><input type="submit"value="search" name="volType"/></td>
                    </tr>

               

<?php

function checkEmptyResult($resultTable) {
    $num_of_rows = mysql_num_rows($resultTable);
    if ($num_of_rows == NULL) {
        echo '<script type="text/javascript">alert("No results found");</script>';
        echo '<script type="text/javascript">history.go(-1);</script>';
    }
}

if (isset($_POST['dateSearch'])) {
    include ('../../controllers/db.php');

    $regDate = $_POST['regDate'];
   

    $queryTable = "SELECT * FROM eop_volunteers WHERE regDate>= '$regDate' and status =1";
    $resultTable = mysql_query($queryTable);
    checkEmptyResult($resultTable);


    echo"<table border = '1' cellpadding = '3' cellspacing = '2' width = '600' align = 'center'>

            <tr>
      <th>Email</th>
      <th>First Name</th>
      <th>Surname</th>
      <th>DOB</th>
   
      <th>Address</th>
      <th>Phone</th>
      <th>Gender</th>
      <th>Reg Date</th>
   
      <th>Country</th>
      <th>Skills</th>
         
      </tr>";


    while ($row = mysql_fetch_array($resultTable)) {
        echo "</td><td>";
        echo $row['email'];
        echo "</td><td>";
        echo $row['fname'];
        echo "</td><td>";
        echo $row['lname'];
        echo "</td><td>";
        echo $row['date'];
        echo "</td><td>";
        echo $row['address'];
        echo "</td><td>";
        echo $row['phone'];
        echo "</td><td>";
       
        $gen = $row['gender'];
                    if($gen == 1){
                        echo "Male";
                    }else {
                        echo "Female";
                    }
       
       
        //echo $row['gender'];
        echo "</td><td>";
        echo $row['regDate'];
        echo "</td><td>";
        echo $row['country'];
        echo "</td><td>";
        echo $row['skills'];
        echo "</td></tr>";
    }
} else if (isset($_POST['volType'])) {
    include ('../../controllers/db.php');

    $volWork = $_POST['comboVolunType'];
   

    $queryTable = "SELECT * FROM eop_volunteers WHERE volunType= '$volWork' and status=1";
    $resultTable = mysql_query($queryTable);
    checkEmptyResult($resultTable);


    echo"<table border = '1' cellpadding = '3' cellspacing = '2' width = '1000' align = 'center'>

            <tr>
      <th>Email</th>
      <th>First Name</th>
      <th>Surname</th>
      <th>DOB</th>
      <th>Type</th>
   
      <th>Address</th>
      <th>Phone</th>
      <th>Gender</th>
   
   
      <th>Country</th>
      <th>Skills</th>
     
      </tr>";


    while ($row = mysql_fetch_array($resultTable)) {
        echo "</td><td>";
        echo $row['email'];
        echo "</td><td>";
        echo $row['fname'];
        echo "</td><td>";
        echo $row['lname'];
        echo "</td><td>";
        echo $row['date'];
        echo "</td><td>";
        echo $row['volunType'];
        echo "</td><td>";
        echo $row['address'];
        echo "</td><td>";
        echo $row['phone'];
        echo "</td><td>";
       
        $gen = $row['gender'];
                    if($gen == 1){
                        echo "M";
                    }else{
                        echo "F";
                    }
       
     
        echo "</td><td>";
     
        echo $row['country'];
        echo "</td><td>";
        echo $row['skills'];
        echo "</td></tr>";
    }
}

// }              
?>

                </table>

    </body>
</html>



Sunday, August 4, 2013

Design form and Connect With Database


In this artical i am going to explain how to create PHP forum and how to connect it to the mysql database. For this purpose I use NetBeans 7.3 as PHP development IDE, HTML5 and PHP 4.0. You can select development technologies as your wish. This is I describing regarding one of my project which i did. You can use this as a help of your projects. This is something similar to registrations.    I'll explain this under 3 main steps.
  1. Form Designing
  2. Establish Database Connectivity
  3. Pass values to database

01 Form Designing

For the designing of the form i used HTML5 and CSS is used to add certain styls to the form. Such as coloured text boxes, coloued buttons etc... Here I used separate classes for form labels, form inputs. Then I can do all CSS works in one separate .css file and it can attach to this form as well  as other forms also. Addition to  that i used capture code for person identifications. Here is the image of  form.





Here is the sample HTML code for designing above form. 

 <form method="POST" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" id="registerMember">
             
        <table border="0" width="500px" cellspacing="5px" cellpadding="2px">
                        <thead>
                            <tr>
                                <th colspan="2" class="formheadings"><b>Personal Information</b></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="formlabels">Email</td>
                                <td class="forminputs">
                                    <input type="email" name="textEmail" id="textEmail" value="buddhika@gmail.com"
required maxlength="254" title="Enter an email"/>
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabels">First Name</td>
                                <td class="forminputs"><input type="text" name="fname" id="fname" value="Buddhika" /></td>
                            </tr>
                            <tr>
                                <td class="formlabels">Last Name</td>
                                <td class="forminputs"><input type="text" name="lname" id="lname" value="Yahampath"/></td>
                            </tr>
                            <tr>
                                <td class="formlabels">Date of Birth</td>
                                <td class="forminputs"><input type="date" class="datepicker" name="dob" id="dob"                                         value="1990-06-04"  required readonly title="Select Your Birth Date"/>                                                      <span>"yyyy-MM-dd"</span></td>
                            </tr>
                            <tr>
                                <td class="formlabels">Member Type</td>
                                <td class="forminputs">
                                    <select name="comboMemType" id="comboMemType">
                                        <option>Family</option>
                                        <option>Individual</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabels">Password</td>
                                <td class="forminputs"><input type="password" id="password" name="password"                                               required title="Enter a Desired Password"/></td>
                            </tr>
                            <tr>
                                <td class="formlabels">Confirm Password</td>
                                <td  class="forminputs"><input type="password" id="con_password"                                                                    name="con_password" title="Reenter above Password"
                 onfocus="validatePass(document.getElementById('password'), this);"
                  oninput="validatePass(document.getElementById('password'),this);"
                                          required /></td>
                            </tr>
                            <tr>
                                <td class="formlabels">Address</td>
                                <td class="forminputs"><textarea name="address" id="address" cols="25" rows="5"                                            title="Enter Your Address"></textarea></td>
                            </tr>
                            <tr>
                                <td class="formlabels">Phone no.</td>
                                <td class="forminputs">
                                    <input type="tel" id="phone" name="phone" value="0716338174" pattern="[0-9.]+"                                              title="Enter Contact Number"/>
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabels">Country</td>    
                                <td  class="forminputs">
                                    <select name="countryName">
                                        <option value="AF">Afghanistan</option>
                                        <option value="AX">Ă…land Islands</option>
                                        <option value="AL">Albania</option>
                                        <option value="DZ">Algeria</option>
                                        <option value="CK">Cook Islands</option>
                                        <option value="CR">Costa Rica</option>
                                        <option value="YE">Yemen</option>
                                        <option value="ZM">Zambia</option>
                                        <option value="ZW">Zimbabwe</option>
                                    </select>
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabels">Zip Code / Postal Code</td>
                                <td class="forminputs"><input type="text" name="zip" id="zip" value="80300"                                                  title="Enter digits Only required  pattern="[0-9.]+" style="text-align: right"                                                       title="Enter Your Postal or Zip code"/></td>
                            </tr>
                            <tr>
                                <td class="formlabels">Gender</td>
                                <td class="forminputs">
                                    <input type="radio" name="gender" id="gender1" value="1" checked/>Male
                                    <input type="radio" name="gender" id="gender0" value="0"/>Female
                                </td>
                            </tr>
                            <tr>
                                <td colspan="2" class="formheadings"><b>Purchase Information</b></td>
                            </tr>
                            <tr>
                                <td class="formlabels">Credit Card Type</td>
                                <td class="forminputs">
                                    <input type="radio" name="creditcardtype" value="Visa" checked/><img                                                            src="../images/static/visa.png"/>
                                    <input type="radio" name="creditcardtype" value="Master" /><img                                                                      src="../images/static/master.png"/>
                                </td>
                            </tr>
                            <tr>
                                <td class="formlabels">Credit Card Number</td>
                                <td class="forminputs"><input type="text" name="creditcardno" placeholder="Credit                                           Card Number" pattern=".{14}"   title="Enter 14 Digits Credit Card Number"                                            required/></td>
                            </tr>
                            <tr>
                                <td class="formlabels">Verification Value</td>
                                <td class="forminputs"><input type="text" name="cvv"  placeholder="CVV" required                                          pattern=".{3}" title="Must have 4 digits"/></td>
                            </tr>
                            <tr>
                                <td class="formlabels">Expire Date</td>
                                <td class="forminputs">
                                    <table><tr>
                                            <td>Month<input type="number" id="txtmonth" name="txtmonth" required                                                          pattern=".{2}" min="1" max="12" value="01"
   title="Your Credit Card Expiration Month"/></td>
                                            <td>Year<input type="number" id="txtyear" name="txtyear" required                                                                             min="2013" value="2019" max="2024"
                                                             pattern=".{4}"  title="Your Credit Card Expiration Year"/></td>
                                        </tr></table>
                                </td>
                            </tr>
                            <tr><td colspan="2">
                                    <img src="../models/captcha_code_file.php?rand=<?php echo rand(); ?>"                                                              id='captchaimg' ><br>
                                            <label for='message'>Enter the code above here :</label><br>
                                                <input id="6_letters_code" name="6_letters_code" type="text" required/>                                                           <br>
                                                        <small>Can't read the image? click <a href='javascript:                                                                                              refreshCaptcha();'>here</a> to refresh</small>
                                                        </td></tr>
                                                        <tr>
                                                            <td colspan="2" class="forminputs" align="center">
                                                                <input type="submit" value="Submit" name="submit" id="submit"                                                                        class="zoobutton"/>
                                                                <input type="reset" value="Reset" class="zoobutton"/>
                                                            </td>
                                                        </tr>
                                           </tbody>
                                      </table>
                                                     
                              </form>
                                               </center>
                         </body>
                    </html>


Jvascripts & css

 You can use javascript functions for validations and CSS for the apply certain styls for the form. Here I used separate two classes for "form labels" and "form inputs". Then i can add css separately.  Here is some sample javascript for password comparisons.

function validatePass(p1, p2) {
    if (p1.value !== p2.value || p1.value === '' || p2.value === '') {
        p2.setCustomValidity('Your passwords does not match.');
    } else {
        p2.setCustomValidity('');
    }
}

javacript for sequrity validations. - This javascript do not allows user to runs the scripts on textbox.

function illegelChar(fld) {
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
    var error = "";
    if (fld.value.match(illegalChars)) {
        fld.style.background = 'Red';
        error = "Some field or fields contains illegal characters.\n";
    } else {
        fld.style.background = 'White';
    }
    return error;
}

Note :- It is better to call this function using "onblur(parameter1)"  methord. 


  • You can use following css code to apply styls on your form.

input[type="text"],input[type="email"],input[type="tel"],
input[type="date"],input[type="number"],input[type="textarea"],
input[type="password"],select,input[type="time"],radio,textarea{
    width:250px;
    border: 2px;
    border-radius:5px;
    text-indent:2px;
    background-color: #FFFFFF;
    box-shadow: 0px 0px 5px rgba(0, 255, 51, 0.7), 0px 1px 2px 0px rgba(0, 0, 0, 0.9) inset;
}

input[type="text"]:focus,input[type="email"]:focus,input[type="tel"]:focus,
input[type="date"]:focus,input[type="number"]:focus,input[type="textarea"]:focus,
input[type="password"]:focus,select:focus,option:focus,input[type="time"]:focus,radio{
    border: 2px solid rgb(153, 255, 51);
    border-radius:5px;
    border-top-width: 2px;
    border-bottom-width: 2px;
    border-top-style: solid;
    border-bottom-style: solid;
    background-color: #FFFFFF;
    border-top-color: rgb(153, 255, 51);
    border-bottom-color: rgb(153, 255, 51);
    box-shadow: 0px 0px 5px rgba(0, 255, 51, 0.7), 0px 1px 2px 0px rgba(0, 0, 0, 0.9) inset;
}

.formlabels{
    vertical-align: top;
    text-align: left;
    text-shadow: calc;
    font-size: 12px;
    font-family: sans-serif;
    width: 25%;
}

.forminputs{
    vertical-align: top;
    text-align: left;
    text-shadow: calc;
    font-size: 12px;
    font-family: sans-serif;
    width: 75%;
}

.formheadings{
    vertical-align: top;
    text-align: center;
    text-shadow: calc;
    font-size: 14px;
    text-decoration-color: whitesmoke;
    font-family: monospace;
    background-color: greenyellow;
}


02 Establish Database Connectivity

To connect with the database we have to write simple code part in PHP file. Then it should be include to your code. Otherwise you can write database connectivity code as a one file along with the form code. But in that case another place if you wants db connection you have to write it again and again. So it better to write separately and include it your code..!

<?php
$host="localhost";
$userName="root";
$password="";
$db_name="sep";
mysql_connect($host,$userName,$password) or die("cannot connect");
mysql_select_db("$db_name") or die ("no database");
?>


03 Pass values to Database

<?php

include "db.php"; // including above cording

if (isset($_POST["submit"])) {

    $email = $_POST["textEmail"];

    $Fname = $_POST["fname"];

    $Lname = $_POST["lname"];

    $DOB = $_POST["dob"];

    $memType = $_POST["comboMemType"];

    $password = md5($_POST["password"]);

    $addr = $_POST["address"];

    $country = $_POST["countryName"];

    $phNo = $_POST["phone"];

    $phoneNo = (int) $phNo;

    $zip = $_POST["zip"];

    $Gender = $_POST["gender"];
 
 
    $nextYear = mktime(0,0,0,date("m"),date("d"),date("Y")+1);
    $next = date("Y/m/d", $nextYear);
 
 
 
    $querry = "INSERT INTO member VALUES ('$email','$password','$Fname','$Lname','$DOB','$memType','$addr','$phoneNo','$country','$zip','$Gender','$next')";

    $result = mysql_query($querry);

    if ($result == 1) {
        echo "<script type='text/javascript'>alert('Registration                                                                                                         successful.');window.parent.location='../dehiwalazoo.php';</script>";

    } else {
        echo "<script type='text/javascript'>alert('Registration was not successfully. Please try again.')

</script>";
    }
}
?>