Archive for the ‘php’ Category


theme coding

Friday, April 18th, 2008

<html>
<head>
<title><?php page_content_element(”title”);?>
</title>
<link rel=”stylesheet” type=”text/css” href=”mystyle.css” />

</head>
<body>
<table>
<tr><td></td><td align=”center”><?php
theme_include($frame_inclusion_filedata[top]);
?></td></tr>
<tr><td valign=”top”><?php
theme_include($frame_inclusion_filedata[left]);
theme_boxes(”left”);
?></td><td valign=”top”>
<?php
page_content_element(”heading”);
page_content(”top”);
theme_include($frame_inclusion_filedata[middle]);

page_content(”bottom”);
?>
</td></tr>
<tr><td colspan=”2″ align=”center”><?php
theme_include($frame_inclusion_filedata[bottom]);
?></td></tr>
</table>
</body>
</html>


message display based on parameter receieved from $_GET

Friday, April 18th, 2008

<?
$locale=array(
“MORE”=>”more…”,
“ADDED_SUCCESSFULLY”=>”Record added successfully”,
“Add_1″=>”Record added successfully”,
“Add_0″=>”Operation failed”,
“Edit_1″=>”Record updated successfully”,
“Edit_0″=>”Record failed to update”,
“EditPassword_1″=>”Password updated successfully”,
“EditPassword_0″=>”Password failed to update”,
“Exist_1″=>”User already exist”
);
while(list($key,$value)=each($locale))
{
define($key,$value);
}

function message($one,$two){
global $locale;
if(array_key_exists($one.”_”.$two,$locale))
return $locale[$one.”_”.$two];
}
?>


config file having path setting, db setting and file inclusions

Friday, April 18th, 2008

<?php
// start session for login to work
session_start();
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set(”display_errors”,”On”);
global $winos,$path,$siteurl,$sitepath,$basepath,$module_path;
$winos=0;
if($winos)
{
$path_separator=”\\”;
}
else
{$path_separator=”/”;

}
$path=array();
$basepath=”/var/www/vhosts/tweb.com/subdomains/teamboard/httpdocs”;

///////////  general path cofing and url config ///////////

$path[’path_to_program’] = “http://”.$_SERVER[’HTTP_HOST’];
$path[’fs_path_to_program’] = $basepath;    //the filesystem path to the program www server
$path[”docrootpath”]= $basepath;
$path[”http_url”]= “http://”. $_SERVER[’HTTP_HOST’];
$path[”sitepath”]= “”;  //required if site runs with deeper dir structure from document root
$path[”imagepath”]= $path_separator.”images”;
$path[”includepath”]= “/include”;
$path[”adminpath”]= $path_separator.”admin”; 

while(list($key,$value)=each($path))
{
define($key,$value);
}
$siteurl= $path[http_url] . $path[sitepath];
$sitepath=$path[docrootpath] . $path[sitepath];

//configuring module paths

$module_path=array(”member”=>$path_separator.”member”.$path_separator);

////////////////////////////////////////////////////
/***** Start Database Stuff *****/

global $db_host,$db_user,$db_pass,$db_name,$db_type,$dbobj;

$db_host = “localhost”;//”localhost”;
$db_user = “username”;
$db_pass = “password”;
$db_name = “teamboard”;
$db_type = “mysql”;
$path[’db_prefix’]=”teamboard”;
require_once($path[’fs_path_to_program’].$path[”includepath”].$path_separator.”db-master-data.php”);
$dbobj=new dbserver();
$con =  $dbobj->connectdb($db_host, $db_user,$db_pass,$db_name);
/****** End Database Stuff ******/
//load required files//////////////////////////////
require_once($path[’fs_path_to_program’].$path[”includepath”].$path_separator.”check_magicquotes.php”);
require_once($path[’fs_path_to_program’].$path[”includepath”].$path_separator.”db.”.$db_type.”.php”);
require_once($path[’fs_path_to_program’].$path[”includepath”].$path_separator.”models.php”);
require_once($path[’fs_path_to_program’].$path[”includepath”].$path_separator.”prepare_data.php”);
require_once($path[’fs_path_to_program’].$path[”includepath”].$path_separator.”module_operation.php”);
require_once($path[’fs_path_to_program’].$path[”includepath”].$path_separator.”general_functions.php”);
require_once($path[’fs_path_to_program’].$path[”includepath”].$path_separator.”login_functions.php”);
require_once($path[’fs_path_to_program’].$path[”includepath”].$path_separator.”locale_en.php”);
require_once($path[’fs_path_to_program’].$path[”includepath”].$path_separator.”teamboard_functions.php”);

?>


working with database using data model and master model

Friday, April 18th, 2008

1) db-master-data.php

<?
class master{
var $name=”";
function Add($datamodelname,$data_array,$userlevel,$explicit_table_name=”") {
//this datamodelname is without suffix “_data”
 $dbserverobj=new dbserver();
   $insert_query=$dbserverobj->model_insertquery($datamodelname,$data_array); 
   $result=$dbserverobj->insert_query($datamodelname,$insert_query,$explicit_table_name);
      
   return $result;
 }
 function Edit($datamodelname,$data_array,$userlevel,$where_string,$explicit_table_name=”") {
//this datamodelname is without suffix “_data”

   $dbserverobj=new dbserver();   
   $update_query=$dbserverobj->model_updatequery($datamodelname,$data_array);
   $dbserverobj->update_query($datamodelname,$update_query,$where_string,$explicit_table_name);
   return 1;
 }
}
class data{
var $fields;
var $datatype;

function get_fields()
{
return $this->fields;
}
function get_datatype(){
  return $this->datatype;
 }
function get_fieldtype($key){
 if (array_key_exists($key,$this->datatype)){
  return $this->datatype[$key];
  }
 }
}
class dbserver{

var $host;
var $username;
var $password;
var $db;
var $tablename;
var $resultset;
var $dbvar_array =array(’host’=>”",’username’=>”",’password’=>”",’db’=>”",’tablename’=>”",’resultset’=>”");
function set($key,$value){

 if (array_key_exists($key,$this->dbvar_array)){

  $this->dbvar_array[$key]=$value;
  }
 } 
function get($key){
 if (array_key_exists($key,$this->dbvar_array)){
  return $this->dbvar_array[$key];
  }
 }
 function datamodel_fields($datamodelname)
 {
 $datamodel=$datamodelname.”_data”;
 $datamodelobj=new $datamodel();
 return $datamodelobj->get_fields();
 }
 function model_insertquery($datamodel,$data_array)
 {
 $datamodel=$datamodel.”_data”;
 $modelobj=new $datamodel();
 if (is_array($data_array)){
 
  $Field=”;
  $FieldValue=”;
  $i=-1;
  foreach($data_array as $Key=>$Value){
   $i++;
   if(!get_magic_quotes_gpc()){
     if($i>0){
     $Value=addslashes($Value); //no need to add slash for id field which is pk as it is ” while adding to avoid \’\’ to go into id field which is int and pk
     }
    }
    $Field.= $Key.”,”;
    if(array_key_exists($Key,$modelobj->get_datatype())){ 
     $Type=$modelobj->get_fieldtype($Key);
     switch ($Type) {
      case “int”:       
      case “float”:
        $FieldValue.=$Value.”,”;
        break;
      case “string”:       
      case “date”:
        $FieldValue.=”‘”.$Value.”‘,”;
        break;
     
      }
     
     }
    }
  
   }
  return “(”.substr($Field,0,-1).”)values(”.substr($FieldValue,0,-1).”)”;
 }
 
function model_updatequery($datamodel,$data_array){
 
// print_r($datamodel);
// print_r($data_array); 
 $datamodel=$datamodel.”_data”;
 $modelobj=new $datamodel();
 //print_r($modelobj);
 if (is_array($data_array)){
  $Field=”;
  $FieldValue=”;
  
  foreach($data_array as $Key=>$Value){
   if(!get_magic_quotes_gpc()){
     $Value=addslashes($Value);
    }
    $Field.= $Key.”,”;
    if(array_key_exists($Key,$modelobj->get_datatype())){ 
     $Type=$modelobj->get_fieldtype($Key);
     switch ($Type) {
      case “int”:       
      case “float”:
        $FieldValue=$Value.”,”;
        break;
      case “string”:       
      case “date”:
        $FieldValue=”‘”.$Value.”‘,”;
        break;
     
      }
     
     }
     if(isset($Value) &&  !empty($Value)){
     $StrUpdate.= $Key .”=”. $FieldValue;
     }
   }
   //echo “<br>”.substr($StrUpdate,0,-1);
   return substr($StrUpdate,0,-1);
 }
 }
 

function connectdb($host,$username,$password,$db){
 $this->set(”host”,$host);
 $this->set(”username”,$username);
 $this->set(”password”,$password);
 $this->set(”db”,$db);
 //print_r($this->dbvar_array);
 $link = mysql_connect($this->get(”host”), $this->get(”username”), $this->get(”password”))  or die( mysql_error());
  
   if (!$link) {
        die(’Not connected : ‘ . mysql_error());
   } 
   $db_selected = mysql_select_db($this->get(”db”), $link);
   if (!$db_selected) {
         die (’Can\’t use foo : ‘ . mysql_error());
      }
      return  $link;

 }
function   query ($query){
//echo $query;
//exit;
  $result= mysql_query($query) or die(mysql_error());
 $rowsaffected=mysql_affected_rows();
 $queryresult[’count’]=0;
 if($result==1){ //insert case
 $queryresult[’count’]=$result;
 }
 else{
   if(mysql_num_rows($result)) //select case
   {
   $count=mysql_num_rows($result);  
   if($count)
   {  
  // echo “count is “. $count;
   $queryresult[’count’]=$count;
   } 
   }
 else{
  if(strtolower(substr(trim($query),0,6))==”select”)
  {
  $queryresult[’count’]=0;//check dupluicte username exists select qurey didnt bring any result
  }
  else{
  $queryresult[’count’]=1; //update didt caused any change to any field
  }
 $queryresult[’resultset’]=1;//update didt caused any change to any field
 }   
 }  
 $queryresult[’resultset’]=$result;

return $queryresult;
}

function insert_query($datamodelname,$insert_query_part,$explicit_table_name=”"){
if(isset($explicit_table_name) & !empty($explicit_table_name))
$table=$explicit_table_name;
else
$table=$datamodelname;
   
   
   $query=”insert into ” . $table. $insert_query_part;//echo $query;exit;
  
 
   return $this->query($query);
   
   //exit;
   /* below comments already taking care in access-validation class so no required to take this care here*/
  //is user given acess to do this operation? is user allowed to insert every fields ?
  //fields_toinsert is a comma separated value , explode it ,
  //then turn byturn for each  exploded element check  whether user has been given access to insert this element
  //access checking can be made from has_field_access(column,user)
 }
 
 
function update_query($datamodelname,$update_query_part ,$where_string,$explicit_table_name=”"){

if(isset($explicit_table_name) & !empty($explicit_table_name))
$table=$explicit_table_name;
else
$table=$datamodelname;

   
   $query= “update ” . $table.  ” set “  . $update_query_part . ” where ” . $where_string;
   return $this->query($query);
   
   /* below comments already taking care in access-validation class so no required to take this care here*/
  //is user given acess to do this operation? is user allowed to insert every fields ?
  //fields_toinsert is a comma separated value , explode it ,
  //then turn byturn for each  exploded element check  whether user has been given access to insert this element
  //access checking can be made from has_field_access(column,user)
 }
function delete_query($datamodelname,$where_string,$explicit_table_name=”"){
if(isset($explicit_table_name) & !empty($explicit_table_name))
$table=$explicit_table_name;
else
$table=$datamodelname;

$query= “delete  from “  . $table . ” where “. $where_string;
//echo $query;exit;

return $this->query($query);
}
function select_query($datamodelname,$fields,$where_string=”",$countfield=”"){
if(isset($where_string)&& !empty($where_string)){
$where_string= ” where ” .$where_string;
}
if(isset($countfield)&& !empty($countfield)){
$fields=”count($countfield)”;
}
$query= “select ” . $fields.  ” from “  . $datamodelname . $where_string;

return $this->query($query);

}

function get_onerecord_object($datamodelname)//generally datamodel name is equal tablename appended with “_data”
{
}
function get_single_record_array($result=”")
{

 while($row1=mysql_fetch_assoc((isset($result[resultset]) && !empty ($result[resultset]))? $result[resultset] : $this->resultset))
   {    
    return $row1;
   }
}

?>

2) singnup.php

<?php
$commandaction=”add_member”;
require_once(”./include/config.php”);
require_once(”common.php”);

if ($_POST[’commandaction’]){

    $checkEmail =”select username from teamboard_users where email =’$_POST[email]’”;
   $check= $dbobj->query($checkEmail);
   
   if($check[count]==0){
   $result=operation_result($commandaction); 
   $insertId = mysql_insert_id();
   $name =$_POST[firstname].” “.$_POST[lastname];
   
   $sql = “INSERT into marty VALUES (null,’$name’,”,”,”,”, ”, ”,”, ”, 1, ”, now(),’1′,’$insertId’)”;
   $return= $dbobj->query($sql);
         
    save_onfailure($result,”signup.php”,”Add=0″);
   save_onsuccess($result,”member_account.php”,”Add=1″);
   }
   else{
   redirect(”signup.php”,”Exist=1″);
 }
 }
else{
$middle=”signup_view.php”;
}
 
?>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<title>::Signup::</title>
<link href=”style.css” mce_href=”style.css” rel=”stylesheet” type=”text/css”></head>
<script type=”text/javascript”>
 function checkPhone(phone){
 if (phone.length == 0) {
   window.alert(”You must provide a phone number.”);
   return false;
   }
 
   
   phone = phone.replace(”-”,”");
   phone = phone.replace(” “,”");
   phone = phone.replace(”(”,”");
   phone = phone.replace(”)”,”");
   phone = phone.replace(”.”,”");
   if (phone.length != 10) {
   window.alert(”Phone numbers must only include a 3-digit area code and a 7-digit phone number.”);
   return false;
   }
   
   
  for (i=0; i<phone.length; i++) {
  if (phone.charAt(i) < “0″ || phone.charAt(i) > “9″) {
  window.alert(”Phone numbers must only contain  numbers.”);
  return false;
   }
  } 
  return true;
 }
 
 function checkEmail(email) {
  if (email.length == 0) {
  window.alert(”You must provide an e-mail address.”);
  return false;
  }
  if (email.indexOf(”/”) > -1) {
  window.alert(”E-mail address has invalid character: /”);
  return false;
  }
  if (email.indexOf(”:”) > -1) {
  window.alert(”E-mail address has invalid character: :”);
  return false;
  }
  if (email.indexOf(”,”) > -1) {
  window.alert(”E-mail address has invalid character: ,”);
  return false;
  }
  if (email.indexOf(”;”) > -1) {
  window.alert(”E-mail address has invalid character: ;”);
  return false;
  }
  if (email.indexOf(”@”) < 0) {
  window.alert(”E-mail address is missing @”);
  return false;
  }
  if (email.indexOf(”\.”) < 0) {
  window.alert(”E-mail address is missing .”);
  return false;
  }
  if (email.indexOf(”@\.”) > 0) {
  window.alert(”E-mail address is invalid”);
  return false;
  }
  return true;
}
   function Validate()
   {
 
      /*   if (document.frm_signup.company_name.value == ” )
   {
     alert(’You must enter the company name’);
     return  false;
   }*/
  
  
    if (document.frm_signup.firstname.value == ” )
   {
     alert(’You must enter the firstname’);
     return  false;
   }
  
  
    if (document.frm_signup.lastname.value == ” )
   {
     alert(’You must enter the lastname’);
     return  false;
   }
    /*if (document.frm_signup.email.value == ” )
   {
     alert(’You must enter the email’);
     return  false;
   }*/
  
     if (document.frm_signup.password.value == ” )
   {
     alert(’You must enter the password’);
     return  false;
   }
   //phone= document.frm_signup.telephone.value;
  
  
  
  if(!checkPhone(document.frm_signup.telephone.value))
  return false;
  
  if(!checkEmail(document.frm_signup.email.value))
  return false;
  
       return true;
  
  
  
   }
</script>
<body>
<table width=”100%” border=”0″>
  <tr>
    <td height=”100″> </td>
  </tr>
  <tr>
    <td align=”center” valign=”middle”><table width=”45%” border=”0″ align=”center” cellpadding=”0″ cellspacing=”0″ bgcolor=”#FFFFFF”>
      <tr>
        <td height=”20″ align=”center” valign=”top”><img src=”images/logo.gif” mce_src=”images/logo.gif” width=”430″ height=”67″ align=”middle”></td>
      </tr>
      <tr>
        <td height=”20″ valign=”top”> </td>
      </tr>
      <tr>
        <td valign=”top”><img src=”images/spacer.gif” mce_src=”images/spacer.gif” width=”1″ height=”5″></td>
      </tr>
      <tr>
        <td valign=”top”><table width=”100%” border=”0″ cellspacing=”0″ cellpadding=”0″>
          <tr>
            <td align=”center” class=”arial16″> Sign
              up now! </td>
          </tr>
          <tr>
            <td align=”center”   valign=”middle” class=”content-text”> </td>
          </tr>
          <tr>
            <td align=”center”   valign=”middle” class=”content-text”><? include ($middle); ?></td>
          </tr>
         
        </table></td>
      </tr>
      <tr>
        <td valign=”top”><img src=”images/spacer.gif” mce_src=”images/spacer.gif” width=”1″ height=”5″></td>
      </tr>
    </table></td>
  </tr>
  <tr>
    <td> </td>
  </tr>
</table>
<link  rel=”stylesheet” type=”text/css”  href=”teamboard.css” mce_href=”teamboard.css”>
</body>
</html>

3) signup_view.php

<?
if ($_Get[’Exist’]==1) { echo  “User already exists”); }

?>
<form  name=”frm_signup” action=”signup.php” method=”post” onSubmit=”return Validate()”>
<table width=”75%” align=”center” class=”addinvestor-text”>
                <tr align=”right”>
                  <td colspan=”3″><?
      if ($_Get[’Add’]==1) { echo  “Record Successfully”); }
      else if  ($_Get[’Add’]==0) { echo  “Opertion failed”); }
 ?>
</td>
                </tr>
                <tr>
                  <td><span id=”" class=”content-text” style=”color:OliveDrab;”></span> </td>
                </tr>
                <tr>
                  <td><div id=”" class=”content-text” style=”color:Red;display:none;”></div></td>
                </tr>
                <tr>
                  <td align=”center” valign=”middle”><table width=”100%” align=”center” cellspacing=”1″ class=”content-text”>
          <tr>
            <td width=”39%” class=”arial12″> First name*:</td>
            <td colspan=2><input name=”firstname” type=”text” maxlength=”50″ id=”firstname” class=”content-text” style=”width:125px;” /></td>
          </tr>
          <tr>
            <td class=”arial12″> Last name*:</td>
            <td colspan=2><input name=”lastname” type=”text” maxlength=”50″ id=”lastname” class=”content-text” style=”width:125px;” /></td>
          </tr>
          <tr>
            <td class=”arial12″> Email*:</td>
            <td colspan=2><input name=”email” type=”text” maxlength=”50″ id=”" class=”content-text” style=”width:125px;” />
              <span id=”" class=”content-text” style=”color:Red;visibility:hidden;”> </span> </td>
          </tr>
          <tr>
            <td class=”arial12″> Password*:</td>
            <td colspan=2><input name=”password” type=”password” maxlength=”50″ id=”" class=”content-text” style=”width:125px;” /><span id=”" style=”color:Red;visibility:hidden;”> </span></td>
          </tr>
          <tr>
            <td class=”arial12″> Confirm password*:</td>
            <td colspan=2><input name=”tbcpass” type=”password” maxlength=”50″ id=”" class=”content-text” style=”width:125px;” />
              <span id=”" class=”content-text” style=”color:Red;visibility:hidden;”> </span></td>
          </tr>
          <tr>
            <td class=”arial12″> Telephone #:</td>
            <td colspan=2><input name=”telephone” type=”text” maxlength=”50″ id=”" class=”content-text” style=”width:125px;” />            </td>
          </tr>
         
          <tr>
            <td align=center> </td>
            <td align=left> </td>
            <td align=center> </td>
          </tr>
          <tr>
            <td align=center><input type=”hidden” name=”commandaction” value=’<? echo $commandaction ?>’ /></td>
            <td width=”25%” align=left>
              <input type=”submit” name=”Submit” value=”Sign up”>               </td>
            <td width=”36%” align=center> </td>
          </tr>
          <tr>
            <td colspan=3 align=center></td>
          </tr>
        </table></td>
                </tr>
  </table>
</form>

4) module_operation.php

<?

function operation_result($commandaction,$request=”")
{
global $dbobj;
switch ($commandaction){
case “add_member”:
 $userobj=new user_master(); 
 $datamodel_array=prepare_datamodel_from_form_POST(”user”,$_POST); //user is logical data model where cal_users is physical data model  ,pass the third parameter if name of primarykey is not “id”
 $result=$userobj->Add(”user”,$datamodel_array,”admin”,”teamboard_users”);//fourth parameter is needed if we want to provide explicit_table_name 
 if($result)
  { $_SESSION[’logged’] = true;
    $_SESSION[’level’] = $datamodel_array[user_level];
    $_SESSION[’user_id’] = mysql_insert_id();
    $_SESSION[’username’] = $_POST[’username’];
    $_SESSION[’registered’] = $datamodel_array[’registered’];
    $_SESSION[’last_logged’] = time();
    $_SESSION[’firstname’] = $datamodel_array[’firstname’];
    $_SESSION[’lastname’] = $datamodel_array[’lastname’];
    $_SESSION[’email’] = $datamodel_array[’email’];
   $_SESSION[’company_name’] = $datamodel_array[’company_name’];
 }
 break;

case “list_member”:
 if ($request==”del”){
 $where_string=” user_id = “.$_GET[del];
 $result1=$dbobj->delete_query(”teamboard_users”,$where_string,”");
 }
 else{
 $userobj=new user_master(); 
 $result=$dbobj->select_query(”teamboard_users”,”user_id,company_name,firstname,lastname,email,telephone”,”",”");   //$where_string=”",$countfield=”"
 
 }
 break; 
 }
return $result;
}

?>

5) prepare_data.php

<?
function prepare_datamodel_from_form_POST($datamodel,$post=”",$record_key=”"){
global $dbobj;

if(isset($record_key)  && !empty($record_key)){
$id=$record_key;
}
else
{
$id=”id”;
}
$datamodel_array=array();
switch ($datamodel){
case “user”:

   $id=”user_id”;
   $datamodel_array=$dbobj->datamodel_fields(”user”); //datamodelname with suffix _data
   
  
     if(isset($_POST[id]) && !empty($_POST[id])){
    $datamodel_array[$id] = $_POST[id];
     }
     else{
    $datamodel_array[$id] = “””;
   }
    
  
    $datamodel_array[’firstname’]=$_POST[’firstname’];
    $datamodel_array[’lastname’]=$_POST[’lastname’];
    $datamodel_array[’email’]=$_POST[’email’];
    $datamodel_array[’user_level’]=1;    
    $datamodel_array[’username’]=$_POST[’email’];
    $datamodel_array[’password’]=md5($_POST[’password’]);
    $datamodel_array[’last_logged’]=”";
    $datamodel_array[’registered’]=date(”Y-m-d H:i:s”);
    $datamodel_array[’last_ip’]=$_SERVER[’REMOTE_ADDR’];;
    $datamodel_array[’company_name’]=$_POST[’company_name’];
    $datamodel_array[’company_desc’]=$_POST[’company_desc’];
    $datamodel_array[’telephone’]=$_POST[’telephone’];
    $datamodel_array[’website_url’]=$_POST[’website_url’];
    
 break;

}
 return $datamodel_array;

}
?>

6) models.php

<?

class user_master extends master {
var $name,$tables,$datamodels;
function user_master(){
 $this->name=”member_user”;
 $this->tables();
 $this->datamodels();
}
function tables()
 {
  $this->tables=array(”teamboard_users”);
 } 
 function datamodels()
{
 $this->datamodels=array(”user_data”);
}
}

class user_data extends data {
function user_data(){
 $this->fields=array(’user_id’=>”,
      ’firstname’=>”,
       ‘lastname’=>”,
       ‘email’=>”,
       ‘user_level’=>”,
       ‘username’=>”,
       ‘password’=>”,
       ‘last_logged’=>”,
       ‘registered’=>”,
       ‘last_ip’=>”,      
       ‘company_name’=>”,
       ‘company_desc’=>”,
       ‘telephone’=>”,
       ‘website_url’=>”
      );
 $this->datatype=array(      
      ‘user_id’=>’int’,
      ’firstname’=>’string’,
       ‘lastname’=>’string’,
       ‘email’=>’string’,
       ‘user_level’=>’int’,
       ‘username’=>’string’,
       ‘password’=>’string’,
       ‘last_logged’=>’string’,
       ‘registered’=>’string’,
       ‘last_ip’=>’string’,
       ‘company_name’=>’string’,
       ‘company_desc’=>’string’,
       ‘telephone’=>’string’,
       ‘website_url’=>’string’
       );
 
 }
}
?>


Theme / layout programming in php

Friday, April 18th, 2008

There can be a need where we need include dynamically 

1)multiple files in header portion of the page

2) multiple files in left portion of the page

3) multiple files at middle of the page

4) Vertically separated two columned content block just above the middle files

5) Vertically separated two columned content block just below the middle files

6) multiple files at the bottom portion of the page

7) dynamic setting of page title

8 ) dynmic setting of page heading just above the vertically separated two column content block

Here is how this can be made possible…

<html>
<head>
<title><?php echo $pagecontentdata[’title’] ?>
</title>
</head>
<body>
<table>
<tr><td></td><td align=”center”><?php
$top=explode(”,”,$frame_inclusion_filedata[top]);
if(is_array($top) && isset($top) && !empty($top))
{
$count=count($top);
for($i=0;$i<$count;$i++)
{
if(file_exists($top[$i])){
echo “<div>”;
include($top[$i]);
echo “<div>”;
}
}
}

?></td></tr>
<tr><td valign=”top”><?php

$left=explode(”,”,$frame_inclusion_filedata[left]);
if(is_array($left) && isset($left) && !empty($left))
{
$count=count($left);
for($i=0;$i<$count;$i++)
{
if(file_exists($left[$i])){
echo “<div>”;
include($left[$i]);
echo “</div>”;
}
}
}
?></td><td valign=”top”>
<?php
if(isset($pagecontentdata[’pageheading’])){
echo “<h1>”.$pagecontentdata[’pageheading’].”</h1>”;
}

if(isset($pagecontentdata[’topcontent1′]) && !empty($pagecontentdata[’topcontent1′]) && isset($pagecontentdata[’topcontent2′]) && !empty($pagecontentdata[’topcontent2′])) {
echo “<table border=’1′><tr><td> “. $pagecontentdata[’topcontent1′].”</td><td>”.$pagecontentdata[’topcontent2′].”</td></tr></table>”;
}
if((isset($pagecontentdata[’topcontent1′]) && empty($pagecontentdata[’topcontent2′]) && !empty($pagecontentdata[’topcontent1′])) || isset($pagecontentdata[’topcontent2′]) && empty($pagecontentdata[’topcontent1′]) && !empty($pagecontentdata[’topcontent2′])) {
echo “<table border=’1′><tr><td> “. $pagecontentdata[’topcontent1′].”</td><td>”.$pagecontentdata[’topcontent2′].”</td></tr></table>”;
}
$middle=explode(”,”,$frame_inclusion_filedata[middle]);
if(is_array($middle) && isset($middle) && !empty($middle))
{
$count=count($middle);
for($i=0;$i<$count;$i++)
{
if(file_exists($middle[$i])){
echo “<div>”;
include($middle[$i]);
echo “</div>”;
}
}
}
/*
else{
 if(isset($middle) && !empty($middle) && file_exists($middle)){
require_once($middle);
}
}*/

if(isset($pagecontentdata[’bottomcontent1′]) && !empty($pagecontentdata[’bottomcontent1′]) && isset($pagecontentdata[’bottomcontent2′]) && !empty($pagecontentdata[’bottomcontent2′])) {
echo “<table border=’1′><tr><td> “. $pagecontentdata[’bottomcontent1′].”</td><td>”.$pagecontentdata[’bottomcontent2′].”</td></tr></table>”;
}
if((isset($pagecontentdata[’bottomcontent1′]) && empty($pagecontentdata[’bottomcontent2′]) && !empty($pagecontentdata[’bottomcontent1′])) || isset($pagecontentdata[’bottomcontent2′]) && empty($pagecontentdata[’bottomcontent1′]) && !empty($pagecontentdata[’bottomcontent2′])) {
echo “<table border=’1′><tr><td> “. $pagecontentdata[’bottomcontent1′].”</td><td>”.$pagecontentdata[’bottomcontent2′].”</td></tr></table>”;
}
?>
</td></tr>
<tr><td colspan=”2″ align=”center”><?php $bottom=explode(”,”,$frame_inclusion_filedata[bottom]);
if(is_array($bottom) && isset($bottom) && !empty($bottom))
{
$count=count($bottom);
for($i=0;$i<$count;$i++)
{
if(file_exists($bottom[$i])){
echo “<div>”;
include($bottom[$i]);
echo “</div>”;
}
}
}?></td></tr>
</table>
</body>
</html>


Structured php programming

Friday, April 18th, 2008

It is very important to separate the functionality in separate files. Each file will be responsible to serve the specific meaningful code.

Lets look at the following code of index.php used at http://webwayworld.com/dynamicworld/index.php

1) index.php

<?php
 include “common.php”;   
 
?>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″ />
<link href=”<?=HTTP_STYLE.” mainstyle.css”; ?>” rel=”stylesheet” type=”text/css”/>
<title>webwayworld.com</title>
</head>
<body>
<table width=”100%” border=”0″ cellspacing=”0″ cellpadding=”0″>
 <tr>
  <td colspan=”2″>
   <? include ROOT_INCLUDE.”header.php”;?>
  </td>
 </tr>
 <tr>
  <td colspan=”2″ align=”right” valign=”middle” class=”website”>
 
   <?
   echo ” Experience the web way world with webwayworld.com”;
   ?>
   
  </td>
 </tr>
 <tr><td colspan=”2″ align=”center”><? echo ” Discover the php solutions “; ?></td></tr>
  <tr>
  <td width=”25%” align=”left” valign=”top”>
  <table width=”100%” border=”0″ cellspacing=”0″ cellpadding=”5″>
  <?php echo “PHP MySQL based <br> web development” ?>
  </table>
 </td>
 
 <td width=”100%” align=”left” valign=”top”>
  <table width=”100%” border=”0″ align=”center” cellspacing=”0″ cellpadding=”5″>
  <?php
  echo “<h1> Explore web way world….<h1>”; ?>
  </table>
 </td>
  </tr>
</table>
</body>
</html>

2) common.php

<?php
 session_start();
 $httphost = $_SERVER[’HTTP_HOST’];
 $docroot = $_SERVER[’DOCUMENT_ROOT’];
 $instal_folder = “/dynamicworld/”;
 
  $rootpath = $docroot.$instal_folder;
 $hostpath = “
http://”.$httphost.$instal_folder;
 
 include $rootpath.”config.php”;
 include ROOT_COMMONDIR.”dbconnect.php”;
 
 include ROOT_FUNCTIONS.”common_functions.php”;
 ?>

3) config.php

<?php
global $rootpath;
global $hostpath;
global $path_separator;
$path_separator = ‘/’;
define(’ROOT_DIR’, $rootpath);
define(’ROOT_INCLUDE’, $rootpath.”includes”.$path_separator);

define(’ROOT_COMMONDIR’, $rootpath.”commondir”.$path_separator);
define(’ROOT_FUNCTIONS’, $rootpath.”functions”.$path_separator);
define(’ROOT_UPLOADS’, $rootpath.”uploads”.$path_separator);
define(’ROOT_STYLE’, $rootpath.”style”.$path_separator);

/*community and eventcalendar module  related root path*/
define(’ROOT_COMMUNITY’, $rootpath.”community”.$path_separator);
define(’ROOT_EVENTCALENDER’, $rootpath.”community/EventCalender”.$path_separator);
define(’ROOT_COMMUNITY_INCLUDE’, ROOT_COMMUNITY.”includes”.$path_separator);

define(’HTTP_DIR’, $hostpath);
define(’HTTP_UPLOADS’, $hostpath.”uploads”.$path_separator);
define(’HTTP_STYLE’, $hostpath.”style”.$path_separator);

/*community and eventcalendar module  related http  url*/
define(’HTTP_COMMUNITY’, $hostpath.”community”.$path_separator);
define(’HTTP_EVENTCALENDER’, $hostpath.”community/EventCalender”.$path_separator);

?>

4)header.php

<table width=”100%” border=”0″ cellspacing=”0″ cellpadding=”0″>
 <tr>
  <td height=”10″ class=”website”></td>
 </tr>
 <tr>
  <td align=”center” valign=”middle” class=”website”><h1>WAY TO DYNAMIC WEBSITES</h1></td>
 </tr>
 <tr>
  <td align=”center” valign=”middle” class=”website”><h4>WEBWAYWORLD</h4></td>
 </tr>
 <tr>
  <td align=”right” class=”website”>
   <a href=”<?=HTTP_COMMUNITY?>/index.php” mce_href=”<?=HTTP_COMMUNITY?>/index.php”><strong>Social Community</strong></a>
  </td>
 </tr>
</table>


How to design a website that is easily modified or updated.

Friday, April 18th, 2008

If you have a website with ten pages, updating should not be a problem. But how about if you have more pages..?

Lets say you can have your menu in one page for example and display it in every page of your website. When you want to change something in the menu, you have to edit only one page, and it automatically changes in other pages.

1)

<html>
<head>
<title> Simplified php web development</title>
</head>
<body>
Top menu here<br>

Save above code as header.php

2)

Main part of the web page<br>

Save it as main.php

3)

copyright

</body>

</html>

Save it as footer.php

What we have done here is, we created three different .php files namely: header.php, main.php and footer.php. Later we will be linking them together within a page to create one whole page. Basicaly header.php should include all the meta tags and top menu. And main.php should include all the body content. As for the footer.php it will include Copyright notes and other content like bottom menu.

4)

<?include (”header.php”); ?>
<? include (”main.php”); ?>
<? include (”footer.php”); ?>

Save it as index.php. All pages should be in the same folder. Otherwise the linking won’t work. Now access the index.php through your webserver. You should be able to see the following page.


include_once, require, require_once, include_path

Monday, April 14th, 2008


One of the problems caused by using multiple libraries within your code is the danger of calling include() twice on the same file. This can occur in larger projects when different library files call include() on a common file. Including the same file twice often results in repeated declarations of functions and classes, thereby causing the PHP engine great unhappiness.

The situation is saved by the include_once() statement. include_once() requires the path to an include file and behaves the same way as include() the first time it’s called. However, if include_once() is called again for the same file during script execution, the file is not included again. This makes include_once() an excellent tool for the creation of reusable code libraries!

The include_path Directive

Using include() and include_once() to access libraries can increase the flexibility and reusability of your projects. However, there are still headaches to overcome. Portability in particular can suffer if you hard-code the paths to included files. Imagine that you create a lib directory and reference it throughout your project:

include_once("/home/user/bob/htdocs/project4/lib/mylib.inc.php");

When you move your project to a new server, you might find that you have to change a hundred or more include paths. You can escape this fate by setting the include_path directive in your php.ini file:

include_path .:/home/user/bob/htdocs/project4/lib/

The include_path can include as many directories as you want, separated by colons (semicolons in Windows). The first dot (.) before the first colon indicates “current directory.” You can then reference your library file by only its name:

include_once("mylib.inc.php");

When you move your project, you need to change only the include_path directive.

 

PHP has both a require() statement, which performs a similar function to include(), and a require_once() statement. require() is executed regardless of a script’s flow, and therefore shouldn’t be used as part of conditional or loop structures.

A file included as a result of a require() statement cannot return a value.


Including Files with include()

Monday, April 14th, 2008

The include() statement enables you to incorporate files into your PHP documents. PHP code in these files can be executed as if it were part of the main document. This can be useful for including library code in multiple pages.

Having created a killer function, your only option until now would have been to paste it into every document that needs to use it. Of course, if you discover a bug or want to add a feature, you would have to find every page that uses the function to make the change. The include() statement can save you from this chore. You can add the function to a single document and, at runtime, read it into any page that needs it. The include() statement requires a single argument: a relative path to the file to be included. 1.php creates a simple PHP script that uses include() to incorporate and output the contents of a file.

Using include()
  1: <html>
  2: <head>
  3: <title>1.php Using include()</title>
  4: </head>
  5: <body>
  6: <?php
  7: include("2.php");
  8: ?>
  9: </body>
 10: </html>

Put the above contents in a file named 1.php.

 

  1: I have been included!!

put the above in a file named 2.php

The include() statement in 1.php incorporates the document 2.php

 

Place both files in your Web server document root. When you access 1.php through your Web browser, the output on the screen is

I have been included!!

This might seem strange to you, given that we’ve included plain text within a block of PHP code. In fact, the contents of an included file are displayed as text by default.

If you want to execute PHP code in an included file, you must enclose it in PHP start and end tags. In below examples , we amend the previous example so that code is executed in the included file.

 Using the include() Statement to Execute PHP in Another File
  1: <html>
  2: <head>
  3: <title>Using include to execute PHP in another file</title>
  4: </head>
  5: <body>
  6: <?php
  7: include("4.php");
  8: ?>
  9: </body>
 10: </html>
Put the above contents  in a file named 3.php
An Include File Containing PHP Code
  1: <?php
  2: print "I have been included!!<BR>";
  3: print "But now I can add up... 4 + 4 = ".(4 + 4);
  4: ?>

Put the above code  in a file named 4.php. Place both these files in your Web server document root. When you access 3.php through your Web browser, the output on the screen is

I have been included!!

But now I can add up... 4 + 4 = 8

Returning a Value from an Included Document

Included files in PHP can return a value in the same way that functions do. As in a function, using the return statement ends the execution of code within the included file. Additionally, no further HTML is included. In below examples we include a file and assign its return value to a variable.

 Using include() to Execute PHP and Assign the Return Value
  1: <html>
  2: <head>
  3: <title>Using include() to execute PHP and
  4:      assign the return value</title>
  5: </head>
  6: <body>
  7: <?php
  8: $addResult = include("listing10.6.php");
  9: print "The include file returned $addResult";
 10: ?>
 11: </body>
 12: </html>
Put the above contents  in a file named 5.php
An Include File That Returns a Value
  1: <?php
  2: $retval = (4 + 4);
  3: return $retval;
  4: ?>
  5: This HTML will never be displayed because it comes after a return statement!

Put the above code in a file named 6.php. Place both of these files in your Web server document root. When you access listing10.5.php through your Web browser, the output is

The include file returned 8

Using include() Within Control Structures

You can use an include() statement in a conditional statement, and the referenced file is read only if the condition is met. For example, the include() statement in the following fragment will never be called:

$test = false;
if ($test) {
include("a_file.txt"); // won't be included
}

If you use an include() statement within a loop, it’s replaced with the contents of the referenced file each time the include() statement is called. This content is executed for every call. Below example illustrates this concept by using an include() statement in a for loop. The include() statement references a different file for each iteration.

Using include() Within a Loop
  1: <html>
  2: <head>
  3: <title> Using include() within a loop</title>
  4: </head>
  5: <body>
  6: <?php
  7: for ( $x = 1; $x<=3; $x++ ) {
  8:    $incfile = "incfile$x".".txt";
  9:    print "Attempting include $incfile<br>";
 10:    include( "$incfile" );
 11:    print "<p>";
 12: }
 13: ?>
 14: </body>
 15: </html>

When above code is run, it includes the content of three different files: “incfile1.txt”, “incfile2.txt”, and “incfile3.txt”. Assuming that each of these files simply contains a confirmation of its own name.


Creating the Script to Send the Mail

Monday, April 14th, 2008

The form below has an action of action_mail.php. The fields are very simple: Line 7 contains a name field, line 8 contains the return email address field, and line 10 contains the text area for the user’s message.

Creating a Simple Feedback Form
  1: <HTML>
  2: <HEAD>
  3: <TITLE>E-Mail Form</TITLE>
  4: </HEAD>
  5: <BODY>
  6: <FORM action="action_mail.php" method="POST">
  7: Your Name: <INPUT type="text" name="name"><br><br>
  8: Your E-Mail Address: <INPUT type="text" name="email"><br><br>
  9: Message:<br>
 10: <textarea name="message" cols=30 rows=5></textarea><br><br>
 11: <INPUT type="submit" value="Send Form">
 12: </FORM>
 13: </BODY>
 14: </HTML>

 

 

Put these lines into a text file called form_mail.php, and place this file in your Web server document root. Now access the script with your Web browser

In below script, in addition to printing the responses to the screen, you send them to an email address as well.

Sending the Simple Feedback Form
  1: <html>
  2: <head>
  3: <title>action_mail.php Sending mail from the form in form_mail.php</title>
  4: </head>
  5: <body>
  6: <?php
  7: print "Thank you, <b>$_POST[name]</b>, for your message!<br><br>\n\n";
  8: print "Your e-mail address is: <b>$_POST[email]</b><br><br>\n\n";
  9: print "Your message was:<br><br>\n\n";
 10: print "$_POST[message] <br><br>";
 11: //start building the mail string
 12: $msg = "Name: $_POST[name]\n";
 13: $msg .= "E-Mail: $_POST[email]\n";
 14: $msg .= "Message: $_POST[message]\n";
 15: //set up the mail
 16: $recipient = "you@yourdomain.com";
 17: $subject = "Form Submission Results";
 18: $mailheaders = "From: My Web Site <defaultaddress@yourdomain.com> \n";
 19: $mailheaders .= "Reply-To: $_POST[email]";
 20: //send the mail
 21: mail($recipient, $subject, $msg, $mailheaders);
 22: ?>
 23: </body>
 24: </html>

The variables you use in lines 7-9 are $_POST[name], $_POST[email], and $_POST[message]—the names of the fields in the form, as part of the $_POST superglobal. That’s all well and good for printing the information to the screen, but in this script, you also want to create a string that’s sent in email. For this task, you essentially build the email by concatenating strings to form one long message string, using the newline (\n) character to add line breaks where appropriate.

Lines 12 through 14 create the $msg string, which contains the values typed by the user in the form fields. This string is the one sent in the email. Note the use of the concatenation operator (.=) when adding to the variable $msg, in lines 13 and 14.

Lines 16 and 17 are hard-coded variables for the email recipient and the subject of the email message. Replace you@yourdomain.com with your own email address, obviously. If you want to change the subject, feel free!

Lines 18 and 19 set up some mail headers, namely From: and Reply-to: headers. You could put any value in the From: header; this is the information that displays in the From or Sender column of your email application when you receive this mail.

The mail() function takes four parameters: the recipient, the subject, the message, and any additional mail headers. The order of these parameters is shown in line 21, and your script is complete after you close up your PHP block and your HTML elements in lines 22-24.

Put these lines into a text file called action_mail.php, and place that file in your Web server document root.