You are on page 1of 24

UX For Dummies

From UX For Dummies by Kevin Nichols, Donald Chesnut


The world of UX (user experience) strategy may seem complicated and hard to grasp. But anyone who wants to build
a digital experience (whether for a local business or a national corporation) can leverage UX best practices to ensure
that the experience meets basic user needs. Optimize the user experience by following UX design phases from
discovery and defining to designing and building. Finally, evaluate and refine your design to ensure a great user
experience.
4 Important Parts of a UX Design Strategy
The goal of any well-crafted user experience (UX) strategy is to focus the company's web presence on the needs of
its customers. You achieve this by integrating web design, user research, business planning, and data analysis.
Always remember that a strong UX design strategy includes these four parts:

A clear, well-defined intent for the experience, goals, and objectives.

Documentation defining the features, functionality, and content necessary to support the objectives. Here,
the user is tantamount, meaning that you must design your experience around your users' needs.

A testing process to make sure the design works. Validation is critical, so don't forget to test your designs and
direction throughout the process of developing it.

Solid planning. Good UX connects the goals and objectives of a business with users' needs by serving up an
experience the users can, well, use. How do you do it? Start with a plan for what you need to do.
UX Design: 8 Elements of the Discovery Phase
During the discovery phase of UX (user experience) design for a website, you assess the current state of your UX, if
you have one, and your competitors' experiences. The following eight points should be part of your assessment:

Survey and define who your users or potential users are. Get as much information as you can about them.
Look at any existing user research, consumer or customer data, and insights from user testing to gather
information about who will use the experience.

Assess any user feedback or analytics to determine what is working and what is not working within your
current experience.

Conduct a competitive analysis to identify the types of features and functionality you can offer your users.
Find out what competitors and their users do and don't have, and then do it better in your UX!

Review your existing content and figure out what you need to do with it, what types of content will tell your
story, and what your competitors offer that you don't. Use a content inventory to capture your content or that of
your competitors and overlay it with an audit to assess how well the content is performing.

If you have a current experience, identify gaps where you could improve the experience, issues, and
strengths. Use a tool, such as a heuristic assessment, to measure the performance of the UX. A heuristic
assessment is a scorecard that weights what is working and what is not based on UX best practices.

Review your technology environment and note the constraints (such as what you have in place to deliver the
experience) and the channel outputs (where it needs to live).

Ask those people in your organization who have a vested interest in the experience to specify their
requirements. Interview brand representatives, marketing teams, product leads, legal teams, tech folks, and any
other people who need to be involved with the UX and the ultimate solution.

Ensure that all stakeholders agree with the final list of needs, requirements, and findings from what you
learn in the discovery phase.
UX Design: 5 Questions for the Define Phase
The define phase of a UX (user experience) design defines the goals, objectives, and strategy for the UX. During this
phase you detail who your website users are and the requirements they have.
The easiest way to define this information is to take the findings from the discovery phase, look at what's working or
necessary and what's not, examine at any gaps or issues with your existing experience and/or that of your
competitors, look at your business or organization, and then ask yourself, "What does my experience need to
accomplish?"
Start with a goal, such as, "Be the most competitive website in the market," and define a set of objectives that are
realistic and attainable. An example is "The experience will increase overall revenue by 20% over the next six
months." Create a strategy around what the experience needs to do and answer the following questions:

Who? Use personas (tools that document how users behave) and user scenarios (tools that capture detailed
information about prototypical users) to further define your users.

Why? Examine the user needs or tasks that need to be accomplished in the UX. Employ user tasks to detail the
end-to-end journeys required for the user to accomplish a task. Remember, list the tasks you need the user to
achieve and frame your journeys around that.

What? Anticipate which devices or channels such as desktop, smartphone, tablet, and so on the user will
employ to engage with your UX. Compose a list of every type of device the user will engage while using the
experience. Remember, you don't control whether a user engages with a mobile device or desktop computer in
most cases.

Where? Predict where the user will most likely use the experience. With the prevalence of mobile technology
today, the user's venue could vary. Ensure you capture and consider various locations, such as at home, en route
to the store, in the store, and so on.

When? What time of day is a user likely to engage with the experience? Don't just plot the times to a clock. Also
consider events and holidays, such as anniversaries involving gift-giving, Valentine's Day, or any time the user
would need to re-engage with the experience.
When you have answered these questions, capture the information in a brief and ensure that you use this logic
when fleshing out the lower-level designs of the experience.
Consider the following:

High-level requirements that list the features and functionality you want your UX to showcase.

Personas for representative users that capture behaviors and characteristics of your types of users. At a
minimum, complete four or five personas. Also sketch out some user scenarios, which detail what a persona
would do to complete a task.

A list of user tasks that details the types of things you want your users to accomplish and a high-level user journey
that captures the end-to-end steps the user will complete. These can be further fleshed out during the design
phase, but remember to capture the channels with which your users will engage and the types of content they will
need to do so.

A list of preliminary content types for example, news releases, home page content, product details page
content, and so on.

A high-level sitemap or high-level architecture, which includes the primary areas of the experience grouped into
categories and subcategories.

Mood boards for the visual design, which define the emotional experience for the UX.

A finalized content audit that lists issues with any current experiences or content and where the content needs to
go.

A survey of your competition where you learn in which areas you can differentiate your UX from your competitors'
experiences.
UX Design: 15 Deliverables for the Design Phase
The design phase of a UX (user experience) is when you actually design the solution, including the look and feel, the
functionality, and the detailed specifications for how the UX will perform.
Your design phase should include these 15 deliverables:

A detailed sitemap that lists the major categories of information in your experience, the subcategories that fall
under the main categories, and any tertiary or additional categories. For example: Animals>Cats>Hypoallergenic
Cats.

A finalized list of features and functionality. You should account for content types with definitions for each and
a description of where and when to use them.

Wireframes that capture what goes on a page type or template and the placement of information.

Navigation models that go into wireframes and show the navigation (primary, secondary, and tertiary) of the
experience.

Page-level content strategy that lists the goals and objectives of page types and identifies who will use those
pages. Include prioritized types of content necessary to accomplish and fulfill the objectives.

Content matrix and models that define the rules for how content is used, from templates to each module that
lives within the templates.

Taxonomy (if necessary) that shows the hierarchy of information. The taxonomy is used to build search engine
and metadata schemas.

Detailed end-to-end user journeys for each type of task.

Functional specifications that detail the rules (business rules and technology requirements) for each wireframe.

Visual guidelines for color, typography, and brand.

Visual design comps (comparables), or final drafts, that finalize the look and feel of the experience.

Visual style guide that captures the rules for the visual design, including measurements for each page type,
colors, typography, fonts, margins and gutters, and specifications for content (such as images, videos, and so on).
Include a content style guide within this document for voice, tone, and rules of use of content.

End-to-end content life cycles for each content type that captures who supplies the content; how it should be
acquired, created, reviewed, and entered into a system, such as a CMS; how it should be tagged and published;
and how it should be measured and optimized and/or retired.

Governance model for the overall solution that shows a governance committee and the tools used to govern
the solution, such as a visual style guide.

List of factors you want to measure and the types of metrics you'll use for measurement.These factors
should take into account what you want your experience to achieve.
For navigation, labels, nomenclature, wireframe designs, user journeys, and taxonomies, you can take advantage of
user testing to validate what you come up with. Use card sorting to figure out how to group information and label it.
Reverse card sorting (tree testing) can validate a navigation and taxonomy after an initial iteration of it. Use clickable
prototypes to test wireframes, the placement of information, and navigation. You can also use participatory design
techniques to test visual design comps.
UX Design: 5 Tasks for the Build Phase
Technology teams implement the build phase of a UX design, so UX designers might think it's time for a welldeserved break. Sorry, but during the build phase, you can still create some deliverables, including finalizing the
documentation (such as a visual style guide for the UX).
Additionally, you can complete the following:

Final metrics that you want to measure, a schedule for when and where the data will be collected, and a
reporting dashboard.

Content production (creation) plan and migration plan, which may include a map for which content in the
existing experience will migrate to the new UX and where it should go.

Editorial calendar that plots out which content is necessary to support the future experience.

A testing plan and scripts for testing the solution within its actual environment.
UX Design: The Evaluate and Optimize Phase
During the evaluate and optimize phase of UX (user experience) design, you use metrics and user feedback to
evaluate what you've launched. As you uncover what's working on the website and what isn't, you can make
recommendations for future releases.
Continually evaluate your experience. UX is an ongoing process for as long as the website exists. Test your
experience every three to four months and update it accordingly.

Technology is always evolving, so remember to evaluate your UX against changes in technology and trends. Taking
a good hard look at your experience in comparison to the new technologies that have been developed can help you
keep your UX relevant for the future!

function prima($n){
for($i=1;$i<=$n;$i++){

//smw angka yg akan di cek

$counter = 0;
for($j=1;$j<=$i;$j++){ //smw kemungkinan faktor pembagi
//jika angka yg akan dicek habis dibagi faktor pembagi, counter nya +1
if($i % $j==0){
$counter++;
}
}

//jumlah warna hijau / faktor habis bagi nya harus2


if($counter==2){
print $i." is Prime <br/>";
}

}
}
prima(20); //cari bilang prima dari 1-20

Simple palindrome program in PHP


What is Palindrome?
It is a word or phrase that is the same spelled forwards and backwards. Example: madam, level, Malayalam etc.
Find string palindrome or not in PHP using strrev() function
<?php
$word = "level";
// declare a varibale
echo "String: " . $word . "<br>";
$reverse = strrev($word);
// reverse the word
if ($word == $reverse)
// compare if

the original word is same as the reverse of the same word

echo 'Output: This string is a palindrome';


else
echo 'Output: This is not a palindrome'; ?>
Find string palindrome or not in PHP without using strrev() function
<?php
$mystring = "level"; // set the string
echo "String: " . $mystring;
$myArray = array(); // php array
$myArray = str_split($mystring); //split the array
$len = sizeof($myArray); // get the size of array
$newString = "";

for ($i = $len; $i >= 0; $i--) {

if ($mystring == $newString) {

$newString.=$myArray[$i]; } echo "<br>";

echo "Output: " . $mystring . " is a palindrome"; } else {

echo "Output: " . $mystring . " is not a palindrome"; } ?>

star triangle

$star = "*"; echo $star."\n";


for ($i=0; $i<=10; $i++)
{
$star = $star."**";
echo $star;
echo str_repeat("0",
$i+1);
echo "\n";
}
Deret fibonacci adalah deret matematika yang dimana polanya adalah angka berikutnya
merupakan hasil penjumlahan angka sebelumnya. kali ini saya akan memberikan sedikit
script untuk membuat deret fibonacci dengan menggunakan bahasa pemrograman PHP.
Ini adalah contoh deret Fibonacci
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, dst.
<?php
$a=0;
$b=1;
echo $a.<br>;
for($i=1;$i<=10;$i++){
$c=$a+$b;
$a=$b;
$b=$c;
echo .$c.<br>;
}
?>
bubble short ascending
<?php
$arr = array(7, 3, 9, 6, 5, 1, 2, 0, 8, 4);
$sortedArr = bubbleSort($arr);
var_dump($sortedArr);
function bubbleSort(array $arr) {
$sorted = false;
while (false === $sorted) {
$sorted = true;
for ($i = 0; $i < count($arr)-1; ++$i) {
$current = $arr[$i];
$next = $arr[$i+1];
if ($next < $current) {
$arr[$i] = $next;
$arr[$i+1] = $current;
$sorted = false;
}
}
}
return $arr;
}

result

array(10) {
[0]=>
int(0)
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(3)
[4]=>
int(4)
[5]=>
int(5)
[6]=>
int(6)
[7]=>
int(7)
[8]=>
int(8)
[9]=>
int(9) }

bubble sort Descending order:

<?php
$arr = array(7, 3, 9, 6, 5, 1, 2, 0, 8, 4);
$sortedArr = bubbleSortDesc($arr);
var_dump($sortedArr);
function bubbleSortDesc(array $arr) {
$sorted = false;
while (false === $sorted) {
$sorted = true;
for ($i = 0; $i < count($arr)-1; ++$i) {
$current = $arr[$i];
$next = $arr[$i+1];
if ($next > $current) {
$arr[$i] = $next;
$arr[$i+1] = $current;
$sorted = false;
}
}
}
return $arr;
}

another bubble short

1. function bubbleSort ($items) {


2.
$size = count($items);
3.
for ($i=0; $i<$size; $i++) {
4.
for ($j=0; $j<$size-1-$i; $j++) {
5.
if ($items[$j+1] < $items[$j]) {
6.
arraySwap($items, $j, $j+1);
7.
}
8.
}
9.
}
10.
return $items;
11. }
12. function arraySwap (&$arr, $index1, $index2) {
13.
list($arr[$index1], $arr[$index2]) = array($arr[$index2], $arr[$index1])
;
14. }

Principles Of Object Oriented Programming in PHP


By Marc Plotz
Object Oriented Programming, or OOP, refers to the method of programming that invokes the use of classes to
organize the data and structure of an application. With PHP, OOP started to become feasible with the release of PHP
4, but really came into its own with PHP 5. Now, as the world awaits the release of PHP 6 we await another great
leap in the evolution of PHP OOP.
While a large number of programmers shun the use of OOP as a programming paradigm, many more are seeing the
advantages of OOP every day. Objects are here to stay - and if you don't like them yet, give it a chance: there comes
a time in every developers career when he makes the evolutionary step up to OOP.
In this article we are going explore exactly what OOP is in relation to PHP, and look at a few things you should
remember about it as well. We'll end of with a simple example of how to use it.
Objects
The first thing that we need to wrap our heads around is the principle of Classes. Put simply, a Class is an Object,
and an Object is a Class. But, like an everyday object, PHP Objects have certain properties, and they can do things.
A simple class might look like this:
<?php

class human { public $gender='Male'; }

The very basic use - and not very good use, I might add - of this simple class would be to get the gender of a human.
Unfortunately, all humans instantiated below will be Male by default.
We use the class as follows:
<?php $Johnny = new human;

echo 'Johnny is a '. $Johnny->gender.'.';

Which will return


Johnny is a male.
For simple objects, that may be fine, but what if we needed to set the gender of a human as either male or female?
The Constructor
This is where we start to see the power of OOP. Consider the example below:
<?php

class human { public $gender;

>gender = $gender; }

public function __construct($gender) { $this-

public function get_gender() { return $this->gender; } }

Adding the Contructor Method (function) to the class makes things a little more interesting. First of all, we can now
instantiate this class like this:
<?php $Johnny = new human('male');
As you can see, whatever arguments you pass directly into the object on instantiation are passed into the constructor
method of the object. What happens now, if you look at our constructor, is that we have assigned the value of the
argument ($gender) to a Property of the object, by using $this. Let's explore that a little more.
$this
This may sound a little loopy (no pun intended) because what on Earth is $this? Think of it as a reference to the
current object. So if you have an object and you are referencing or assigning a value to $this->gender, then you are
referencing or assigning a value to the gender Property of the object you are currently working with.
self::
Now, $this is a good way of referencing properties, but how do we reference Methods? Remember, a Method is a
function inside an object, and gives the Object the ability to DO THINGS.
So, in order to call a Method of the Object I am working in, I can use the self:: call, as below:
<?php

class human { public $gender;

>gender = $gender;

public function __construct($gender) { $this-

echo self::get_gender(); }

public function get_gender() { return

$this->gender; } }
What you will see now is that once the object is instantiated, it sets the value of $gender, and then runs the
get_gender() function, which prints the following to the screen:
Male

This makes setting up and running methods in a current class very simple.
Inheritance
So far, things are simple. But now we take thing once step further by introducing inheritance.
Inheritance is just like it sounds - we talk about one object extending another one, and when it does, it inherits the
properties and methods of the parent object.
In terms of out human class, lets try the following:
<?php

class human { public $gender;

public function __construct($gender) { $this-

>gender = $gender;

echo self::get_gender(); }

public function get_gender() { return

$this->gender; } }

class person extends human { public $name; public $surname;

public static function set_name($name) { $this->name = $name; }


function set_surname($surname) { $this->surname = $surname; }
get_name() { return $this->name; }
$this->surname; } }

public static

public static function

public static function get_surname() { return

$Johnny = new person('male'); $Johnny->set_name('Johnny');

$Johnny->set_surname('Williams');

echo $Johnny->get_name().' '.$Johnny-

>get_surname().' is a '.$this->get_gender();

$Mary = new person('female'); $Mary-

>set_name('Mary'); $Mary->set_surname('Williams');

echo $Mary->get_name().' '.$Mary-

>get_surname().' is a '.$this->get_gender();
Accessors
Accessors are instructions that generally give a property of method permission to be accessible in different ways.
There are three types:
public: This property or permission is accessible from anywhere in the application.
protected: This property or permission is accessible only from a class that extends the parent class.
private: This property or permission is accessible only within the current class you are working with.
The really neat thing about access is that it protects your code should other developers be working on the same
project. If you don't want them to be able to touch something, don't give him access to it.
In conclusion
In this article we have seen the very basics of PHP OOP. We have found that objects are classes that have
properties and methods. We have also found that objects have a constructor class that runs when an object is
instantiated, and that we can use SELF or $this in an object to reference methods or properties within the class.

an object;
is defined;
An object is an instance of a class. You define a class using the code below.

class parentClass
{
//code in here
}
is instantiated;
$parentObject = new parentClass;
Optionally, you can pass variables (or properties) into the class which are used by the constructor
method.

$parentObject = new parentClass($var1, $var2);


has a constructor;
This is a magic method which is executed when the object is instantiated. If no constructor is
defined, the constructor from the parent class (if applicable) is used.

function __construct()
{
//code in here
}
If you are passing variables into the object then you will need to use the following code:

function __construct($var1, $var2)


{
//code in here
}
You can use the parent constructor instead. By defining the constructor in the child class you can
run some processing or pass in additional arguments into the parent constructor. For example,

function __construct($var1, $var2)


{
parent::__construct($var1, $var2, $var3);
}
OBJECT ORIENTED PROGRAMMING IN PHP
Page 1 of 9has a destructor;
This magic method is executed when the object has finished, usually once the script has
finished processing.

function __destruct()
{
//code in here
}
can inherit;
A class can inherit from another class and access all of the parent methods and properties
contained within. This is one of the key principles of OOP; Inheritance.

class childClass extends parentClass


{

//code in here
}
can be abstract;
This class cannot be instantiated directly and must be extended from. This is one of the key
principles of OOP; Abstraction.

abstract class parentClass


{
//code in here
}
can be final;
This is the last class in the hierarchy. You cannot extend from this class.

final class childClass extends parentClass


{
//code in here
}
can be copied;
An object (an instance of a class) can be copied. This creates an entirely new instance of the
object containing the data at the point the object was copied.

$childObject = new childClass;


$copy_of_childObject = clone $childObject;
OBJECT ORIENTED PROGRAMMING IN PHP
Page 2 of 9 can be autoloaded;
Auto loading is a magic method which is called once a new object is instantiated. It is commonly
used to include the class PHP file so you dont need to include all the class files in your
application. For example;

function __autoload($class)
{
include_once(CLASS_INCLUDE_PATH.'class.'.$class.'.php');
}

using instanceof;

This is used to determine whether a variable is an instantiated object.

$childObject = new childClass;


if ($childObject instanceof childClass)
{
//this is true
}
using __call();
This is a magic method which is run when an inaccessible or undefined method is called. The
function name and arguments must be passed in as arguments.

function __call($function, $args)


{
echo Call to inaccessible or undefined method.<br>;
echo Method: .$function.<br>;
echo implode(', ', $args);
exit;
}
a method;
is defined;
A method is a function within a class.

function childMethod()
{
echo 'This is a method.';
}
is accessed;
Use methods in the exact way as you would normally use a function. You can pass variables into
the method if you wish. To call the method from within the class itself use;
$this->childMethod();
OBJECT ORIENTED PROGRAMMING IN PHP
Page 3 of 9 To call the method from outside the class use;

$childObject = new childClass;


$result = $childObject->childMethod();

You can also call methods from parent classes in the exact same way. You reference them from
within the class and outside of the class using;

$childObject = new childClass;


$result = $childObject->parentMethod();

Alternatively, from within the child class you can use the following. This is normally only used
when referencing static methods or properties.
$result = parent::parentMethod();
can be abstract;
Making a method abstract means it must be defined in all child classes. If arguments are given,
they must also be included in the child classes. See examples below from the parent class;

abstract function requiredMethod($var1, $var2);


abstract function anotherRequiredMethod();
can be overridden;
You can override a method in child classes, providing they are not set as final (see below). For
example, the following method can be defined in the child class. This is one of the key principles
of OOP; Polymorphism.

function parentMethod()
{
echo 'This is the same as the parent method.';
}
can be final;
Marking a method as final means it cannot be overridden in subsequent child classes.

final function parentMethod()


{
echo 'You cannot define another method with this name';
}
OBJECT ORIENTED PROGRAMMING IN PHP
Page 4 of 9 can be public;
By default, all methods are public. However, it is best practice to add the public keyword. This is
one of the key principles of OOP; Encapsulation.

public function parentMethod()

{
//code in here
}
can be private;
If a method is set as private it can only be accessed from within the class itself.

private function parentMethod()


{
//code in here
}
can be static;
A static method allows you to access static properties within a class, and nothing else. You do
not need to instantiate an object to access the static method. To define a static method use;

//define a static constant


static public $static = 10;
static function staticMethod()
{
//to access a static property use the self keyword
echo self::$static;
}
Then to access the method from outside the class without instantiating the object (where
childClass is the name of the object) use;
echo childClass::staticMethod();
type hinting;
Type hinting allows you to specify the data type of arguments being passed into a method. For
example, you may only wish an array or an instance of an object to be passed in.

public function parentMethod(childClass $childObject)


{
echo 'The variable must be an instance of childClass';
}

OBJECT ORIENTED PROGRAMMING IN PHP


Page 5 of 9 You can also specify that an argument is an array using;

public function parentMethod(array $array)

{
echo 'The variable must be an array';
}
using func_num_args();
This is a function which can be used within a method to check the number of arguments passed
into the method. For example;

public function parentMethod($var1, $var2)


{
if (func_num_args() != 2)
{
! ! return false;
}
else
{
! ! //code in here
}
}
a property;
is defined;
A property is a variable within a class. To define a property use;
$childVar = True;
is accessed;
To reference a property or set a property value from within the class itself use;

//to reference a property


print $this->childVar;
//to set a property value
$this->childVar = False;
To reference a property or set a property value from outside of the class use;

//to reference a property


print $childObject->childVar;
//to set a property value
$childObject->childVar = False;
OBJECT ORIENTED PROGRAMMING IN PHP
Page 6 of 9 can be public;

By default, all properties are public. This means they can be accessed and manipulated from
anywhere. However, it is best practice to add the public keyword;

public $childVar = True;


public $anotherVar;
can be private;
A private property can only be accessed from within the class itself, not even in child classes.

private $childVar = True;


private $anotherVar;
can be protected;
A protected property can only be accessed from within the class itself and any child classes. It
cannot be accessed from outside.

protected $childVar = True;


protected $anotherVar;
can be static;
You do not need to instantiate an object to access a static property. To define a static property
use;

static public $static = 10;


To access the property from outside the class without instantiating the object (where
childClass is the name of the object) use;
echo childClass::$static;
can be constant;
Constant properties will never change under any circumstances and are typically used as
references for passing in as arguments into a method. For example, rather than passing in a value
of 1, pass in the constant value STATUS_PENDING which has meaning. To define a constant use;

const STATUS_PENDING = 1;
To access the constant you use the class name in the same way as access static properties.
echo childClass::STATUS_PENDING;
OBJECT ORIENTED PROGRAMMING IN PHP
Page 7 of 9an interface;
is defined;
An interface is an instruction manual or template on how classes must be used. It is similar to

defining abstract methods in parent classes but allows for greater flexibility across multiple
classes. It is typically used for high-level tasks such as logging or exception handling.

interface template
{
//code in here
}
can contain methods;
This means that the defined methods and their signatures must be used somewhere in the
hierarchy that uses this interface.

interface template
{
public function parseXML($xml);
}
can contain constants;
You can declare interface constants which can be used within the classes and also from outside.
They cannot be overridden any class which uses the interface.

interface template
{
const name = Hello;
}
To access these constants use;
echo template::name;
is implemented;
When defining a class, you use the implements keyword to say the class must use the interface
template. More than one interface can be implemented if desired.

class parentClass implements template


{
//code in here
}
OBJECT ORIENTED PROGRAMMING IN PHP
Page 8 of 9 can be extended;
Interface can extend from other interfaces and inherit the same methods and constants from the
parent interfaces.

interface template extends mainTemplate


{
//code in here
}
misc;
php5 oop;
http://www.php.net/manual/en/oop5.intro.php
OBJECT ORIENTED PROGRAMMING IN PHP
Page 9 of 9

CRUD PHP MYSQL


<? session_start();
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//
//

**** dbCRUD : READ ME ****


dbCrud allows non-technical users to perform CRUD operations (create, read, update, delete)
on a MySQL database that contains hierarchical data, where each table is a parent or child of
another table.
Before you use dbCrud, you should create the necessary tables in your database.
Here's how the database should be structured:
* Table names should be singular (e.g. "user" rather than "users")
* Each table should contain, at a minimum, an "id" field and a "name" field
* Each child table should have a field that contains its parent ID.
EXAMPLE:
If the parent table is "company" and the child table is "employee",
then the "employee" table should contain a "company_id" field that
should be linked (using a foreign key) to the "id" field in the
"company" table.
The only portion of this file you should NEED to edit is your database settings.
You probably will WANT to also edit the HTML (at the bottom of the file).

// Database settings
$db_connect = mysql_connect('localhost', 'username', 'password') or die ("Problem connecting to da
tabase.");
$db_name = 'my_database';
$db_select = mysql_select_db($db_name, $db_connect);
// By default, dbCrud is not password-protected, which basically means that anybody
// can edit your database. That is generally a very bad idea. To enable password
// protection, set $pwd_protect to TRUE and define a password.
$pwd_protect = FALSE;
$pwd = 'Enter a pa$$word here';
if ($pwd_protect === TRUE && $_SESSION[logged_in] != 1) {
if ($_POST[pwd] == $pwd) {
$_SESSION[logged_in] = 1;
}
else {
echo '<form action="'.$self.'" method=post>Password: <input type=password size=30 name=pwd>
<input type=submit></form>';
exit;
}
}
// Set the number of new rows that each table should provide.
$num_new_rows = 5;
// By default, every table in the database requires a "name" field.
// If you would rather that field be called something else, like "title",
// you can update the value below.
$name_col = 'name';

// Current file
$self = $_SERVER["PHP_SELF"];
// Possibly change current table
if ($_REQUEST[table]) {
$_SESSION[table] = $_REQUEST[table];
}
// Alias for MySQL escaping
function esc($string) {
return mysql_real_escape_string($string);
}
// Get list of tables and determine the parent/child relationships
$query = "SHOW TABLES FROM `".esc($db_name)."`";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$query2 = "SHOW INDEX FROM `".esc($db_name)."`.`".esc($row[0])."`";
$result2 = mysql_query($query2) or die();
if (mysql_num_rows($result2) > 0) {
while ($row2 = mysql_fetch_array($result2)) {
if (strpos($row2['Key_name'], '_id')) {
$this_child = $row2['Table'];
$this_parent = str_replace('_id', '', $row2['Key_name']);
$parent[$this_child] = $this_parent;

$child[$this_parent] = $this_child;
}
}
}
}
}
// Determine the hierarchy
if (!$_SESSION[hierarchy]) {
$parent_child_diff = array_diff($parent, $child);
$hierarchy[0] = array_shift($parent_child_diff);
$child_clone = $child;
while (count($child_clone) > 0) {
$hierarchy_last_key = count($hierarchy)-1;
$clone_last = $hierarchy[$hierarchy_last_key];
array_push($hierarchy, $child_clone[$clone_last]);
unset($child_clone[$clone_last]);
}
$_SESSION[hierarchy] = $hierarchy;
$_SESSION[hierarchy_count] = count($_SESSION[hierarchy]);
}
// If no active table exists, set the active table to the topmost table in the hierarchy
if (!$_SESSION[table]) {
$_SESSION[table] = $hierarchy[0];
}
// Determine the active table's order in the hierarchy
$_SESSION[this_hierarchy] = array_search($_SESSION[table], $_SESSION[hierarchy]);
if ($_SESSION[this_hierarchy] == '') { $_SESSION[this_hierarchy] = 0; }
// Gather information about the parent table, if there is one
// This information will be used to create a breadcrumb
if ($_REQUEST[parent_id]) {
$_SESSION[parent_id] = $_REQUEST[parent_id];
$this_table = $_SESSION[table];
$_SESSION[parent_table] = $parent[$this_table];
$query = "SELECT `".esc($name_col)."` FROM `".esc($_SESSION[parent_table])."` WHERE id = '".esc
($_SESSION[parent_id])."'";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$_SESSION[parent_name] = $row[$name_col];
}
}
}
if ($_SESSION[this_hierarchy] == 0) {
$_SESSION[parent_id] = '';
$_SESSION[parent_name] = '';
}
if ($_REQUEST[id] && $_SESSION[this_hierarchy] > 0) {
$this_table = $_SESSION[table];
$_SESSION[parent_table] = $parent[$this_table];
$parent_table_id = $_SESSION[parent_table]."_id";
$query = "SELECT `".esc($parent_table_id)."` FROM `".esc($_SESSION[table])."` WHERE id = '".esc
($_REQUEST[id])."'";
$result = mysql_query($query) or die();
while ($row = mysql_fetch_array($result)) {
$_SESSION[parent_id] = $row[$parent_table_id];
}
$query = "SELECT `".esc($name_col)."` FROM `".esc($_SESSION[parent_table])."` WHERE id = '".esc
($_SESSION[parent_id])."'";
$result = mysql_query($query) or die();
while ($row = mysql_fetch_array($result)) {
$_SESSION[parent_name] = $row[$name_col];
}
}
if ($_SESSION[parent_id] && $_SESSION[this_hierarchy] > 0) {
$this_table = $_SESSION[table];
$parent_table = $parent[$this_table];
if ($_SESSION[this_hierarchy] > 1) {
$parent_parent_table = $parent[$parent_table];
$query = "SELECT `".esc($parent_parent_table)."`.`".esc($name_col)."` FROM `".esc($parent_ta
ble)."`, `".esc($parent_parent_table)."` WHERE `".esc($parent_table)."`.id = '".esc($_SESSION[pare
nt_id])."' AND `".esc($parent_parent_table)."`.id = `".esc($parent_table)."`.`".esc($parent_parent
_table)."_id`";
$result = mysql_query($query) or die();
while ($row = mysql_fetch_array($result)) {
$parent_parent_name = $row[$name_col];
}
}
$breadcrumb = '<a href="'.$self.'?table='.$parent_table.'&id='.$_SESSION[parent_id].'">&laquo;
Go back to '.$parent_parent_name.' '.$parent_table.'s</a>';
}
// Update or insert rows in the current table
if ($_REQUEST[action] == 'Update') {
$this_table = $_SESSION[table];

$update_vars = $_POST[$this_table];
foreach($update_vars as $index => $cols) {
$query = "UPDATE `".esc($_SESSION[table])."` SET ";
unset($set);
foreach($cols as $col_name => $val) {
$set[] = "`$col_name` = '".mysql_real_escape_string($val)."'";
}
$query .= implode(',', $set);
$query .= " WHERE id = '".esc($index)."'";
$result = mysql_query($query);
}
foreach ($_REQUEST['new'] as $index => $cols) {
$query = "INSERT INTO `".esc($_SESSION[table])."` SET ";
unset($set, $non_empty_set);
foreach($cols as $col_name => $val) {
$set[] = "`$col_name` = '".mysql_real_escape_string($val)."'";
if ($val != '') {
$non_empty_set = 1;
}
}
if ($non_empty_set == 1) {
$query .= implode(',', $set);
if ($_SESSION[this_hierarchy] > 0) {
$this_table = $_SESSION[table];
$this_parent = $parent[$this_table];
$query .= ', `'.esc($this_parent)."_id` = '".esc($_SESSION[parent_id])."'";
}
//echo $query;
$result = mysql_query($query) or die();
}
}
header("Location: admin.php");
}
// Delete a row in the current table
if ($_REQUEST[action] == 'delete') {
$del_table = $_REQUEST[table];
$del_id = $_REQUEST[id];
$query = "DELETE FROM `".esc($del_table)."` WHERE id = '".esc($del_id)."'";
$result = mysql_query($query);
header("Location: admin.php");
}
// Restrict the table query to only show rows that have the specified parent ID
if ($_SESSION[parent_id]) {
$parent_table = $_SESSION[table];
$where = ' WHERE `'.esc($parent[$parent_table])."_id` = '".esc($_SESSION[parent_id])."'";
}
// Begin constructing the table
$table = '<form action="" method=post>';
$table .= '<input type=hidden name=table value="'.$_SESSION[table].'">';
$table .= '<table class=table-list>';
// Determine the table fields
$query = "SHOW FIELDS FROM `".esc($_SESSION[table])."`";
$result = mysql_query($query) or die();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$field_name = $row[Field];
$field_table = $_SESSION[table];
$field[$field_table][$field_name] = $row[Type];
}
}
// Output the editable table field names as TH cells
$table .= '<tr>';
foreach($field[$field_table] as $col_name => $col_type) {
if ($col_name != 'id' && strpos($col_name, '_id') === FALSE) {
$table .= '<th>'.$col_name.'</th>';
}
}
$table .= '<th>actions</th></tr>';
// Get the rows from the table
$query = "SELECT * FROM `".esc($_SESSION[table])."` $where";
$result = mysql_query($query) or die();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$table .= '<tr>';
// Output an editable text box
foreach($field[$field_table] as $col_name => $col_type) {
if ($col_name != 'id' && strpos($col_name, '_id') === FALSE) {
$table .= '<td><input type=text size=15 name='.$_SESSION[table].'['.$row[id].']['.$col

_name.'] value="'.htmlspecialchars($row[$col_name]).'"></td>';
}
}
$table .= '<td><a href="'.$self.'?action=delete&table='.$_SESSION[table].'&id='.$row[id].'">
Delete</a>';
// Drill down to the children of this table
if ($_SESSION[this_hierarchy] != $_SESSION[hierarchy_count] - 1) {
$this_child = $_SESSION[this_hierarchy] + 1;
$query2 = "SELECT * FROM `".esc($_SESSION[hierarchy][$this_child])."` WHERE `".esc($_SESS
ION[table])."_id` = '".esc($row[id])."'";
$result2 = mysql_query($query2);
$table .= ' &nbsp;&#149;&nbsp; <a href="'.$self.'?table='.$_SESSION[hierarchy][$this_chil
d].'&parent_id='.$row[id].'">'.mysql_num_rows($result2).' '.$_SESSION[hierarchy][$this_child].'s (
view/add/edit)</a>';
}
$table .= '</td></tr>';
}
}
// Allow the user to enter new rows in this table
for ($i=0; $i<$num_new_rows; $i++) {
$table .= '<tr>';
foreach($field[$field_table] as $col_name => $col_type) {
if ($col_name != 'id' && strpos($col_name, '_id') === FALSE) {
$table .= '<td><input type=text size=15 name=new['.$i.']['.$col_name.']></td>';
}
}
$table .= '<td>&nbsp;</td></tr>';
}
// Update button
$table .= '</table><p><input type=submit name=action value="Update"></form>';
?>
<html>
<style>
a {
text-decoration:none;
color:#009;
}
.table-list th, td {
font-family:arial;
font-size:14px;
padding:2px 4px;
background-color:#EEE;
text-align:left;
}
input[type=text] {
border:0;
}
</style>
<body>
<h1><?=$_SESSION[parent_name]." ".$_SESSION[table];?>s</h1>
<p><?=$breadcrumb;?></p>
<?=$table;?>
</body>
</html>

User experience is about science, not art. Thats why consummate UX pros dont base design
decisions on intuition. Instead, they use data and feedback to improve the experience for
users of websites and applications.
They think independently, solve problems and arent afraid to advocate for their ideas,
according to Jen Romano Bergstrom, UX Project Leader for Arlington, Va., research firm Fors
Marsh Group. Shes also the Director of Marketing and Communications for the User
Experience Professionals Association.
Search user experience jobs here.
You can tell the difference between a guru and an average candidate right off the bat,
Bergstrom says. Average candidates provide vague answers to interview questions and
make decisions on feelings instead of facts. Real pros use an iterative process to improve the
user experience.
To explore a candidates traits and familiarity with popular UX research methods and tools,
Bergstrom asks these questions during interviews.
Describe your process for designing prototypes.

What Most People Say: I dont have a process. I go with my gut instinct. My
experience has taught me what users want and dont want.

What You Should Say: First, I utilize proven research techniques to solicit usercentered feedback. For instance, I might conduct a usability study, eye-tracking study,
field study or focus group to gather input. After reviewing the data, Ill create several
mock ups in the lab and continue testing and refining the prototypes until I achieve the
desired outcome or goal.

Why You Should Say It: UX isnt about you, its about the user. You need an iterative
process and an open mind to see things from another persons perspective.
What tools have you used to build prototypes? Do you have a favorite?

What Most People Say: Ive used several tools but I dont really have a preference.

What You Should Say: I consider the kind of prototype Im building, the cost,
timeframe, user experience and so forth when selecting a tool. My favorite software
programs are Azure and Justinmind Prototyper because they provide a comprehensive
solution for wireframing and protoyping. But I often use Solidify App or Filesquare to
create, test and gather insights from users when time and budgets are tight. I typically
use MockingBird or iPlotz when Im working with software applications.

Why You Should Say It: UX experts know how to select the right tool, according to
Bergstrom. They should know what works and what doesnt in a given situation by

weighing the cost, effectiveness, ease of use and the experience for users who provide
feedback, she says.
How do you incorporate usability into the design and testing process?

What Most People Say: We dont really worry about incorporating usability into the
website design and testing process at my company. If someone wants to test a site,
they come to me and I provide the data or plan a study.

What You Should Say: It depends on when Im brought into the process. If Im
involved from the outset, I conduct research and integrate UX throughout the design and
testing phases. If Im brought in later, Ill conduct two to four rounds of testing and
provide recommendations that offer the greatest return while being mindful of time and
budget issues.

Why You Should Say It: Ideally, UX is woven into every stage of an iterative design
and testing process. However, UXers are often brought in later. So real pros have the
ability to render fact-based opinions and improve the user experience from several entry
points.
How do you advocate for usability in your organization?

What Most People Say: I havent had to do that. People come to me when they need
something.

What You Should Say: I blog about UX and speak at conferences to demonstrate the
value of improving the user experience. To garner support from executives and
colleagues in my company, Ive taken the initiative to identify opportunities to improve
our existing applications and websites. Its easy for them to see the merits and financial
benefits because I validate my recommendations with facts.

Why You Should Say It: Identifying opportunities without being asked is the sign of a
real go-getter, observes Bergstrom. It shows the type of independent thinking that
separates the average performers from the UX rock stars.

You might also like