<style type="text/css"> #cssmenu ul {margin: 0; padding: 7px 6px 0; background: #7d7d7d url(menu_assets/images/overlay.png) repeat-x 0 -110px; line-height: 100%; border-radius: 1em; font: normal .8em/1.5em Arial, Helvetica, sans-serif; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 1px 3px rgba(0,0,0, .4); -moz-box-shadow: 0 1px 3px rgba(0,0,0, .4);} #cssmenu li {margin: 0 5px; padding: 0 0 8px; float: left; position: relative; list-style: none; } #cssmenu a, #cssmenu a:link {font-weight: bold; color: #e7e5e5; text-decoration: none; display: block; padding: 8px 20px; margin: 0; border-radius: 5px; -webkit-border-radius: 5px; -moz-border-radius: 5px; text-shadow: 0 1px 1px rgba(0,0,0, .3); } #cssmenu a:hover {background: #000; color: #fff;} #cssmenu .active a, #cssmenu li:hover > a {background: #666 url(menu_assets/images/overlay.png) repeat-x 0 -40px; color: #444; border-top: solid 1px #f8f8f8; -webkit-box-shadow: 0 1px 1px rgba(0,0,0, .2); -moz-box-shadow: 0 1px 1px rgba(0,0,0, .2); box-shadow: 0 1px 1px rgba(0,0,0, .2); text-shadow: 0 1px 0 rgba(255,255,255, 1); } #cssmenu ul ul li:hover a, #cssmenu li:hover li a {background: none; border: none; color: #666; -webkit-box-shadow: none; -moz-box-shadow: none;} #cssmenu ul ul a:hover {background: #8f8f8f url(menu_assets/images/overlay.png) repeat-x 0 -100px !important; color: #fff !important; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; text-shadow: 0 1px 1px rgba(0,0,0, .1);} #cssmenu li:hover > ul {display: block;} #cssmenu ul ul {display: none; margin: 0; padding: 0; width: 185px; position: absolute; top: 40px; left: 0; background: #ddd url(menu_assets/images/overlay.png) repeat-x 0 0; border: solid 1px #b4b4b4; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 1px 3px rgba(0,0,0, .3); -moz-box-shadow: 0 1px 3px rgba(0,0,0, .3); box-shadow: 0 1px 3px rgba(0,0,0, .3);} #cssmenu ul ul li {float: none; margin: 0; padding: 3px; } #cssmenu ul ul a {font-weight: normal; text-shadow: 0 1px 0 #fff; } #cssmenu ul:after {content: '.'; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;} * html #cssmenu ul {height: 1%;}</style> <div id='cssmenu'> <ul> <li class='active '><a href='index.html'><span>Home</span></a></li> <li class='has-sub '><a href='#'><span>Products</span></a> <ul> <li><a href='#'><span>Product 1</span></a></li> <li><a href='#'><span>Product 2</span></a></li> </ul> </li> <li><a href='#'><span>About</span></a></li> <li><a href='#'><span>Contact</span></a></li> </ul> </div>
article
Tuesday, August 20, 2013
Simple Dropdown Menu like apple
Simple Dropdown Menu like apple
Create Modal Box Using Jquery
Create Modal Box Using Jquery
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Modal Box</title> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { //Buttons that trigger the popup $(".signup_popup_button").click(function(e) { $(this).doPopup(); //this is needed so it wont fire the closePopup function when we click the body e.stopPropagation(); }); $.fn.doPopup = function(options) { var defaults = { slide: 0, }; //popup window div var popup_window = $("#popup_window"); //loader var loader = $(".loader"); //state of popup //if its 0 its hidden , 1 its shown var state = 0; //self explanotary, centers the popup window function centerPopup(){ var windowWidth = document.documentElement.clientWidth; var windowHeight = document.documentElement.clientHeight; var popupWidth = popup_window.width(); //centering popup_window.css({ "position": 'absolute', "top": '21%', "left": windowWidth/2-popupWidth/2 }); $("#bg_color").css({ "height": windowHeight }); } //remove the background color when popup is active function backgroundFade(){ $("#bg_color").css({ "opacity": "0.7" }); $("#bg_color").fadeIn("fast"); } //closes the popup function closePopup(){ //remove background fade $("#bg_color").fadeOut("fast") //close popup popup_window.fadeOut("fast"); } //show the page content function showContent(){ //show div containing the forms $(".popup_content_data").show(); } //this is needed so the popup remains shown popup_window.click(function(e){ e.stopPropagation(); }); //when we click the X button on the top right corner of the popup //we close the window $(".popup_window_close").click(function(){ state=0; closePopup(); }); //when we click on the body we close the popup window $("body").click(function(){ if (state == 1){ closePopup(); state = 0; } }); //Shows the Popup function showPopup(type){ if (state == 0){ //fade background on click backgroundFade() if (type == ""){ $(".popup_content_data").hide(); //show the loading text and image loader.show(); } //dynamically show the popup window centerPopup(); //show the popup window popup_window.show(); //animate the popup window and hide the loader setTimeout(function(){ loader.hide(); showContent(); }, 200); state = 1; } } showPopup("fade"); }; })(jQuery); </script> <style> body{ font-size:13px; font-family:Tahoma; border: 0 none; margin: 0; outline: 0 none; padding: 0; vertical-align: baseline; } h1,h2,h3{ margin:0; padding:0; } #signup_submit{ min-width:100px; max-width:135px; display:inline-block; height:18px; border:1px solid #B5B5B5; padding:5px; background: -moz-linear-gradient(center top , #FFFFFF, #E3E3E3) repeat scroll 0 0 #F6F6F6; -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#FFFFFF, endColorstr=#E3E3E3)"; background-image: -o-linear-gradient(#FFFFFF,#E3E3E3); color:#3D3D3D; cursor:pointer; background-color:#E8E8E8; border-radius:3px; } .message_error{ border:solid 1px #a1a1a1; background-color: #FFC922; border-radius:5px; color: #3B3B3B; width:96%; padding:5px; display:none; float:left; margin-top:10px; } .signup_popup_button{ float:left; width:78px; margin-left:-1px; text-align:center; } .recoverpass_popup_button{ float:left; width:110px; margin-left:-1px; border-radius:0; text-align:right; } .activate_account_popup_button{ float:left; border-radius:0 3px 3px 0; margin-left:-1px; } #popup_window{ display:none; border:12px solid #292929; padding:12px; border-radius:12px; width:591px; min-height:250px; overflow:hidden; word-wrap: break-word; position:absolute; _position:absolute; z-index:9999; background-color:#FFFFFF; background-image: -webkit-gradient( linear, left bottom, left top, color-stop(0.44, #EDEDED), color-stop(0.72, #FFFFFF), color-stop(0.86, #FFFFFF) ); background-image: -moz-linear-gradient( center bottom, #EDEDED 44%, #FFFFFF 72%, #FFFFFF 86% ); -ms-filter: "progid:DXImageTransform.Microsoft.gradient(GradientType=0, startColorstr=#FFFFFF, endColorstr=#EDEDED)"; background-image: -o-linear-gradient(#FFFFFF,#EDEDED); -moz-box-shadow: 0 0 5px 5px #888; -webkit-box-shadow: 0 0 5px 5px#888; box-shadow: 0 0 5px 5px #888; } .loader{ display:none; font-family:Tahoma; font-size:20px; width:150px; height:150px; text-align:center; margin:0 auto; margin-top:20%; } .popup_content_data{ display:none; float:left; width:100%; } .popup_content_sign_in,.popup_content_sign_up,.popup_content_recoverpass,.popup_content_activate_account,.popup_content_resent_activation_code{ margin:0 auto; margin-left:3px; margin-top:5px; width:395px; padding:5px 5px 11px; float:left; border-bottom: 1px solid #CCCCCC; border-top: 1px solid #CCCCCC; min-height:325px; display:none; } .popup_content_sign_in label,.popup_content_sign_up label,.popup_content_recoverpass label,.popup_content_activate_account label,.popup_content_resent_activation_code label{ display:block; width:125px; float:left; height:20px; padding-top:5px; padding-left:3px; } .popup_window_close{ background-image: url('images/close.png'); width:24px; height:24px; float:right; cursor:pointer; } .popup_header_title{ margin:0 auto; width:365px; padding:0; font-family:Tahoma; } .actions_header_title{ display:inline-block; text-align:center; font-size:20px; padding-bottom:3px; margin-bottom:15px; } .user_profile_details{ float:left; width: 558px; margin-top:15px; margin-left:139px; } .user_profile_details label{ float:left; margin-top:3px; padding-top:2px; height:20px; width:300px; } #user_settings_gender{ float:left; width:257px; } #user_page_username{ float:right; } #bg_color{ display:none; position:fixed; _position:absolute; height:100%; width:100%; top:0; left:0; background:#000000; border:1px solid #cecece; z-index:1; } #username_input_signin,#user_settings_current_password,#user_settings_retype_password,#user_settings_password,#user_settings_email,#user_settings_lastname,#user_settings_firstname,#user_settings_username,#username_input_signup,#firstname_input_signup,#lastname_input_signup,#password_input_signin,#password_input_signup,#retype_password_input_signup,#email_input_signup,#email_input_recpass,#email_input_activateaccount,#code_input_activateaccount,#email_input_resent_activation_code{ border:1px solid #CCC; border-radius:5px; height:20px; width:250px; padding:3px; margin-bottom:5px; float:left; } #username_input_signup:hover{ border:1px solid #000000; } #username_input_signin:focus,#user_settings_current_password:focus,#user_settings_retype_password:focus,#user_settings_password:focus,#user_settings_email:focus,#user_settings_lastname:focus,#user_settings_firstname:focus,#user_settings_username:focus,#username_input_signup:focus,#firstname_input_signup:focus,#lastname_input_signup:focus,#password_input_signin:focus,#password_input_signup:focus,#retype_password_input_signup:focus,#email_input_signup:focus,#email_input_recpass:focus,#email_input_activateaccount:focus,#email_input_resent_activation_code:focus,#code_input_activateaccount:focus{ -moz-box-shadow: 0 0 3px 3px #FFDB2C; -webkit-box-shadow: 0 0 3px 3px #FFDB2C; box-shadow: 0 0 3px 3px #FFDB2C; border:1px solid #A68323; } #gender_input_signup{ width:120px; } .popup_right_message{ background-color: #FFE16B; border-radius: 5px 5px 5px 5px; float: right; padding: 5px; width: 170px; margin-top:11px; } </style> </head> <body> <div id="bg_color"></div> <div style="text-align: center;"> <div id="user_controls"> <div class="signup_popup_button" id="sign_up" title="Sign up">Sign Up</div> </div> </div> <div id="popup_window"> <div class="loader"><img src="images/loading.gif" style="border:0;" alt="loading" />Loading...</div> <div class="popup_content_data"> <span class="popup_window_close" title="Close Popup"></span> <h1>Sign Up</h1> <div class="popup_content_sign_up" style="display:inline-block;"> <label for="username_input_signup"> Username: </label> <input type="text" id="username_input_signup" /> <br /> <label for="firstname_input_signup"> Firstname: </label> <input type="text" id="firstname_input_signup" /> <br /> <label for="lastname_input_signup"> Lastname: </label> <input type="text" id="lastname_input_signup" /> <br /> <label for="password_input_signup"> Password: </label> <input type="password" id="password_input_signup" /> <br /> <label for="retype_password_input_signup"> Re-type Password: </label> <input type="password" id="retype_password_input_signup" /> <br /> <label for="email_input_signup"> Email: </label> <input type="text" id="email_input_signup" /> <br /> <label for="gender_input_signup"> Gender: </label> <select name="gender_input_signup" id="gender_input_signup"> <option name="0">Select Gender:</option> <option name="1">Male</option> <option name="2">Female</option> </select> <br /> <div id="signup_submit">Sign up</div><br /> <div class="message_error"></div> </div> </div> </div> </body> </html>
Saturday, August 17, 2013
Create Database Table Using Class PHP
<?php error_reporting(0); define('MYSQL_HOSTNAME', 'localhost'); define('MYSQL_USERNAME', 'root'); define('MYSQL_PASSWORD', ''); define('MYSQL_DATABASE', 'test'); define('USERS_TABLE_NAME','alm_users2'); class Db { function connect() { $connect = mysql_connect(MYSQL_HOSTNAME, MYSQL_USERNAME, MYSQL_PASSWORD); $select_db = mysql_select_db (MYSQL_DATABASE, $connect); if (!$connect) { $errno = mysql_errno(); switch($errno) { case 1045 : { $this->error(); break; } } } elseif(!$select_db) {$this->error(); break;} $strSQL = "SELECT * from ".USERS_TABLE_NAME." limit 1"; $result = mysql_query ($strSQL); if($result==null) { $this->create_table(); die(); } } function error() { echo "<div style='width:350;margin:auto;text-align:center;font-family:Arial'> <span style='font-size:15px;color:red'>MYSQL SERVER ERROR : ".mysql_error()."</span> </div>"; echo "<div style='width:350;margin:auto;text-align:center;margin-top:10px;font-family:Arial'> You must edit first the database config </div>"; die(); } function create_table() { $strSQL = " CREATE TABLE `".USERS_TABLE_NAME."` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(200) NOT NULL DEFAULT '', `password` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; "; $result = mysql_query ($strSQL); $strSQL = "INSERT INTO `".USERS_TABLE_NAME."` (`id`,`username`,`password`) VALUES (1,'admin','admin');"; $result = mysql_query ($strSQL); echo ('<meta http-equiv="refresh" content="0;">'); } } $msql = new Db; $msql->connect(); ?>
Ajax, Php class dynamic select box
Ajax, Php class dynamic select box
Create table state
CREATE TABLE IF NOT EXISTS `state` (
`state_id` int(11) NOT NULL AUTO_INCREMENT,
`country_id` int(11) NOT NULL,
`state_name` varchar(255) NOT NULL,
PRIMARY KEY (`state_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 98, 'Zambales'),
(2, 98, 'Pampanga');
Crate table city
CREATE TABLE IF NOT EXISTS `city` (
`city_id` bigint(20) NOT NULL AUTO_INCREMENT,
`state_id` bigint(20) NOT NULL,
`country_id` int(11) NOT NULL,
`city_name` varchar(255) NOT NULL,
PRIMARY KEY (`city_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `city` (`city_id`, `state_id`, `country_id`, `city_name`) VALUES
(1, 1, 98, 'Olongapo City'),
(2, 1, 98, 'Iba'),
(3, 2, 98, 'Angeles City'),
(4, 2, 98, 'San Fernando');
Create table state
CREATE TABLE IF NOT EXISTS `state` (
`state_id` int(11) NOT NULL AUTO_INCREMENT,
`country_id` int(11) NOT NULL,
`state_name` varchar(255) NOT NULL,
PRIMARY KEY (`state_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 98, 'Zambales'),
(2, 98, 'Pampanga');
Crate table city
CREATE TABLE IF NOT EXISTS `city` (
`city_id` bigint(20) NOT NULL AUTO_INCREMENT,
`state_id` bigint(20) NOT NULL,
`country_id` int(11) NOT NULL,
`city_name` varchar(255) NOT NULL,
PRIMARY KEY (`city_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
INSERT INTO `city` (`city_id`, `state_id`, `country_id`, `city_name`) VALUES
(1, 1, 98, 'Olongapo City'),
(2, 1, 98, 'Iba'),
(3, 2, 98, 'Angeles City'),
(4, 2, 98, 'San Fernando');
//index.php <?php include("functions.php"); $db = new PHP_fun(); ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Ajax, Php class list box </title> <script language="javascript" type="text/javascript" src="validation.js"></script> <script language="javascript" type="text/javascript"> function getCities(id) { var obj = document.form1; if (id != "") { url = "getCities.php?stateid="+id; http.open("GET", url, true); http.onreadystatechange = getCitiesResponse; http.send(null); } } function getCitiesResponse() { //alert(http.readyState); var obj = document.form1; if (http.readyState == 4) { var result = trimString(http.responseText); if (result != '' && result != 'undefined') { clearBox(obj.city); obj.city.options[0] = new Option("-City-", ""); var result_line_arr = result.split("###"); for (i=0;i<result_line_arr.length;i++) { var result_arr = result_line_arr[i].split(":"); var code = result_arr[0]; var name = result_arr[1]; obj.city.options[i+1] = new Option(name, code); } } } } </script> </head> <body> <table width="60%" border="0" cellspacing="0" cellpadding="5"> <form action="" method="post" name="form1"> <tr> <td align="right" class="verdana11">State :</td> <td align="left" class="verdana11"> <select name="state" id="state" onchange="javascript: getCities(this.value);"> <option value="">-State-</option> <?php $sql = "select * from state"; $rs = $db->select_row($sql); for($i=0;$i<count($rs);$i++) { ?> <option value="<?=$rs[$i]['state_id']?>"><?=$rs[$i]['state_name']?></option> <?php } ?> </select> </td> </tr> <tr> <td align="right" class="verdana11">City : </td> <td align="left" class="verdana11"> <select name="city" id="city" style="width:150px;"> <option value="">-City-</option> </select> </td> </tr> </form> </table> </body> </html>
//funtion.php <?php class PHP_fun { function getConfig() { $this->DB_SERVER = 'localhost'; $this->DB_USER = 'root'; $this->DB_PASS = ''; $this->DB_NAME = 'test'; } function __construct() { $this->getConfig(); $Conn = mysql_connect($this->DB_SERVER, $this->DB_USER, $this->DB_PASS); if (!$Conn) die("Error: ".mysql_errno($Conn).":- ".mysql_error($Conn)); $DB_select = mysql_select_db($this->DB_NAME, $Conn); if (!$DB_select) die("Error: ".mysql_errno($Conn).":- ".mysql_error($Conn)); } function select_row($sql) { if ($sql!="") { $result = mysql_query($sql) or die("Error: ".mysql_errno().":- ".mysql_error()); if ($result) { while($row = mysql_fetch_array($result)) $data[] = $row; } return $data; } } } ?>
//getCities.php <?php include("functions.php"); $db = new PHP_fun(); $str = ""; $stateid = trim($_REQUEST['stateid']); if ($stateid != "") { $sql = sprintf("SELECT city_id, city_name FROM city WHERE state_id = '%d' ", $stateid); $rs = $db->select_row($sql); if (count($rs) > 0) { for($i=0;$i<count($rs);$i++) { $str .= $rs[$i]['city_id'].":".$rs[$i]['city_name']."###"; } echo $str = substr($str,0,-3); } } ?>
//validation.js // ajax oject function getHTTPObject() { var xmlhttp; /*@cc_on @if (@_jscript_version >= 5) try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } @else xmlhttp = false; @end @*/ if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { try { xmlhttp = new XMLHttpRequest(); } catch (e) { xmlhttp = false; } } return xmlhttp; } var http = getHTTPObject(); // We create the HTTP Object function clearBox(ObjselBox) { for(i=ObjselBox.length-1; i>=0; i--) { deleteOption(ObjselBox, i); } } function deleteOption(theSel, theIndex) { var selLength = theSel.length; if(selLength > 0) { theSel.options[theIndex] = null; } } // end ajas object function trimString(str) { return str.replace(/^\s+|\s+$/g, ''); }
Simple PHP Class Drop Down Menu
Simple PHP Class Drop Down Menu
Create database table
CREATE TABLE `tblcategories` (
`id` int(11) NOT NULL,
`Name` varchar(100) collate latin1_general_ci NOT NULL,
`pid` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
Create database table
CREATE TABLE `tblcategories` (
`id` int(11) NOT NULL,
`Name` varchar(100) collate latin1_general_ci NOT NULL,
`pid` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;
//index.php <?php DEFINE ('DB_USER', 'root'); DEFINE ('DB_PASSWORD', ''); DEFINE ('DB_HOST', 'localhost'); DEFINE ('DB_NAME', 'test'); class AjaxDropdown { var $table; function AjaxDropdown() { mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL: ' . mysql_error() ); mysql_select_db (DB_NAME) OR die ('Could not select the database: ' . mysql_error() ); $this->table = "tblcategories"; } function dbConnect() { mysql_connect (DB_HOST, DB_USER, DB_PASSWORD); } function getArray($id) { $this->dbConnect(); $query = "SELECT * FROM $this->table where pid = {$id} ORDER BY id asc"; $result = mysql_query ($query); $arr = array(); while($row = mysql_fetch_object($result)) { $arr[] = $row; } mysql_close(); return $arr; } } $strRet = ""; $obj = new AjaxDropdown(); $arr = $obj->getArray(0); $strRet .= '<option value="0">--Select--</option>'; foreach ( $arr as $row ) { $strRet .= '<option value="'.$row->id.'">'.$row->Name.'</option>'; } ?> <select name="selCat" class="text"> <?php echo $strRet; ?> </select>
Ajax Add & Delete MySQL records using jQuery & PHP
Ajax Add & Delete MySQL records using jQuery & PHP
Create Table
CREATE TABLE IF NOT EXISTS `add_delete_record` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Create Table
CREATE TABLE IF NOT EXISTS `add_delete_record` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
//index.php <html> <head> <title>Ajax Add/Delete Record with jQuery</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#FormSubmit").click(function (e) { e.preventDefault(); if($("#contentText").val()==='') { alert("Please enter some text!"); return false; } var myData = 'content_txt='+ $("#contentText").val(); //build a post data structure jQuery.ajax({ type: "POST", // Post / Get method url: "response.php", //Where form data is sent on submission dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables success:function(response){ $("#responds").append(response); $("#contentText").val(''); }, error:function (xhr, ajaxOptions, thrownError){ alert(thrownError); } }); }); $("body").on("click", "#responds .del_button", function(e) { e.returnValue = false; var clickedID = this.id.split('-'); //Split string (Split works as PHP explode) var DbNumberID = clickedID[1]; //and get number from array var myData = 'recordToDelete='+ DbNumberID; //build a post data structure jQuery.ajax({ type: "POST", // Post method url: "response.php", dataType:"text", // Data type, HTML, json etc. data:myData, //Form variables success:function(response){ $('#item_'+DbNumberID).fadeOut("slow"); }, error:function (xhr, ajaxOptions, thrownError){ //On error, we alert user alert(thrownError); } }); }); }); </script> <link href="css/style.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="content_wrapper"> <ul id="responds"> <?php include_once("config.php"); //MySQL query $Result = mysql_query("SELECT id,content FROM add_delete_record"); //get all records from add_delete_record table while($row = mysql_fetch_array($Result)) { echo '<li id="item_'.$row["id"].'">'; echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">'; echo '<img src="images/icon_del.gif" border="0" />'; echo '</a></div>'; echo $row["content"].'</li>'; } mysql_close($connecDB); ?> </ul> <div class="form_style"> <textarea name="content_txt" id="contentText" cols="45" rows="5"></textarea> <button id="FormSubmit">Add record</button> </div> </div> </body> </html>
//config.php <?php $username = "root"; $password = ""; $hostname = "localhost"; $databasename = 'test'; $connecDB = mysql_connect($hostname, $username, $password)or die('could not connect to database'); mysql_select_db($databasename,$connecDB); ?>
response.php <?php include_once("config.php"); if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0) { /* sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters. */ $contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); if(mysql_query("INSERT INTO add_delete_record(content) VALUES('".$contentToSave."')")) { $my_id = mysql_insert_id(); echo '<li id="item_'.$my_id.'">'; echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$my_id.'">'; echo '<img src="images/icon_del.gif" border="0" />'; echo '</a></div>'; echo $contentToSave.'</li>'; }else{ header('HTTP/1.1 500 Looks like mysql error, could not insert record!'); exit(); } } elseif(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"])) { $idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT); if(!mysql_query("DELETE FROM add_delete_record WHERE id=".$idToDelete)) { header('HTTP/1.1 500 Could not delete record!'); exit(); } } else { //Output error header('HTTP/1.1 500 Error occurred, Could not process request!'); exit(); } mysql_close($connecDB); ?>
Thursday, August 15, 2013
Simple Class login using php
<? class UserAuth { var $user; var $pass; function isUserValid($user, $pass) { $sql = "select uid, first_name from $users_tb where user_name='$user' and password='$pass'"; $result = mysql_query($sql); $rows = mysql_num_rows($result); if($rows == 1) { $result_row = mysql_fetch_row($result); return $result_row; } else { return "0"; } } } $userauth = new UserAuth; session_start(); $user = $_POST['uname']; $pass = $_POST['password']; $val = $userauth->isUserValid($user, $pass); if($val == "0") { header("Location: login.php"); } else { $_SESSION['uid'] = $val[0]; $_SESSION['fname'] = $val[1]; $_SESSION['uname'] = $user; header("Location: SchedulerMain.php"); } ?> <form name="scheduler_login" method="post" action="UserAuthController.php"> User name<input type=text size=15 name=uname> Password<input type=password size=15 name=password> <input type=submit name=submit value="Submit"> </form>
Sunday, August 11, 2013
Jquery Count Remaining Character
Jquery Count Remaining Character
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script><script> $(document).ready(function(){ var totalChars = 100; //Total characters allowed in textarea var countTextBox = $('#counttextarea') // Textarea input box var charsCountEl = $('#countchars'); // Remaining chars count will be displayed here charsCountEl.text(totalChars); //initial value of countchars element countTextBox.keyup(function() { //user releases a key on the keyboard var thisChars = this.value.replace(/{.*}/g, '').length; //get chars count in textarea var per = thisChars*100; var value= (per / totalChars); // total percent complete if(thisChars > totalChars) //if we have more chars than it should be { var CharsToDel = (thisChars-totalChars); // total extra chars to delete this.value = this.value.substring(0,this.value.length-CharsToDel); //remove excess chars from textarea }else{ charsCountEl.text( totalChars - thisChars ); //count remaining chars $('#percent').text(value +'%'); } }); }); </script> <div class="main-item"><div><textarea name="counttextarea" id="counttextarea" cols="45" rows="5" style="width: 400px;padding: 10px;"></textarea></div> <div><span name="countchars" id="countchars"></span> Characters Remaining. <span name="percent" id="percent"></span></div> </div>
Wednesday, August 7, 2013
Codeigniter Add, Edit, Delete, jquery ajax, jquery-ui
Codeigniter Add, Edit, Delete, jquery ajax, jquery-ui
Create Database Table
CREATE TABLE IF NOT EXISTS `daily` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`name` varchar(64) NOT NULL,
`amount` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
Create Controllerapplication\controllers\daily.php
Download http://bit.ly/2GXWB1S
Create Database Table
CREATE TABLE IF NOT EXISTS `daily` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`name` varchar(64) NOT NULL,
`amount` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
Create Controllerapplication\controllers\daily.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Daily extends CI_Controller { public function __construct() { parent:: __construct(); $this->load->helper("url"); $this->load->model('MDaily'); $this->load->helper('form'); } public function index(){ $data['query'] = $this->MDaily->getAll(); $this->load->view('daily/input',$data); } public function submit(){ if ($this->input->post('ajax')){ if ($this->input->post('id')){ $this->MDaily->update(); $data['query'] = $this->MDaily->getAll(); $this->load->view('daily/show',$data); }else{ $this->MDaily->save(); $data['query'] = $this->MDaily->getAll(); $this->load->view('daily/show',$data); } } } public function delete(){ $id = $this->input->post('id'); $this->db->delete('daily', array('id' => $id)); $data['query'] = $this->MDaily->getAll(); $this->load->view('daily/show',$data); } }Create Modalapplication\models\MDaily.php
<?php class MDaily extends CI_Model { function getAll(){ $this->db->select('*'); $this->db->from('daily'); $this->db->limit(50); $this->db->order_by('id','ASC'); $query = $this->db->get(); return $query->result(); } function get($id){ $query = $this->db->getwhere('daily',array('id'=>$id)); return $query->row_array(); } function save(){ $date = $this->input->post('date'); $name = $this->input->post('name'); $amount=$this->input->post('amount'); $data = array( 'date'=>$date, 'name'=>$name, 'amount'=>$amount ); $this->db->insert('daily',$data); } function update(){ $id = $this->input->post('id'); $date = $this->input->post('date'); $name = $this->input->post('name'); $amount=$this->input->post('amount'); $data = array( 'date'=>$date, 'name'=>$name, 'amount'=>$amount ); $this->db->where('id',$id); $this->db->update('daily',$data); } }Create Viewapplication\views\daily\input.php
<html lang="en-US"> <head> <title>Daily Notes</title> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" /> <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script> <script src="http://jquery-ui.googlecode.com/svn/tags/latest/external/jquery.bgiframe-2.1.2.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/i18n/jquery-ui-i18n.min.js" type="text/javascript"></script> <meta charset="UTF-8"> <style> body { font-size: 75%; } label, input { display:block; } input.text { margin-bottom:12px; width:95%; padding: .4em; } h1 { font-size: 1.2em; margin: .6em 0; } a{text-decoration:none;} {font-size:60%}; </style> <script> $(function() { $( "#dialog:ui-dialog" ).dialog( "destroy" ); $( "#dialog-confirm" ).dialog({ autoOpen: false, resizable: false, height:140, modal: true, hide: 'Slide', buttons: { "Delete": function() { var del_id = {id : $("#del_id").val()}; $.ajax({ type: "POST", url : "<?php echo site_url('daily/delete')?>", data: del_id, success: function(msg){ $('#show').html(msg); $('#dialog-confirm' ).dialog( "close" ); //$( ".selector" ).dialog( "option", "hide", 'slide' ); } }); }, Cancel: function() { $( this ).dialog( "close" ); } } }); $( "#form_input" ).dialog({ autoOpen: false, height: 300, width: 350, modal: false, hide: 'Slide', buttons: { "Add": function() { var form_data = { id: $('#id').val(), date: $('#date').val(), name: $('#name').val(), amount: $('#amount').val(), ajax:1 }; $('#date').attr("disabled",true); $('#name').attr("disabled",true); $('#amount').attr("disabled",true); $.ajax({ url : "<?php echo site_url('daily/submit')?>", type : 'POST', data : form_data, success: function(msg){ $('#show').html(msg), $('#date').val('<?php echo date('Y-m-d'); ?>'), $('#id').val(''), $('#name').val(''), $('#amount').val(''), $('#date').attr("disabled",false); $('#name').attr("disabled",false); $('#amount').attr("disabled",false); $( '#form_input' ).dialog( "close" ) } }); }, Cancel: function() { $('#id').val(''), $('#name').val(''); $('#amount').val(''); $( this ).dialog( "close" ); } }, close: function() { $('#id').val(''), $('#name').val(''); $('#amount').val(''); } }); $( "#create-daily" ) .button() .click(function() { $( "#form_input" ).dialog( "open" ); }); }); $(".edit").live("click",function(){ var id = $(this).attr("id"); var date = $(this).attr("date"); var name = $(this).attr("name"); var amount = $(this).attr("amount"); $('#id').val(id); $('#date').val(date); $('#name').val(name); $('#amount').val(amount); $( "#form_input" ).dialog( "open" ); return false; }); $(".delbutton").live("click",function(){ var element = $(this); var del_id = element.attr("id"); var info = 'id=' + del_id; $('#del_id').val(del_id); $( "#dialog-confirm" ).dialog( "open" ); return false; }); </script> </head> <body> <div id="show"> <?php $this->load->view('daily/show'); ?> </div> <p> <button id="create-daily">Input New</button> </p> <div id="form_input"> <table> <?php echo form_open('daily/submit'); ?> <input type="hidden" value='' id="id" name="id"> <tr > <td> <?php echo form_label('Date : '); ?></td> <td> <?php echo form_input('date',date('Y-m-d'),'id="date"'); ?></td> </tr> <tr> <td> <?php echo form_label('Name : ');?> </td> <td> <?php echo form_input('name','','id="name"'); ?></td> </tr> <tr> <td> <?php echo form_label('Amount : ');?> </td> <td> <?php echo form_input('amount','','id="amount"'); ?></td> </tr> </table> </div> <div id="dialog-confirm" title="Delete Item ?"> <p> <span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span> <input type="hidden" value='' id="del_id" name="del_id"> Are you sure?</p> </div> </body> </html>Create Viewapplication\views\daily\show.php
<h1>Daily Notes</h1> <table id="daily" class="ui-widget ui-widget-content" width="400px"> <tr class="ui-widget-header "> <th>No</th> <th>Date</th> <th>Name</th> <th>Amount</th> <th>Edit</th> <th>Delete</th> </tr> <? $i=0; foreach ($query as $row){ $i++; echo "<tr class=\"record\">"; echo "<td>$i</td>"; echo "<td>$row->date</td>"; echo "<td>$row->name</td>"; echo "<td>$row->amount</td>"; echo "<td><a href=\"#\" class=\"edit\" id=\"$row->id\" date=\"$row->date\" name=\"$row->name\" amount=\"$row->amount\">Edit</a></td>"; echo "<td><a class=\"delbutton\" id=\"$row->id\" href=\"#\" >Delete</a></td>"; echo "</tr>"; } ?> </table>
Download http://bit.ly/2GXWB1S
Sunday, August 4, 2013
CodeIgniter - jquery-ajax, jQueryUI - Autocomplete
CodeIgniter - jquery-ajax, jQueryUI - Autocomplete
Create Database table
CREATE TABLE `country` (
`id` smallint(5) UNSIGNED NOT NULL,
`printable_name` varchar(255) NOT NULL,
`CountryAbbrev` varchar(10) DEFAULT NULL,
`CurrencyAbbr` varchar(4) DEFAULT NULL,
`CurrencyRate` float DEFAULT NULL,
`CurrencyCode` varchar(3) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
ALTER TABLE `country`
ADD PRIMARY KEY (`id`);
ALTER TABLE `country`
MODIFY `id` smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=289;
Create Controller
application\controllers\autocomplete.php
/ Download http://bit.ly/2EaD1fA
Create Database table
CREATE TABLE `country` (
`id` smallint(5) UNSIGNED NOT NULL,
`printable_name` varchar(255) NOT NULL,
`CountryAbbrev` varchar(10) DEFAULT NULL,
`CurrencyAbbr` varchar(4) DEFAULT NULL,
`CurrencyRate` float DEFAULT NULL,
`CurrencyCode` varchar(3) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
ALTER TABLE `country`
ADD PRIMARY KEY (`id`);
ALTER TABLE `country`
MODIFY `id` smallint(5) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=289;
Create Controller
application\controllers\autocomplete.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Autocomplete extends CI_Controller { public function __construct() { parent:: __construct(); $this->load->model("MAutocomplete"); $this->load->helper("url"); $this->load->helper('form'); } public function index(){ $this->load->view('autocomplete/show'); } public function lookup(){ // process posted form data $keyword = $this->input->post('term'); $data['response'] = 'false'; //Set default response $query = $this->MAutocomplete->lookup($keyword); //Search DB if( ! empty($query) ) { $data['response'] = 'true'; //Set response $data['message'] = array(); //Create array foreach( $query as $row ) { $data['message'][] = array( 'id'=>$row->id, 'value' => $row->printable_name, '' ); //Add a row to array } } if('IS_AJAX') { echo json_encode($data); //echo json string if ajax request } else { $this->load->view('autocomplete/index',$data); //Load html view of search results } } }Create Modal application\models\MAutocomplete.php
<?php class MAutocomplete extends CI_Model{ function lookup($keyword){ $this->db->select('*')->from('country'); $this->db->like('printable_name',$keyword,'after'); $query = $this->db->get(); return $query->result(); } }Create Viewapplication\views\autocomplete\show.php
<html lang="en-US"> <head> <title>Codeigniter Autocomplete</title> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/base/jquery-ui.css" type="text/css" media="all" /> <link rel="stylesheet" href="http://static.jquery.com/ui/css/demo-docs-theme/ui.theme.css" type="text/ css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script> <meta charset="UTF-8"> <style> /* Autocomplete ----------------------------------*/ .ui-autocomplete { position: absolute; cursor: default; } .ui-autocomplete-loading { background: white url('http://jquery-ui.googlecode.com/svn/tags/1.8.2/themes/flick/images/ui-anim_basic_16x16.gif') right center no-repeat; }*/ /* workarounds */ * html .ui-autocomplete { width:1px; } /* without this, the menu expands to 100% in IE6 */ /* Menu ----------------------------------*/ .ui-menu { list-style:none; padding: 2px; margin: 0; display:block; } .ui-menu .ui-menu { margin-top: -3px; } .ui-menu .ui-menu-item { margin:0; padding: 0; zoom: 1; float: left; clear: left; width: 100%; font-size:80%; } .ui-menu .ui-menu-item a { text-decoration:none; display:block; padding:.2em .4em; line-height:1.5; zoom:1; } .ui-menu .ui-menu-item a.ui-state-hover, .ui-menu .ui-menu-item a.ui-state-active { font-weight: normal; margin: -1px; } </style> <script type="text/javascript"> $(this).ready( function() { $("#id").autocomplete({ minLength: 1, source: function(req, add){ $.ajax({ url: "<?php echo base_url(); ?>index.php/autocomplete/lookup", dataType: 'json', type: 'POST', data: req, success: function(data){ if(data.response =="true"){ add(data.message); } }, }); }, select: function(event, ui) { $("#result").append( "<li>"+ ui.item.value + "</li>" ); }, }); }); </script> </head> <body> Country : <?php echo form_input('printable_name','','id="id"'); ?> <ul> <div id="result"></div> </ul> </body> </html>View http://localhost/CODEIGNATER/autocomplete
/ Download http://bit.ly/2EaD1fA
CodeIgniter Upload Image and Resize
CodeIgniter Upload Image and Resize
Create Controller
application\controllers\upload.php
Create folder name uploads root directory
Create Controller
application\controllers\upload.php
Create folder name uploads root directory
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Upload extends CI_Controller { public function __construct() { parent:: __construct(); $this->load->helper("url"); $this->load->library('table'); $this->load->helper('form'); } public function index() { $this->load->view('upload_form'); } public function upload_success() { $this->load->view('test/upload_success'); } public function doUpload() { $config['upload_path'] = 'uploads/'; $config['allowed_types'] = 'gif|jpg|jpeg|png'; $config['max_size'] = '1000'; $config['max_width'] = '1920'; $config['max_height'] = '1280'; $this->load->library('upload', $config); if(!$this->upload->do_upload()) echo $this->upload->display_errors(); else { $fInfo = $this->upload->data(); $this->_createThumbnail($fInfo['file_name']); $data['uploadInfo'] = $fInfo; $data['thumbnail_name'] = $fInfo['raw_name'] . '_thumb' . $fInfo['file_ext']; $this->load->view('test/upload_success', $data); } } public function _createThumbnail($fileName) { $config['image_library'] = 'gd2'; $config['source_image'] = 'uploads/' . $fileName; $config['create_thumb'] = TRUE; $config['maintain_ratio'] = TRUE; $config['width'] = 75; $config['height'] = 75; $this->load->library('image_lib', $config); if(!$this->image_lib->resize()) echo $this->image_lib->display_errors(); } }Create View application\views\upload_form.php
<html> <head> <title>Upload an Image </title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <div id="container"> <h2>Upload an Image </h2> <?php echo form_open_multipart('upload/doUpload'); ?> <input type="file" name="userfile" /> <p><input type="submit" value="Submit" name="submit" /></p> <?php echo form_close(); ?> </div> </body> </html>Create View application\views\test\upload_success.php
Upload an Image Success
View http://localhost/CODEIGNATER/upload/CakePHP Add,Edit,Delete and Validate
CakePHP Add,Edit,Delete and Validate
Create Database Table
CREATE TABLE `categories` (
`id` INTEGER(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM
Crate Model app\models\category.php
Create Database Table
CREATE TABLE `categories` (
`id` INTEGER(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM
Crate Model app\models\category.php
<?php class Category extends AppModel { var $name = 'Category'; var $validate = array( //validate 'name' => array( 'rule' => 'notEmpty', 'message' => 'No, no, this field must not be empty!' ) ); } ?>Create Controller app/controllers/categories_controller.php
<?php class CategoriesController extends AppController { var $name = 'Categories'; function index() { $this->set('categories', $this->Category->find('all')); } function add() { if (!empty($this->data)) { if ($this->Category->save($this->data)) { $this->Session->setFlash('Your category has been saved.'); $this->redirect(array('action' => 'index')); } } } function delete($id) { $this->Category->delete($id); $this->Session->setFlash('The category with id: '.$id.' has been deleted.'); $this->redirect(array('action'=>'index')); } function edit($id = null) { $this->Category->id = $id; if (empty($this->data)) { $this->data = $this->Category->read(); } else { if ($this->Category->save($this->data)) { $this->Session->setFlash('Your category has been updated.'); $this->redirect(array('action' => 'index')); } } } } ?>Create View index app/view/categories/index.ctp
<!-- File: /app/views/categories/index.ctp --> <h1>Categories</h1> <?php echo $html->link('Add Category',array('controller' => 'categories', 'action' => 'add')); ?> <table> <tr> <th>Id</th> <th>Title</th> <th>Actions</th> </tr> <?php foreach ($categories as $category): ?> <tr> <td><?php echo $category['Category']['id']; ?></td> <td> <?php echo $html->link($category['Category']['name'], array('controller' => 'categories', 'action' => 'edit', $category['Category']['id'])); ?> </td> <td> <?php echo $html->link('Delete', array('action' => 'delete', $category['Category']['id']), null, 'Are you sure?' )?> <?php echo $html->link('Edit', array('action'=>'edit', $category['Category']['id']));?> </td> </tr> <?php endforeach; ?> </table>Create View Edit app/view/categories/edit.ctp
<h1>Edit Category</h1> <?php echo $form->create('Category', array('action' => 'edit')); echo $form->input('name'); echo $form->input('id', array('type'=>'hidden')); echo $form->end('Save Category'); ?>Create View add app/view/categories/add.ctp
<h1>Add Category</h1> <?php echo $form->create('Category'); echo $form->input('name'); echo $form->end('Save Post'); ?>
CakePHP Making a small application
CakePHP Making a small application
Create Database Table
Create Database Table
CREATE
TABLE
`categories` (
`id`
INTEGER
(11)
NOT
NULL
AUTO_INCREMENT,
`
name
`
VARCHAR
(255)
NOT
NULL
,
PRIMARY
KEY
(`id`)
) ENGINE=MyISAM
Create Model app\models\category.php
<?php class Category extends AppModel { var $name = 'Category'; } ?>Create Controller app\controllers\categories_controller.php
<?php class CategoriesController extends AppController { var $name = 'Categories'; function index() { $this->set('categories', $this->Category->find('all')); } function add() { if (!empty($this->data)) { if ($this->Category->save($this->data)) { $this->Session->setFlash('Your category has been saved.'); $this->redirect(array('action' => 'index')); } } } } ?>Create View index app\views\categories\index.ctp
<!-- File: /app/views/categories/index.ctp --> <?php echo $html->link('Add Category',array('controller' => 'categories', 'action' => 'add')); ?> <h1>Categories</h1> <table> <tr> <th>Id</th> <th>Title</th> </tr> <?php foreach ($categories as $category): ?> <tr> <td><?php echo $category['Category']['id']; ?></td> <td> <?php echo $html->link($category['Category']['name'], array('controller' => 'categories', 'action' => 'view', $category['Category']['id'])); ?> </td> </tr> <?php endforeach; ?> </table>Create View add app\views\categories\add.ctp
<!-- File: /app/views/categories/add.ctp --> <h1>Add Category</h1> <?php echo $form->create('Category'); echo $form->input('name'); echo $form->end('Save Post'); ?>
Saturday, August 3, 2013
Defining and Using Functions in PHP
A function is a self-contained piece of code which carries out a particular task or function. benefit of using functions is that they are reusable
<?php //Defining a Function //syntax for defining a function function addNumbers($num1, $num2) { $result = $num1 + $num2; return $result; } $total = addNumbers(5, 10); //echo $total; //result 15 //Organizing Functions function hello() { echo "<h1>HELLO!</h1>"; echo "<p>Welcome to my web site</p>"; } function printBreak($text) { echo "$text<br>"; } function addNumbers($num1, $num2) { return $num1 + $num2; } echo hello(); echo printBreak("This is a line"); echo addNumbers(3.75, 5.645); //9.39536.75 //Accepting a Variable Number of Arguments function calcAverage() { // initialize value to be used in calculation $total = 0; // find out how many arguments were given $arguments = func_num_args(); // loop to process each argument separately for ($i = 0; $i < $arguments; $i++) { // add the value in the current argument to the total $total += func_get_arg($i); } // after adding all arguments, calculate the average $average = $total / $arguments; // return the average return $average; } // invoke the function with 5 arguments //echo calcAverage(44, 55, 66, 77, 88); //output 66 // invoke the function with 8 arguments echo calcAverage(12, 34, 56, 78, 90, 9, 8, 7); //ouput 36.75
Friday, August 2, 2013
CodeIgniter show record from database
CodeIgniter show record from database
Create Table
CREATE TABLE IF NOT EXISTS `daily` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`name` varchar(64) NOT NULL,
`amount` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
Insert
INSERT INTO `daily` (`id`, `date`, `name`, `amount`) VALUES
(1, '2012-02-21', 'Kenshin', 5000),
(2, '2012-02-21', 'Naruto', 6000),
(3, '2012-02-21', 'Lufy', 7000),
(4, '2012-02-21', 'Zoro', 8000),
(5, '2012-02-21', 'Franky', 9000);
Controller
application\controllers\welcome.php
views\welcome\index.php
Create Table
CREATE TABLE IF NOT EXISTS `daily` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`date` date NOT NULL,
`name` varchar(64) NOT NULL,
`amount` double NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
Insert
INSERT INTO `daily` (`id`, `date`, `name`, `amount`) VALUES
(1, '2012-02-21', 'Kenshin', 5000),
(2, '2012-02-21', 'Naruto', 6000),
(3, '2012-02-21', 'Lufy', 7000),
(4, '2012-02-21', 'Zoro', 8000),
(5, '2012-02-21', 'Franky', 9000);
Controller
application\controllers\welcome.php
<?php class Welcome extends CI_Controller { function index(){ $this->load->library('table'); $this->load->database(); $data['records']=$this->db->get('daily'); $header = array('ID', 'Date', 'Name', 'Amount'); $this->table->set_heading($header); $this->load->view('welcome/index',$data); } }View
views\welcome\index.php
<div id="container"> <h1>Welcome to CodeIgniter!</h1> <div id="body"> <?php echo $this->table->generate($records); ?> </div> </div>
CodeIgniter Form Validation
Controller
application\controllers\welcome.php
<?php class Welcome extends CI_Controller { public function index() { //Form Validation $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->form_validation->set_rules('username', 'Username', 'required'); $this->form_validation->set_rules('password', 'Password', 'required'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); $this->form_validation->set_rules('email', 'Email', 'required'); //Validation Functions //$this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]|is_unique[users.username]'); //$this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]'); //$this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); //$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]'); if ($this->form_validation->run() == FALSE) { $this->load->view('welcome_message'); } else { $this->load->view('formsuccess'); } } }application\views\welcome_message.php
<?php echo validation_errors(); ?> <?php echo form_open('welcome'); ?> <h5>Username</h5> <input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" /> <h5>Password</h5> <input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" /> <h5>Password Confirm</h5> <input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" /> <h5>Email Address</h5> <input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" /> <div><input type="submit" value="Submit" /></div> </form>Showing Errors Individually
<h5>Username</h5> <?php echo form_error('username'); ?> <input type="text" name="username" value="<?php echo set_value('username'); ?>" size="50" /> <h5>Password</h5> <?php echo form_error('password'); ?> <input type="text" name="password" value="<?php echo set_value('password'); ?>" size="50" /> <h5>Password Confirm</h5> <?php echo form_error('passconf'); ?> <input type="text" name="passconf" value="<?php echo set_value('passconf'); ?>" size="50" /> <h5>Email Address</h5> <?php echo form_error('email'); ?> <input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
Insert – Edit – Delete Codeigniter
Insert – Edit – Delete Codeigniter
Create Database
CREATE TABLE IF NOT EXISTS `users` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`username` varchar(15) NOT NULL,
`password` text NOT NULL,
`fullname` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
)
Setup Controller
application\controllers\user.php
Create Database
CREATE TABLE IF NOT EXISTS `users` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`username` varchar(15) NOT NULL,
`password` text NOT NULL,
`fullname` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
)
Setup Controller
application\controllers\user.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class User extends CI_Controller{ /** * The __construct function is called so that I don't have to load the model each and every time. * And any change while refactoring or something else would mean change in only one place. */ function __construct() { parent::__construct(); $this->load->model('Model_user'); $this->load->library('form_validation'); $this->load->helper('form'); } function index(){ $data['query'] = $this->Model_user->getAll(); $this->load->view('view_user/input',$data); } function submit(){ if ($this->input->post('submit')){ if ($this->input->post('id')){ $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]'); $this->form_validation->set_rules('password', 'Password', 'matches[passconf]'); $this->form_validation->set_rules('fullname', 'Fullname', 'required|min_length[5]|max_length[25]'); if ($this->form_validation->run() == FALSE){ $data['id'] = $this->input->post('id'); $data['username'] = set_value('username'); $data['fullname'] = set_value('fullname'); $this->load->view('view_user/edit',$data); }else{ $this->Model_user->update(); redirect('view_user/index'); } }else{ $this->form_validation->set_rules('username', 'Username', 'required|min_length[5]|max_length[12]'); $this->form_validation->set_rules('password', 'Password', 'required|matches[passconf]'); $this->form_validation->set_rules('passconf', 'Password Confirmation', 'required'); $this->form_validation->set_rules('fullname', 'Fullname', 'required|min_length[5]|max_length[25]'); if ($this->form_validation->run() == FALSE){ $data['query'] = $this->Model_user->getAll(); $this->load->view('view_user/input',$data); }else{ $this->Model_user->save(); redirect('user/index'); } } } } function edit(){ $id=$this->uri->segment(3); $data['result']=$this->Model_user->getUser($id); if (empty($id) or count($data['result'])==0 ){ redirect('user/index'); }else{ $result=$this->Model_user->getUser($id); $data['id'] = $result['id']; $data['username'] = $result['username']; $data['fullname'] = $result['fullname']; $this->load->view('view_user', $data); } } function delete($id){ $this->db->delete('user', array('id' => $id)); redirect('user/index'); } }Model application\models\Model_user.php
<?php class Model_user extends CI_Model{ function getAll(){ $this->db->select('id,username,fullname'); $this->db->from('users'); $this->db->limit(10); $this->db->order_by('id','ASC'); $query = $this->db->get(); return $query->result(); } function getUser($id){ $this->db->where('id', $id); $query = $this->db->get('users'); return $query->row_array(); } function save(){ $username = $this->input->post('username'); $password = $this->input->post('password'); $fullname = $this->input->post('fullname'); $data = array( 'username'=>$username, 'password'=>md5($password), 'fullname'=>$fullname ); $this->db->insert('users',$data); } function update(){ $id = $this->input->post('id'); $username = $this->input->post('username'); $password = $this->input->post('password'); $fullname = $this->input->post('fullname'); if ($password==''){ $data = array( 'username'=>$username, 'fullname'=>$fullname ); }else{ $data = array( 'username'=>$username, 'password'=>md5($password), 'fullname'=>$fullname ); } $this->db->where('id',$id); $this->db->update('users',$data); } }View application\views\view_user\input.php
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Data User</title> </head> <body> <div id="form_input" title="Input / Edit Data"> <table> <?php echo validation_errors(); ?> <?php echo form_open('user/submit'); ?> <tr > <td> <?php echo form_label('User Name : '); ?></td> <td> <?php echo form_input('username',set_value('username'),'id="username"'); ?></td> </tr> <tr> <td> <?php echo form_label('Password : ');?> </td> <td> <?php echo form_password('password','','id="password"'); ?></td> </tr> <tr> <td> <?php echo form_label('Repeat Password : ');?> </td> <td> <?php echo form_password('passconf','','id="passconf"'); ?></td> </tr> <tr> <td> <?php echo form_label('Full Name : ');?> </td> <td> <?php echo form_input('fullname', set_value('fullname'),'id="fullname"'); ?></td> </tr> <tr> <td><?php echo form_submit('submit','Save')?> </tr> </table> </div> <div id="show"> <?php $this->load->view('view_user/show'); ?> </div> </div> </body> </html>application\views\view_user\show.php
<?php if (isset($query) && count($query) > 0){ ?> <h1>Data User</h1> <table width="400" border="1"> <tr > <th>No</th> <th>Username</th> <th>Fullname</th> <th>Edit</th> <th>Delete</th> </tr> <?php $i=0; foreach ($query as $row){ $i++; echo "<tr class=\"record\">"; echo "<td>$i</td>"; echo "<td>$row->username</td>"; echo "<td>$row->fullname</td>"; echo "<td><a href=".base_url()."index.php/user/edit/$row->id>Edit</a></td>"; echo "<td><a href=".base_url()."index.php/user/delete/$row->id>Delete</a></td>"; echo "</tr>"; } ?> </table> <?php } ?>
Simple Login with CodeIgniter in PHP
Create the database
CREATE TABLE `users` (
`id` tinyint(4) NOT NULL AUTO_INCREMENT,
`username` varchar(10) NOT NULL,
`password` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
insert into users (username, password) values ('admin', MD5('password'));
Configure CodeIgniter
application/config/database.php
Default Controller
application/config/routes.php
call landing controller login $route['default_controller'] = "login";
Default Libraries
application/config/autoload.php
handle user sessions, and also the URL helper for internal link generation
$autoload['libraries'] = array('database','session');
$autoload['helper'] = array('url');
Encryption Key
application/config/config.php
$config['encryption_key'] = 'REALLY_LONG_NUMBER';
The Code
User Model (application/models/user.php)
<?php Class User extends CI_Model { function login($username, $password) { $this -> db -> select('id, username, password'); $this -> db -> from('users'); $this -> db -> where('username', $username); $this -> db -> where('password', MD5($password)); $this -> db -> limit(1); $query = $this -> db -> get(); if($query -> num_rows() == 1) { return $query->result(); } else { return false; } } } ?>Login Controller (application/controllers/login.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Login extends CI_Controller { function __construct() { parent::__construct(); } function index() { $this->load->helper(array('form')); $this->load->view('login_view'); } } ?>Login View (application/views/login_view.php)
<h1>Simple Login with CodeIgniter</h1> <?php echo validation_errors(); ?> <?php echo form_open('verifylogin'); ?> <label for="username">Username:</label> <input type="text" size="20" id="username" name="username"/> <br/> <label for="password">Password:</label> <input type="password" size="20" id="passowrd" name="password"/> <br/> <input type="submit" value="Login"/> </form>VerifyLogin Controller (application/controllers/verifylogin.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class VerifyLogin extends CI_Controller { function __construct() { parent::__construct(); $this->load->model('user','',TRUE); } function index() { //This method will have the credentials validation $this->load->library('form_validation'); $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean'); $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database'); if($this->form_validation->run() == FALSE) { //Field validation failed. User redirected to login page $this->load->view('login_view'); } else { //Go to private area redirect('home', 'refresh'); } } function check_database($password) { //Field validation succeeded. Validate against database $username = $this->input->post('username'); //query the database $result = $this->user->login($username, $password); if($result) { $sess_array = array(); foreach($result as $row) { $sess_array = array( 'id' => $row->id, 'username' => $row->username ); $this->session->set_userdata('logged_in', $sess_array); } return TRUE; } else { $this->form_validation->set_message('check_database', 'Invalid username or password'); return false; } } } ?>Home Controller (application/controllers/home.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); session_start(); //we need to call PHP's session object to access it through CI class Home extends CI_Controller { function __construct() { parent::__construct(); } function index() { if($this->session->userdata('logged_in')) { $session_data = $this->session->userdata('logged_in'); $data['username'] = $session_data['username']; $this->load->view('home_view', $data); } else { //If no session, redirect to login page redirect('login', 'refresh'); } } function logout() { $this->session->unset_userdata('logged_in'); session_destroy(); redirect('home', 'refresh'); } } ?>Home Page View (application/views/home_view.php)
<html> <head> <title>Simple Login with CodeIgniter - Private Area</title> </head> <body> <h1>Home</h1> <h2>Welcome <?php echo $username; ?>!</h2> <a href="home/logout">Logout</a> </body> </html>
How to enable or disable an anchor using jQuery
How to enable or disable an anchor using jQuery
To prevent an anchor from following the specified href
$(document).ready(function() { $('a.something').click(function(e) { e.preventDefault(); }); });
Passing array of checkbox values to php through jQuery
Passing array of checkbox values to php through jQuery
//index.hmtl <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> function doit() { var p=[]; $('input.cb').each( function() { if($(this).attr('checked')) { p.push($(this).attr('rel')); } } ); $.ajax( { url:'process.php', type:'POST', data: {list:p}, success: function(res) { alert(res); } }); } </script> <input type="checkbox" class="cb" rel="1"></input>Test 1<br /> <input type="checkbox" class="cb" rel="2"></input>Test 2<br /> <input type="checkbox" class="cb" rel="3"></input>Test 3<br /> <a href="javascript:void(0)" onclick="doit()">Click</a>
//process.php <?php print_r(@$_POST['list']); ?>
Subscribe to:
Posts (Atom)