Things covered: Defining class. Creating Objects. Public and Private access of Properties/Data. Separating Class file and the application file.
What is a Class ? A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.
class is a keyword. Add is the name of the class we’ve assigned. $a and $b are two variables of class Add. These have private access specifier, meaning, they’re not accessible directly from outside the class. Public access specifier indicates that they can be accessed even outside the scope of a class. Private variables are treated as safe, so we prefer that.
Since private variables are accessed inside the class, we declared two methods inside the class Add. i.e., setValues() and add() setValues() has two parameters which are then assigned to the local variables $a and $b using the $this pointer.
$this pointer references to the object which is currently pointing to it.
add() method adds the user passed values and returns the result.
Here we include the add.php file and create an object of (class)type Add. Using this object we pass values to setValues(), and then call add() method, which returns the added value of the passed numbers. which is then output to the browser.
We could create as many objects as we wish and then pass and output as many results as required, without altering the class file what so ever, once finalized.
So this is the power of Object Oriented Programming. This way we could manage complex applications easily or in an organized/standard way. Increase code re-usability. Also reduce maintenance cost etc..
Why OOP in PHP ? Most web projects still use procedural i.e., function based software development approach. And honestly, it has no issue, because most web projects are so small scale and straight forward that they don’t require OOP in most cases.
But for complex application development, you need OOP for effectiveness. Like, if you want to build a home, you need a lot of planning, preparation and some standard approach to build it.
In Voting system we need to make sure, one person votes only once, to a particular poll. Or One person can only like a particular image once. Person who votes must be allowed to vote down and the person who likes must be allowed to unlike the same image / item etc.
Looks complicated? Relax, its not that complicated!
Let me explain the logic and direct you to some videos.. First, build your User Signup and Login forms. Make username as primary key.
Now another table with two fields again: username and id Make username and id as primary keys..that is, composite primary key.
In database design, a composite key is a key that consists of 2 or more attributes that uniquely identify an entity occurrence. Each attribute that makes up the compound key is a simple key in its own right.
This way, same user can not like / vote for the same image twice! It would throw error, as it violets composite key rule. You could make use of Die() and show appropriate message or still better use if else and if the query has not executed(due to violation of composite key rule) show links in the else part to vote down or unlike. There you could simply delete the entry from vote table.
Video Tutorial: Build VOTE / LIKE, UNLIKE Feature: PHP & MySQL
Take 3 tables: user, image and vote username is primary key in user table. id is primary key in image table. attributes: id and image id and username are composite primary key in vote table.
Vote / Like, Unlike
1
mysql> INSERT INTO vote VALUES( ‘2’, ’apple’ );
mysql> INSERT INTO vote VALUES( ‘2’, ’apple’ );
Count Vote / Like
1
mysql> SELECT count(*) FROM vote WHERE id= ‘2’;
mysql> SELECT count(*) FROM vote WHERE id= ‘2’;
Vote down / Unlike
1
mysql> DELETE FROM vote WHERE( id=‘2’ AND username=’apple’ );
mysql> DELETE FROM vote WHERE( id=‘2’ AND username=’apple’ );
Make sure to take the values of id and username dynamically. Am showing 2 and apple for the sake of illustration. username will be present inside the session variable once the user logs in. id value will be associated with the like or vote link/button of the image. [id is unique to each individual image]
Taking advantage of the error thrown by the composite primary key. i.e., using if else we check if the user has already voted or liked particular image or participated in a particular poll, if yes, we show him/her unlike or vote down link/button.
Vote, Vote Down or Like, Unlike Feature
1
2
3
4
If( mysql_query(“INSERT INTO vote VALUES( ‘2’, ’apple’ )”) )
echo “Thanks for the vote”;
else
echo “<a href=‘vote.php?down=1’>Vote Down</a>”;
If( mysql_query(“INSERT INTO vote VALUES( ‘2’, ’apple’ )”) ) echo “Thanks for the vote”;else echo “<a href=‘vote.php?down=1’>Vote Down</a>”;
You could mix this simple logic with some CSS and other stuffs like AJAX and implement the voting system easily in a short period of time, like a pro!
These are the entries in our table apple: 1Google USA 2Apple USA 3Microsoft USA 4Oracle USA 10IBM 11HP 12Symantec 13Adobe 14Cisco 15McAfee 16Red Hat 17Sun Microsystems 18Intel 19Salesforce 20Facebook 21Technotip 22MindTree 23Tate Consultancy Ser 24Cognizant 25Citigroup 26Maestro 27Visa 28KingFisher 29HDFC 30ICICI 31SBI 32SBM 33Twitter 34LinkedIn 35BlueDart 36VRL 37Zappos 38FlipKart 39Amazon 40Yahoo! 41ebay 42PayPal
We would split these entries into 5 segments each and display 5 records at a time.
In this video tutorial we’re showing the latest entry first. If you want to show first entry first, then take another database field called date and insert the date and time of the insertion operation. Now using the WHERE clause and LIMIT fetch the data from database and display as you wish.
WHERE clause and LIMIT, to fetch depending on date and time mysql query
1
mysql> SELECT * from apple [ WHERE some_condition ] ORDER BY date ASC LIMIT $start, 5;
mysql> SELECT * from apple [ WHERE some_condition ] ORDER BY date ASC LIMIT $start, 5;
1
mysql> SELECT * from apple [ WHERE some_condition ] ORDER BY date DESC LIMIT $start, 5;
mysql> SELECT * from apple [ WHERE some_condition ] ORDER BY date DESC LIMIT $start, 5;
$rs = mysql_query("SELECT count(*) FROM apple");
$rw = mysql_fetch_array($rs);
if( !(isset($_GET['page'])) )
$start = $rw[0] - 5;
else
$start = $rw[0] - ($_GET['page'] * 5);
$res = mysql_query("SELECT * FROM apple LIMIT $start, 5")
or Die("More entries coming, stay tuned!");
$rs = mysql_query("SELECT count(*) FROM apple");
$rw = mysql_fetch_array($rs);
if( !(isset($_GET['page'])) ) $start = $rw[0] - 5;
else $start = $rw[0] - ($_GET['page'] * 5);
$res = mysql_query("SELECT * FROM apple LIMIT $start, 5") or Die("More entries coming, stay tuned!");
First we need to calculate the number of records present inside the table. Next decide onto how many items you want to display. Based on this, subtract the actual number of records with number of items you actually want to display.
If use explicitly passes $_GET[‘page’] i.e., by clicking on the navigation or pagination numbers, then multiply the number with the number of items you want to display and subtract it with the actual number of records present inside the table.
The final step is to, pass the $start and the number till which you want to fetch from $start.
In our case, we want to show 5 items from the table apple, so we give the limit: starting from $start to 5 records after $start.
Video Tutorial: Simple / Basic Pagination / Navigation: PHP & MySQL
< ?php
include_once('db.php');
if( isset($_GET['del']) )
{
$id = $_GET['del'];
$sql= "DELETE FROM apple WHERE id='$id'";
$res= mysql_query($sql) or die("Failed".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=index.php'>";
}
?>
< ?php
include_once('db.php');
if( isset($_GET['del']) )
{
$id = $_GET['del'];
$sql= "DELETE FROM apple WHERE id='$id'";
$res= mysql_query($sql) or die("Failed".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=index.php'>";
}
?>
Here we receive the value of id, passed from index.php and assign it to a local variable called $id. Then using simple DELETE query, we delete the records associated with the id.
Video Tutorial: Delete / Remove Records In Database Table: PHP & MySQL
mysql> UPDATE apple SETname='newName'WHERE id='session_id';
mysql> UPDATE apple SET name='newName' WHERE id='session_id';
Security Issue: Make sure not to allow people to explicitly pass random id’s and retrieve and edit/update other’s data. To solve this issue, you can save the id of the logged in user in a session variable and instead of passing id to edit.php we can directly use the id stored in our session variable. This would solve the issue.