How to organize your university final project in PHP without a Framework

Sample Project : Click Here to Download

In this post I’ve decided to share you some basic steps on a popular question that I’ve been answering over and over again. “How to organize and start My University Final project and I’m a complete beginner to coding or development”. First go through my points and download the example application and try it by your self. So let’s start.

  • First sit and relax.
  • Think of the system you are going to build, think why you are going to build if it is already available, what should you include in your system to make it unique. Write them down.
  • Think a good name for your System (I’m not talking about the project title, but application title, like ex: Microsoft Word)
  • Think of every basic requirement that is critical to your system. Write them down.
  • Think how those requirements/functions and entities relates to each other; get an A4 paper draw a diagram freely. You can use UML to elaborate it more.
  • Now you can decide how the user interfaces should look like, sketch them up all simply. (just use an A4 a pencil)
  • Start designing UI Pages in code. (You can always refer HTML, CSS, Javascript, PHP, SQL Tutorials accordingly from http://www.w3schools.com/ )
  • Okay, now make sure each User Interface page has a PHP file to handle its activities inside the FORM tag. Better if you can separate the User Interface files from Logic files.
  • Use a naming convention. Like Using a prefix for all of your source files. For Example

o   User interfaces, start with UI_

o   Logic PHP files, start with LOGIC_

o   So “UI_Register.php” will be handled by “LOGIC_Register.php”

  • Use a standard layout/design throughout the system. Which will bring more professionalism to your system.
  • Use a good folder structure. See below sample folder structure

o   Application Name (Main Folder)

·         index.php

§  PUBLIC

·         scripts

·         images

§  LOGIC

·         LOGIC_Register.php

§  UI

·         UI_Register.php


Regarding the sample Project

in LOGIC_Register.php make sure to change following according to your mysql settings in red.

$con=mysqli_connect(“localhost“,”root“,”1234“,”testdb”);

I have included the Database backup as well inside the file. Import it to your mysql server before you test this sample app.

Implementing Singleton Design Pattern in Code – Java

In this post I would like to share a simple example on how to implement Singleton Design Pattern in code using java.

First what is Singleton Design Pattern? Simply singleton design pattern makes sure of creating only one instance of a particular class and providing global access to that instance.

  1. We name our class as “Singleton” (you can name it whatever you want)
  2. Let’s create a private and static instance named “INSTANCE” inside its own.
  3. We’ll make Singleton’s constructor private so that no one can instantiate an object directly.
  4. To access the already created instance “INSTANCE” we’ll create a getter which returns the “INSTANCE”.
  5. So basically that’s it, You have implemented Singleton Design pattern in code which will look like below.
public class Singleton {

    private static Singleton INSTANCE = new Singleton();

    private Singleton(){

    }

    public static Singleton getInstance(){

    return INSTANCE;

    }

}

How Access Modifiers Work – Java

Download Project File(Netbeans 7.0) : Click here to Download

In this post I’m going to share some knowledge on “How Access Modifiers Work” using an example in Java, You can download the Netbeans 7.0 Sample Project and try it out by your self.

In this example there are two packages as,

  • com.package1
  • com.package2

and there are four classes as Foo, Hoo, Bar & Nee. Foo class is the class that having the main method, so we are running the example through the Foo class’s main method. Foo & Hoo resides in com.package1 and Bar & Nee resides in com.package2. Foo has extended Nee. So let’s move on to each class,

/*-----------Foo Class-----------*/
package com.package1;

import com.package2.Bar;
import com.package2.Nee;

/**
 *
 * @author Dilukshan Mahendra
 */
public class Foo extends Nee {

    private void sayPrivate() {

        System.out.println("I'm a private method in Foo!");

    }

    public static void main(String[] args) {

        Hoo myhoo = new Hoo();
        myhoo.sayDefault();
        /*You can call this method because with the default/no access modifier level it allows to access
        the particular method or variable from any class "within the same package"     
         */
        myhoo.sayProtected();
        /*You can call this method because with the protected modifier level it allows to access
        the particular method or variable from any class "within the same package" or from any inherited class
        (from a class that extended this class as its superclass)
         */

        myhoo.sayPublic();
        /*You can call a public method or variable from anywhere*/

        /*----------------------------------*/
        /*myhoo.sayPrivate(); You cannot call a private method or variable outside its own class*/
        /*----------------------------------*/

        /*Let's create an intance of this Foo class*/
        Foo myfoo = new Foo();
        myfoo.sayPrivate();
        /*You can call this private method because we are calling it within the same class*/

        /*Let's create an intance of this Bar class*/
        Bar mybar = new Bar();
        /* mybar.sayDefault();  */
        /*You cannot call this because methods or variables with 
        default or no-access modifier cannot be called from outside the package where its class resides
         */

        /*mybar.sayProtected*/
        /*You cannot call the above either, because to call a protected method or variable 
        you should be calling from the same package or from an instance of inherited class/subclass of it
        so here, neither both are true

         */

        mybar.sayPublic(); // you can call this from anywahere

        /*Let's consider again on the instance of this class Foo, myfoo */
        myfoo.sayProtected();
        /*you can call its superclass's protected method from a subclass object even 
        from outside superclass's package*/

    }
}
/*-----------Hoo Class-----------*/
package com.package1;

/**
 *
 * @author Dilukshan Mahendra
 */
public class Hoo {

    void sayDefault() {

        System.out.println("I'm a default method in Hoo!");

    }

    public void sayPublic() {

        System.out.println("I'm a public method in Hoo!");

    }

    protected void sayProtected() {

        System.out.println("I'm a protected method in Hoo!");

    }

    private void sayPrivate() {

        System.out.println("I'm a private method in Hoo!");

    }
}
/*-----------Bar Class-----------*/
package com.package2;

/**
 *
 * @author Dilukshan Mahendra
 */
public class Bar {

    void sayDefault() {

        System.out.println("I'm a default method in Bar!");

    }

    public void sayPublic() {

        System.out.println("I'm a public method in Bar!");

    }

    protected void sayProtected() {

        System.out.println("I'm a protected method in Bar!");

    }

    private void sayPrivate() {

        System.out.println("I'm a private method in Bar!");

    }
}
/*-----------Nee Class-----------*/
package com.package2;

/**
 *
 * @author Dilukshan Mahendra
 */
public class Nee {

    void sayDefault() {

        System.out.println("I'm a default method in Nee!");

    }

    public void sayPublic() {

        System.out.println("I'm a public method in Nee!");

    }

    protected void sayProtected() {

        System.out.println("I'm a protected method in Nee!");

    }

    private void sayPrivate() {

        System.out.println("I'm a private method in Nee!");

    }
}
/*-----------Final Output will look like-----------*/
I'm a default method in Hoo!
I'm a protected method in Hoo!
I'm a public method in Hoo!
I'm a private method in Foo!
I'm a public method in Bar!
I'm a protected method in Nee!

PHP – Parsing an ID from a dynamically generated table column

Download Project : Click Here to Download

In this example I’m going to show you a technique on how to parse an ID value from a dynamically generated table  to another page using php which will be more useful when you are to edit/delete a dynamically loaded item. So I’m going to use a MySQL Database to generate the table, and parse the ID value on click of a button in particular row. Let’s move on to the example.

1. First Download the sample php project, extract the file into WAMP->WWW or any other hosting server, and import the sql file(“parseiddb”) which is inside that project folder as your database.

2. Now go to ParsingID->application->config->config.php and setup your user settings if they are differ from your own settings.

$config['base_url'] = ‘http://localhost:8080/ParsingID/’ // Base URL including trailing slash (e.g. http://localhost/)
$config['default_controller'] = ‘main’; // Default controller to load
$config['error_controller'] = ‘error’; // Controller used for errors (e.g. 404, 500 etc)
$config['db_host'] = ‘localhost’; // Database host (e.g. localhost)
$config['db_name'] = ‘parseiddb’; // Database name
$config['db_username'] = ‘root’; // Database username
$config['db_password'] = ’1234′; // Database password

3. Run the project through your server and you’ll get the home page something like below.

parsingIdhome

4. Just Click a “Parse ID” Button, you’ll see the “Employee ID” of that particular row will be transferred into another page like below.

parsingId-result

So what I have done here is

    • I have loaded all the employee data from “main” controller using “database_model->getEmployeeDetails()” and load them up in a table in “welcome.php” view.
    • For each record from the database it will generate a row in a table as you would have seen in this example.
    • Notice that I have surrounded the row which is generating inside “for each” loop with a “FORM”.
    • So for each row that is generated will be wrapped by a separate FORM.
    • Also, you could see that there is a HIDDEN field which take up the value of “empid” for each row that is generating.
<table class="CSSTable" cellspacing="0px">
   <tr>
      <td>ID</td>
      <td>Name</td>
      <td>Address</td>
      <td>Salary</td>
      <td>Action</td>
   </tr>
   <?php foreach($employee as $row){?>
   <form action="<?php echo BASE_URL; ?>parseid" method="post">
      <tr>
         <td><?php echo $row->empid; ?><input name="empid" type="hidden" value="<?php echo $row->empid; ?>" /></td>
         <td><?php echo $row->empname; ?></td>
         <td><?php echo $row->empaddress; ?></td>
         <td><?php echo $row->empsalary; ?></td>
         <td>
            <center><input name="btn_parse" type="submit" value="Parse ID" /></center>
         </td>
      </tr>
   </form>
   <?php }?>
</table>
  • Once you click the button of a particular row, it will submit it’s own FORM with the values of the particular row.

Sample Database Class in C#

public class DBConnection
{
static SqlConnection connection;
public void getConnection() {
try {
connection = new SqlConnection("Data Source=YOURSQLINSTANCENAME;Initial Catalog=YOURDATABASE;User ID=YOURUSERID;Password=YOURPASSWORD");
connection.Open();
}catch(Exception e){
throw e;
}
}
public DataTable executeSelectQuery(String sql) {
try
{
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.CommandType = CommandType.Text;

SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
catch (Exception e)
{
throw e;
}
finally {
connection.Close();
}
}
public void executeUpdateQuery(String sql) {
try {
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.ExecuteNonQuery();
}catch(Exception e){
throw e;
}
finally
{
connection.Close();
}
}
}

SQL Exercise 02 – Employee & Department

Create the following tables (employee , department) and insert the data given. empid is the PK of Employee and deptid is the PK of Department. (Assume salary is in $ ). Try it by yourself without looking the answers first.

Employee

tbl-emp

Department

tbl-dept

Q1. Find all employee details along with their department and the working location.

Q2. Find all employee names who has a salary equal or greater than 300 and the working location is not ‘Ontario’.

Q3. Find all the employee names whose name starts with a ‘A’.

Q4. Find all Employees who has same salaries as some others do.


Solutions

Q1.

select e.empid,e.empname,e.empsalary,d.deptid,d.deptname,d.deptlocation
from employee e
inner join department d
on e.empdept = d.deptid

Q2.

select e.empname
from employee e
inner join department d
on e.empdept = d.deptid
where e.empsalary >= 300 and d.deptlocation != 'Ontario'

Q3.
select e.empname
from employee e
where e.empname like 'A%'

Q4.

select *
from employee
where empsalary
in (select empsalary from employee group by empsalary having count(empsalary) > 1 )

Or you also can do it by

SELECT * FROM employee a
WHERE EXISTS (
SELECT 1 FROM employee b
WHERE a.empsalary = b.empsalary
AND a.empid <> b.empid
)

SQL Exercise 01 – Doctor & Patient

Create the following tables (Doctor , Patient) and insert the data given (Assume that a patient only has one doctor to consult him/her, but a doctor can consult one or more patients). Write the queries to achieve the asked information. (Try it by yourself without looking the answers first)

Doctor

table-doctor

Patient

table-patient

Q1. Find all the details about the Doctors with the count of the patients they are consulting.

Q2. Find all the details about the Doctors with the count of the patients and where they are consulting more than 1 patient.


Solutions

Q1.

select d.doctorid,d.doctorname,count(p.patientid) AS patients
from doctor d
inner join patient p
on d.doctorid = p.doctorid
group by p.doctorid

Q2.
select d.doctorid,d.doctorname,count(p.patientid) AS patients
from doctor d
inner join patient p
on d.doctorid = p.doctorid
group by p.doctorid
having patients > 1

Object Oriented Programming (OOP) – Understanding the Basics

In this Post I’m going to share some basic knowledge on OOP concepts with an example project (Java and Netbeans 7.0) using a practical scenario.

Download Link : Click here to download

OOP or Object-oriented programming (OOP) is a programming technique that uses “Objects “and their interactions to design applications and computer programs which is based on the following concepts which are

  • Objects
  • Classes
  • Data Abstraction and Encapsulation
  • Inheritance
  • Polymorphism

So in this technique we design the system/program using separate objects which are specific to a particular task/purpose. You can achieve many benefits using OOP like

  • Clear Modular Structure where other programmers can understand your code
  • Code Re-usability which will save your time in the long run
  • Ease of Maintainability
  • Security

Send and Retrieve Data Using JSON & AJAX (Via Netbeans 7.0)

Download Link : Click here to download

In this example I would like to share you a simple project I’ve created to Send and Retrieve Data Using JSON & AJAX, Specially if you are a beginner for JSON & AJAX.

“We use JSON to store and transport data as we do in XML, But in a more smaller, faster and easier way than XML. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.”
 

The Example contains A Netbeans 7.0 Project file and MySQL Database Backup where the application transacts with a MySQL database to retrieve data using JSON & AJAX.

ex1ajaxjson

The application searches for user details by UserID and displays in Name & Address fields without refreshing the page.

Fix “Login failed for user.” when trying to access a SQL Server Express database from VS2010 C#

Try to replace your SQL instance name which will start by your computer name instead of DILUKSHAN-PC\\SQLEXPRESS after “Data Source”. For example:

SqlConnection Connection = new SqlConnection(“Data Source=DILUKSHAN-PC\\SQLEXPRESS;Initial Catalog=ExamDBSQL;User ID=xxxxx;Password=xxxxx”);