What is class and functions in PHP script or object oriented programming

What is Class in Programming ?

A class is a collection of variables and functions working with these variables. Variables are defined by var and functions are defined by function. It is an object oriented programming.

Define a class

Define a class using a keyword class

Syntax

class className

{

}

Example

class myfirstprogram

{

}

Note: Here myfirstprogram is a class name

Functions

Functions are defined inside the class, which is used to access the object data.

Define a function

Define a function using the keyword function

Syntax

function functionName()

{
  
}

Example

function factorial()

{

}

Note: factorial is a function name

Sample code to find factorial of the given number

//fact.php

<?php
class fact
{
public $num=null;
public $fact1=null;
public $objRes=null;

function getValue()
{
$this->num=$_REQUEST[‘num’];
}

function factorial()
{
if(isset($_REQUEST[‘submit’]))
{
$this->getValue();
$fact1=1;
for ($i=$this->num; $i>=1; $i–) {
$fact1 = $fact1 * $i;
$this->objRes=$fact1;
}
}
}
}
$objFact=new fact();
$objFact->factorial();

?>
<html>
<body>
<form action=”fact.php” method=”post”>
Enter the number<input type=”text” name=”num”/>
<input type=”submit” name=”submit”/>
</form>
<?php
echo “Factorial of $objFact->num is $objFact->objRes”;
?>
</body>
</html>

output

fact

essential and important JavaScript functions required in website

These are the following important java script functions used in a website. Please note that  you may use jquery for all functions

Progressive pop ups for Social networking

<script>
// create social networking pop-ups
(function() {
// link selector and pop-up window size
    var Config = {
                Link: "a.share",
		Width: 500,
		Height: 500
	};

// add handler links
	var slink = document.querySelectorAll(Config.Link);
	for (var a = 0; a < slink.length; a++) {
		slink[a].onclick = PopupHandler;
	}

	// create popup
	function PopupHandler(e) {

		e = (e ? e : window.event);
		var t = (e.target ? e.target : e.srcElement);

		// popup position
		var px = Math.floor(((screen.availWidth || 1024) - Config.Width) / 2),
		py = Math.floor(((screen.availHeight || 700) - Config.Height) / 2);

		// open popup
		var popup = window.open(t.href, "social", 
			"width="+Config.Width+",height="+Config.Height+
			",left="+px+",top="+py+
			",location=0,menubar=0,toolbar=0,status=0,scrollbars=1,resizable=1");
		if (popup) {
			popup.focus();
			if (e.preventDefault) e.preventDefault();
			e.returnValue = false;
		}

		return !!popup;
	}

}());
</script>

Image slider with thumbnail navigator
<script src="jssor.slider.min.js"></script>
<script>
    jssor_slider1_starter = function (containerId) {
        var options = {
            $ThumbnailNavigatorOptions: {
                $Class: $JssorThumbnailNavigator$,
                $ChanceToShow: 2
            }
        };
        var jssor_slider1 = new $JssorSlider$(containerId, options);
    };
</script>
Bootstrap DateTime picker

<script type="text/javascript">
 $(function() 
{ 
$('#datetimepicker1').datetimepicker({ language: 'pt-BR' }); 
});
 </script>

ScrollTop in javascript

 <script type="text/javascript">
        function OnScrollDiv (div) {
            var info = document.getElementById ("info");
            info.innerHTML = "Horizontal: " + div.scrollLeft
                            + "px<br/>Vertical: " + div.scrollTop + "px";
        }
    </script>

 Using JsFiddle

$(document).ready(function () {

 $(window).scroll(function () {
 if ($(this).scrollTop() > 100) {
 $('.scrollup').fadeIn();
 } else {
 $('.scrollup').fadeOut();
 }
 });

 $('.scrollup').click(function () {
 $("html, body").animate({
 scrollTop: 0
 }, 600);
 return false;
 });

});

//css for jSFiddle

.scrollup {
 width: 40px;
 height: 40px;
 position: fixed;
 bottom: 50px;
 right: 100px;
 display: none;
 text-indent: -9999px;
 background: url('icon_top.png') no-repeat;
 background-color: #000;
}
Blinking Text

<script language=”javascript”>

setInterval(blinktext, 500);

var txt = “”;

var count = 0;

function blinktext() {

var cntrl = document.getElementById(“txtblinkingtext”);

if (count == 0)

txt = cntrl.value;

if (count % 2 == 0)

cntrl.value = “”;

else

cntrl.value = txt;

count++;

}

</script>

Pagination in javascript

function Pager(tableName, itemsPerPage) {
    this.tableName = tableName;
    this.itemsPerPage = itemsPerPage;
    this.currentPage = 1;
    this.pages = 0;
    this.inited = false;
 
    this.showRecords = function(from, to) {        
        var rows = document.getElementById(tableName).rows;
        // i starts from 1 to skip table header row
        for (var i = 1; i < rows.length; i++) {
            if (i < from || i > to)  
                rows[i].style.display = 'none';
            else
                rows[i].style.display = '';
        }
    }
 
    this.showPage = function(pageNumber) {
    	if (! this.inited) {
    		alert("not inited");
    		return;
    	}
 
        var oldPageAnchor = document.getElementById('pg'+this.currentPage);
        oldPageAnchor.className = 'pg-normal';
 
        this.currentPage = pageNumber;
        var newPageAnchor = document.getElementById('pg'+this.currentPage);
        newPageAnchor.className = 'pg-selected';
 
        var from = (pageNumber - 1) * itemsPerPage + 1;
        var to = from + itemsPerPage - 1;
        this.showRecords(from, to);
    }   
 
    this.prev = function() {
        if (this.currentPage > 1)
            this.showPage(this.currentPage - 1);
    }
 
    this.next = function() {
        if (this.currentPage < this.pages) {
            this.showPage(this.currentPage + 1);
        }
    }                        
 
    this.init = function() {
        var rows = document.getElementById(tableName).rows;
        var records = (rows.length - 1); 
        this.pages = Math.ceil(records / itemsPerPage);
        this.inited = true;
    }
 
    this.showPageNav = function(pagerName, positionId) {
    	if (! this.inited) {
    		alert("not inited");
    		return;
    	}
    	var element = document.getElementById(positionId);
 
    	var pagerHtml = '<span onclick="' + pagerName + '.prev();" class="pg-normal"> &#171  </span> Blogroll';
        for (var page = 1; page <= this.pages; page++) 
            pagerHtml += '<span id="pg' + page + '" class="pg-normal" onclick="' + pagerName + '.showPage(' + page + ');"></span>  ';
        pagerHtml += '<span onclick="'+pagerName+'.next();" class="pg-normal">  »</span>';            
 
        element.innerHTML = pagerHtml;
    }
}
 

important MYSQL syntaxes or query in php program

mysql

SQL QUERY

SQL stands  for Structured Query Language, it is used for accessing and manipulating  databases.

Using SQL one can perform more actions in a database.Such as insert, update, select and delete a records from the database.

Essential SQL queries

1. To create a database in mysql 

Create database is used to create the database.

Syntax

CREATE DATABASE database_name;

Example

CREATE DATABASE first_db;

2. To create a table in mysql 

Create table is used to create a table in a database

Syntax

CREATE TABLE table_name(

columnName1 datatype(size),

columnName2 datatype(size)

);

Note:

  • column_name parameter specifies the name of the column.
  • datatype parameter specifies different types of data type(i.e., varchar, int, enum, date, etc).
  • size parameter specifies the maximum length of the column.

Example

CREATE TABLE tbl_user(

id int NOT NULL,

username varchar(20),

age int(3),

place varchar(30),

PRIMARY KEY(id)

);

Here id is a primary key, so it increments id by 1

3. To insert a record in a table

Insert query is used to insert a new record in a table.

Syntax

There are two ways to insert a record into the database.

First way, is to insert a data by specifying both the column name and values in a query.

INSERT INTO table_name (columnName1, columnName2) VALUES (value1,value2,value3);

Second way,not specifying a column name but only specifying the values.

INSERT INTO table_name VALUES(value1,value2,value3);

In both way, we can insert the records in a table.

Example

To insert a username, age and place, use the sql insert query.

INSERT INTO tbl_user (username,age,place) VALUES  (‘joe’, ’23’, ‘chennai’);

INSERT INTO tbl_user VALUES  (‘joe’, ’23’, ‘chennai’);

4. To update/Edit a record in a database

Update query is used to update the existing records in a table.

Syntax

UPDATE table_name SET column1=value1, column2=value2 WHERE some_column=some_value;

Example

UPDATE tbl_login SET username=’John’ age=’24’ where place=’chennai’;

Note: WHERE clause is used to identify which record should be update. If we omit the WHERE clause, all the records will be updated.

5. To select the records from the database

Select query is used to select the records from the table.

Syntax

Two ways to select the record.One is to select the specified column and another one is to select all the records from the table.

SELECT columnName1, columnName2 FROM table_name;

SELECT * FROM table_name;

Example

SELECT username, age from tbl_user;

SELECT * from tbl_user;

6. Delete a record 

Delete query is used to delete a rows from the table.

Syntax

DELETE FROM table_name WHERE some_column=some_value;

Another way to delete a rows from the table

DELETE * FROM table_name; (0r) DELETE FROM table_name;

Example

DELETE FROM tbl_user where username=”john”;

DELETE * FROM tbl_user; (0r) DELETE FROM tbl_user;

It deletes entire rows in the table.

7.  Using Where clause in SQL

WHERE clause is used to extract only those records which satisfy the condition.

Syntax

SELECT columnName1, columnName2 from table_name WHERE some_column operator some_value;

Example

SELECT username,age from tbl_user  WHERE place=”chennai”;

Note:Operators you may use  >, <, >=, <=, <>, BETWEEN, LIKE, IN

SELECT * FROM tbl_user WHERE age>=23;

8. Alter table 

Alter table statement is used to add,  modify column in an existing table

Syntax

To add a column name in a table, use the following syntax

ALTER TABLE table_name ADD column_name data_type;

To change the data type of a column

ALTER TABLE table_name MODIFY COLUMN column_name data_type;

Example

ALTER TABLE tbl_user ADD phone bigint(11);

9. Truncate Table

Truncate table is used to delete the data inside the table.

Syntax

TRUNCATE TABLE table_name;

Example

TRUNCATE TABLE tbl_user;

10. Drop Table

Drop table statement is used to delete a table.

Syntax   

DROP TABLE table_name;

Example

DROP TABLE tbl_user;

 

What is session in php, how to start and stop session

phpimg

Session in PHP

Session is a way to store the user information(in variables) to be used across multiple pages.

For example, When we work with an application, we may open it, do some modification and we close it. This is what a session is.The computer may know who you are, and when you start and end the application. But in internet there was a problem in web server , it doesn’t know who you are and what you do.Because of the HTTP, it doesn’t maintain the state information.

Session variable solve this problem by storing user information.Session variable starts once the user open the application and its last until the user close the browser. Hence, session variable holds the information about a single user, and maintain through out the application.

Start the session

To start a session variable, use session_start() function.

Session variables are set with PHP global variable $_SESSION

Here is a code to start a session with session variable

<?php
session_start();
?>
<html>
<body>
<?php
//to set a session variable
$_SESSION[“msg”]=”Working with session”;
echo “Session started”;
?>
</body>
</html>

Stop the session

To stop a session variable, use session_unset() and session_destroy() functions.

  • session_unset is used to remove all session variables.
  • session_destroy is used to destroy the session.

Here is a code to remove the session variable and destroy the session

<?php
session_start();
?>
<html>
<body>
<?php
session_unset();
session_destroy();
?>
</body>
</html>

PHP script to find Highest, lowest, count and average numbers in array

phpimg

To find a highest, lowest, count and average numbers in an array

Here, we find the sample php programs to find the find he highest number in an array, similarly lowest number in an array, count of the numbers in an array and average of the numbers in an array.

<?php
$array=array(‘1′,’2′,’3′,’4’);
echo “Given array <br/>”;
$arrlength = count($array);

for($x = 0; $x < $arrlength; $x++) {
echo $array[$x];
echo “<br>”;
}echo “Highest number in an array<br/>”;
echo max($array);
echo “<br/>”;
echo “Lowest number in an array<br/>”;
echo min($array);
echo “<br/>”;
echo “Count of an array<br/>”;
echo $arrlength;
echo “<br/>”;
echo “Average of number for an array<br/>”;
$avg=array_sum($array)/count($array);
echo $avg;

?>

output

Given array
1
2
3
4
Highest number in an array
4
Lowest number in an array
1
Count of an array
4
Average of number for an array
2.5

PHP script for sample contact page for website

phpimg

Contact page for website

<?php
include(‘config.inc.php’);

class ContactUs
{
var $arrErrors = array();
var $strSuccess = ”;
public $strSelect=null;
public $objResult=null;
var $objConfig = null;
var $objDbConn=null;
var $intRandSiteLimit = 35;
var $arrRandSites = array();
var $strName = ”;
var $strPhone = null;
var $strEmail = ”;
var $strContent = ”;
var $strReferrer = null;

function __construct()
{
$this->objConfig = new Config();
}

function processReq()
{
$blnMagicQuotesOn = get_magic_quotes_gpc();
if (isset($_REQUEST[‘contact_name’])) {
$this->strName = trim($_REQUEST[‘contact_name’]);
if ($blnMagicQuotesOn) {
$this->strName = stripslashes($this->strName);
}
}
if (isset($_REQUEST[‘contact_email’])) {
$this->strEmail = trim($_REQUEST[‘contact_email’]);
if ($blnMagicQuotesOn) {
$this->strEmail = stripslashes($this->strEmail);
}
}
if (isset($_REQUEST[‘contact_phn’])) {
$this->strPhone = trim($_REQUEST[‘contact_phn’]);
if ($blnMagicQuotesOn) {
$this->strPhone = stripslashes($this->strPhone);
}
}
if (isset($_REQUEST[‘contact_message’])) {
$this->strContent = trim($_REQUEST[‘contact_message’]);
if ($blnMagicQuotesOn) {
$this->strContent = stripslashes($this->strContent);
}
}
}

function validateReq()
{
$blnSuccess = true;

if ($this->strName == ”) {
$this->arrErrors[‘name’] = ‘Name can\’t be empty’;
$blnSuccess = false;
}
if ($this->strEmail == ”) {
$this->arrErrors[’email’] = ‘Email address can\’t be empty’;
$blnSuccess = false;
}else if (!preg_match(‘/^[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i’, $this->strEmail)) {
$this->arrErrors[’email’] = ‘Email address is invalid’;
$blnSuccess = false;
}
if ($this->strContent == ”) {
$this->arrErrors[‘message’] = ‘Message can\’t be empty’;
$blnSuccess = false;
}
return $blnSuccess;
}

function clearFields()
{
$this->strName = ”;
$this->strEmail = ”;
$this->strContent = ”;
$this->strPhone = null;
}

function __destruct()
{
unset($this->objConfig);
}

function closeDbConnection()
{
mysql_close($this->objDbConn);
}

function run()
{
$this->objConfig = new Config();
$this->objDbConn = mysql_connect($this->objConfig->dbHostname, $this->objConfig->dbUsername, $this->objConfig->dbPassword);
mysql_select_db($this->objConfig->dbName);

$strCurrentTime = date(“y-m-d h:i:s”,time());
$strIP = $_SERVER[‘REMOTE_ADDR’];

if(isset($_REQUEST[‘submitted’])) {

$this->processReq();
if ($this->validateReq())
{
$strSelect = “INSERT into `contact_db` (`name`,`phone`,`email`,`message`,`date`,`ip`) VALUES (‘$this->strName’,’$this->strPhone’,’$this->strEmail’,’$this->strContent’,’$strCurrentTime’,’$strIP’)”;
$objResult = mysql_query($strSelect,$this->objDbConn);

if(!mysql_affected_rows()<= 0 )
{
$this->strSuccess=’We have received your message.. Thank you!<br />’;
}
else {
$this->arrErrors[‘failed’]=’Some errors occured. Please try again!’;
}
$this->clearFields();
}
}
else {
}
$this->closeDbConnection();
}
}
$ins = new ContactUs();
$ins->run();
?>
<h3>Contact / Feedback Page</h3>
<?php
if(is_array($ins->arrErrors) && !empty($ins->arrErrors)) {
foreach($ins->arrErrors as $key=>$val) {
echo (“<div style=’color: #FF0000;’>”. $val . “</div>”);
}
} elseif ( $ins->strSuccess != “” ) {
echo (“<div style=’color: #0000FF;’>”. $ins->strSuccess . “</div>”);
}
?>
<form action=”contact.php” method=”post”>
<input type=”hidden” name=”action” value=”post” />
<p><br />
<label for=”contact_name”>Name * <span class=”required”></span></label>
<input type=”text” id=”contact_name” name=”contact_name” value=”<?php echo $ins->strName; ?>” size=”20″ tabindex=”1″/>
</p>

<p>
<label for=”contact_email”>Email * <span class=”required”></span></label>
<input type=”text” id=”contact_email” name=”contact_email” value=”<?php echo $ins->strEmail; ?>” size=”20″ tabindex=”1″/>
</p>
<p>
<label for=”contact_phn”>Phone Number – Optional <span></label>
<input type=”text” id=”contact_phn” name=”contact_phn” value=”<?php echo $ins->strPhone; ?>” size=”20″ tabindex=”1″/>
</p>

Your Message *
<p>
<label for=”contact_message”><span class=”required”></span></label>
<textarea name=”contact_message” id=”contact_message” cols=65 rows=10 tabindex=”2″><?php echo $ins->strContent; ?></textarea>
</p>
<p class=”buttons”>
<input name=”submitted” id=”submitted” value=”true” type=”hidden”>
<button name=”submit” type=”submit” id=”submit” class=”button” tabindex=”5″>Send Email</button>
</p>
</form>
</p>
</div>
<?php
$ins->closeDbConnection();
?>
</body>
</html>

 

How to create user login, forgot password and logout page using php script

phpimg

To create a login page in php

Note: Create a table tbl_login with uname and pwd
//config.inc.php

<?php
class Config {
public $dbHostname = ‘localhost’;
public $dbUsername = ‘root’;
public $dbPassword = ‘xxx’;
public $dbName = ‘dbname’;
}

?>

//index.php

<?php
session_start();
include(“config.inc.php”);
class Login
{
public $strUsername = null;
private $strPassword = null;
public $arrErrors = array();
private $objConfig = null;
private $objDbConn = null;

function __construct()
{
$this->objConfig = new Config();
}

function processRequest()
{
$this->strUsername = trim($_POST[“uname”]);
$this->strPassword = trim($_POST[“pwd”]);
}

function validateRequest()
{
$blnValidationSuccess = true;
if($this->strUsername == “”) {
$this->arrErrors[“uname”] = “Username is required”;
$blnValidationSuccess = false;
}

if($this->strPassword == “”) {
$this->arrErrors[“pwd”] = “Password is required”;
$blnValidationSuccess = false;
}
if($blnValidationSuccess) {
$objResult = mysql_query(“select * from tbl_login where uname='” . $this->strUsername . “‘ and pwd = ‘” . $this->strPassword . “‘ ” ,$this->objDbConn);
if(mysql_num_rows($objResult)<=0) {
$this->arrErrors[‘usernameorpassword’] = “Username or Password is wrong”;
$blnValidationSuccess = false;
}
}
return $blnValidationSuccess;
}

function closeDbConnection()
{
mysql_close($this->objDbConn);
}

function run()
{
if(isset($_POST[“issubmit”])) {
$this->processRequest();
$this->validateRequest();
//connect to db
$this->objDbConn = mysql_connect($this->objConfig->dbHostname, $this->objConfig->dbUsername, $this->objConfig->dbPassword);
mysql_select_db($this->objConfig->dbName);
$this->closeDbConnection();
}
}
}
$objLogin = new Login();
$objLogin->run();
?>
<html>
<head>
<title> Login Page</title>
</head>
<body>
<div>
<div>
<form action=”index.php” method=”post”>
<input type=”hidden” name=”issubmit” value=”true” />
<?php
if(isset($objLogin->arrErrors[‘usernameorpassword’])) {
echo “<div style=’color: #FF0000′>”. $objLogin->arrErrors[‘usernameorpassword’] . “</div>”;
}
?>
User Name<input type=”text” name=”uname” value=”<?php echo $objLogin->strUsername; ?>” />
<?php
if(isset($objLogin->arrErrors[‘uname’])) {
echo “<div style=’color: #FF0000′>”. $objLogin->arrErrors[‘uname’] . “</div>”;
}
?>
<br/>
Password <input type=”password” name=”pwd” value=”” />
<?php
if(isset($objLogin->arrErrors[‘pwd’])) {
echo “<div style=’color: #FF0000′>”. $objLogin->arrErrors[‘pwd’] . “</div>”;
}
?>
<br />
<input type=”submit” name=”submit” value=”submit” />
</form>
</div>
</body>
</html>

To create a logout page in php

//logout.php

<?php
session_start();
session_destroy();
?>
<html>
<title>Logout</title>
<body>
<h3> You are successfully Logged out</h3>
<a href=’index.php’> CLICK HERE TO LOGIN AGAIN </a>
</body>
</html>