Sort by today, this week, this month

$by=trim($_REQUEST[‘by’]);
if($by==’today’) { $cond.=” and DATE(activity_crtd)='”.date(“Y-m-d”).”‘”; }
if($by==’week’) { $cond.=” and YEARWEEK(activity_crtd) = YEARWEEK(‘”.date(“Y-m-d”).”‘) “; }
if($by==’month’) { $cond.=” and YEAR(activity_crtd) = ‘”.date(“Y”).”‘ and MONTH(activity_crtd) = ‘”.date(“m”).”‘ “; }

$qry = “select * from `table_name` where status=’Active’ “.$cond
    
<select onchange=”window.location=’my_profile.php?by=’+this.value” name=””>
<option value=”all”>All </option>
<option value=”today”>Today</option>
<option value=”week”>This Week</option>
<option value=”month”>This Month </option>
</select>

MySql commit and rollback using php

First crate table using InnoDB storage engine of MySql.

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;

<?php
$link = mysqli_connect("localhost", "root", "", "transaction");

/* check connection */
if (!$link) {
echo "Connect failed: ".mysqli_connect_error();
exit();
}

// set autocommit to off //
mysqli_autocommit($link, FALSE);

// Insert some values //
mysqli_query($link, "INSERT INTO users VALUES ('', 'Avi')");
mysqli_query($link, "INSERT INTO users VALUES ('', 'Sourav')");

// commit transaction //
$comm = mysqli_rollback($link);
$comm = mysqli_commit($link);
if (!$comm) {
echo "Transaction commit failed";
exit();
} else {
echo "Transaction committed";
}

// close connection //
mysqli_close($link);
?>

Order By Mysql

Reorder table using single query with php, jquery UI, MySql

Script

<script>

$(function() {

$( "#sortable" ).sortable({
update: function( event, ui ) {
var sortedIDs = $( "#sortable" ).sortable( "toArray" );

$.ajax({
type: "POST",
url: "general_ajax.php",
data: { mode: "SortMustKnows", sortedIDs: sortedIDs },
success : function(data){
alert( data );
}
});
}
});

$( "#sortable" ).disableSelection();
});

</script>

HTML

<ul id="sortable">

<li id="1"><span></span>Item 1</li>
<li id="2"><span></span>Item 2</li>
<li id="3"><span></span>Item 3</li>
<li id="4"><span></span>Item 4</li>
<li id="5"><span></span>Item 5</li>

</ul>

Mysql Query

$sortedIDs = '5,4,3,2,1';
@mysql_query("SELECT @i:=0;");
@mysql_query("UPDATE `table_name` SET  must_order = @i:=@i+1 where `primary_key` IN ($sortedIDs) ORDER BY FIELD(`primary_key`,$sortedIDs)");

Gmap API

Save this file as index.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps AJAX + mySQL/PHP Example</title>
http://maps.google.com/maps/api/js?sensor=false

//

var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};

function load() {
var map = new google.maps.Map(document.getElementById("map"),
{
center: new google.maps.LatLng(22.6343422, 88.3385809),
zoom: 13,
mapTypeId: 'roadmap'
}
);

var infoWindow = new google.maps.InfoWindow;

// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml_1.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i " + name + "
" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}

function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}

function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;

request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};

request.open('GET', url, true);
request.send(null);
}

function doNothing() {}

//]]>

</head>

<body onLoad="load()">

</body>
</html>

Create a new file as phpsqlajax_genxml_1.php
<?php
//require("phpsqlajax_dbinfo.php");

// get long lat data from google..
//http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false
// PWD Rd, Bally Howrah, WB 711205

function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}

// Opens a connection to a MySQL server
/*$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}*/

// Set the active MySQL database
/*$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
*/
// Select all the rows in the markers table
/*$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}*/

header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<markers>';

// Iterate through the rows, printing XML nodes for each
//while ($row = @mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
echo 'name="' . parseToXML("Belur Math") . '" ';
echo 'address="' . parseToXML("Belur Math, Belur, Howrah, West Bengal") . '" ';
echo 'lat="22.6343422" ';
echo 'lng="88.3385809" ';
echo 'type="restaurant" ';
echo '/>';

echo '<marker ';
echo 'name="' . parseToXML("Bally Ghat") . '" ';
echo 'address="' . parseToXML("PWD Rd, Bally Howrah, WB 711205") . '" ';
echo 'lat="22.6527382" ';
echo 'lng="88.3414109" ';
echo 'type="bar" ';
echo '/>';

//}

// End XML file
echo '</markers>';

?>

Now run the index.php

Public Private Protected variable concepts

private – can be accessed from WITHIN the class only

protected – can be accessed from WITHIN the class and INHERITING classes

public – can be accessed from code OUTSIDE the class as well

<?php
/**
* Define MyClass
*/
class MyClass
{
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';

function printHello()
{
echo $this->public;
echo ‘<br>’;
echo $this->protected;
echo ‘<br>’;
echo $this->private;
echo ‘<br>’;
}
}

//$obj = new MyClass();
//echo $obj->public; // Works
//echo $obj->protected; // Fatal Error
//echo $obj->private; // Fatal Error
//$obj->printHello(); // Shows Public, Protected and Private

/**
* Define MyClass2
*/
class MyClass2 extends MyClass
{
// We can redeclare the public and protected method, but not private
protected $protected = ‘Protected2’;

function printHello2()
{
echo $this->public;
echo ‘<br>’;
echo $this->protected;
echo ‘<br>’;
echo $this->private;
echo ‘<br>’;
}
}

$obj2 = new MyClass2();
//echo $obj2->public; // Works
//echo $obj2->private; // Undefined
//echo $obj2->protected; // Works
$obj2->printHello2(); // Shows Public, Protected2, Undefined

?>

Numaric Captcha

<?php

session_start();

function generate_equation() {
$firstnum = rand(5,8);
$secondnum = rand(1,4);
$coinflip = rand(1,2) % 2;
if($coinflip == 0) {
$math = $firstnum + $secondnum;
$operator = array("+");
} else {
$math = $firstnum - $secondnum;
$operator = array("-");
}

$_SESSION['captcha_equation'] = $firstnum . " " . $operator[0] . " " . $secondnum . " = ";
$_SESSION['captcha_answer'] = $math;

return( $_SESSION['captcha_equation'] );
}

?>

XLS Export

<?php
set_time_limit(0);
require_once(“../includes/connection.php”);
adminSecure();

function xlsBOF() {
echo pack(“ssssss”, 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
// Excel end of file footer
function xlsEOF() {
echo pack(“ss”, 0x0A, 0x00);
return;
}
// Function to write a Number (double) into Row, Col
function xlsWriteNumber($Row, $Col, $Value) {
echo pack(“sssss”, 0x203, 14, $Row, $Col, 0x0);
echo pack(“d”, $Value);
return;
}
// Function to write a label (text) into Row, Col
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack(“ssssss”, 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}

////////////////////////////////////////////////////////////

header(“Pragma: public”);
header(“Expires: 0”);
header(“Cache-Control: must-revalidate, post-check=0, pre-check=0”);
header(“Content-Type: application/force-download”);
header(“Content-Type: application/octet-stream”);
header(“Content-Type: application/download”);;
header(“Content-Disposition: attachment;filename=product.xls”);
header(“Content-Transfer-Encoding: binary “);

xlsBOF();

$data_array = array(
“product_name”,
“brand_id”,
“style_id”,
“frame_id”,
“gender_id”,
“size_id”,
“eyesize_id”,
“bridgesize_id”,
“templelength_id”,
“option_color”,
“option_price”,
“product_url”,
“image_url”,
);

$header_array = array(
“Name”,
“Brand”,
“Style”,
“Frame”,
“Gender”,
“Size”,
“Eyesize”,
“Bridgesize”,
“Templelength”,
“Color”,
“Price”,
“Product Url”,
“Image Url”
);

foreach($header_array as $key => $value){
xlsWriteLabel(0,$key,$value);
}

$k = 2;

$res1 = $obj->selectData(TABLE_PRODUCT.” as p”,””,”p.product_id > 0 and p.product_status=’Active’ order by p.product_added desc”,””);
while($data1 = mysql_fetch_array($res1)){

$res2 = $obj->selectData(TABLE_PRODUCT_OPTION.” as po”,””,”po.option_status=’Active’ and po.product_id='”.$data1[‘product_id’].”‘”,””);
while($data2 = mysql_fetch_array($res2)){

$option_image = $obj->selectData(TABLE_PRODUCT_OPTION_IMAGE.” as poi”,””,”poi.image_status=’Active’ and poi.option_id='”.$data2[‘option_id’].”‘ and poi.option_extra_image<>” limit 1″,1);

$image_url = FURL.PRODUCT_IMAGES.$option_image[‘option_extra_image’];
$product_url = FURL.”products_detail.php?p_id=”.$data2[‘product_id’].”&o_id=”.$data2[‘option_id’].””;

foreach($data_array as $key => $value){
if($value == “product_name”){
xlsWriteLabel($k,$key,$data1[$value]);
} else if($value == “brand_id”){
xlsWriteLabel($k,$key,$obj->getBrandName($data1[$value]));
} else if($value == “style_id”){
xlsWriteLabel($k,$key,$obj->getProductStyle($data1[$value]));
} else if($value == “frame_id”){
xlsWriteLabel($k,$key,$obj->getFrameName($data1[$value]));
} else if($value == “gender_id”){
xlsWriteLabel($k,$key,$obj->getGenderName($data1[$value]));
} else if($value == “size_id”){
xlsWriteLabel($k,$key,$obj->getProductSize($data1[$value]));
} else if($value == “eyesize_id”){
xlsWriteLabel($k,$key,$obj->getProductEyeSize($data1[$value]));
} else if($value == “bridgesize_id”){
xlsWriteLabel($k,$key,$obj->getProductBridgeSize($data1[$value]));
} else if($value == “templelength_id”){
xlsWriteLabel($k,$key,$obj->getProductTempleLength($data1[$value]));
} else if($value == “product_url”){
xlsWriteLabel($k,$key,$product_url);
} else if($value == “image_url”){
xlsWriteLabel($k,$key,$image_url);
} else {
xlsWriteLabel($k,$key,$data2[$value]);
}
}
$k++;
}
}

xlsEOF();
/////////////////////////////////////////////////////

?>

Google Translate

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<meta name="google-translate-customization" content="4bc028f58847675b-c4dbfa7ae83c6fb9-gaade28b55526543d-19"></meta>

function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: ‘en’, layout: google.translate.TranslateElement.InlineLayout.SIMPLE},
‘google_translate_element’);
}
http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit

</head>

<body>

</body>
</html>

Post hit counter

get_results( "SELECT ID,post_title,post_date,post_content,post_excerpt,meta_value as views FROM $wpdb->posts p JOIN $wpdb->postmeta pm ON p.ID = pm.post_id WHERE meta_key = 'post_views_count' AND meta_value != '' AND post_status = 'publish' AND post_type='post' GROUP BY p.ID ORDER BY ( meta_value+0 ) DESC LIMIT 5" );
echo '

    ';
    foreach( $viewed as $post ){
    $categories = get_the_category($post->ID);
    ?>
    <li>
    <span class="username"></span> <a href="ID); ?>" class="clearfix">cat_name;?><span class="title">post_title;?></span></a>

    post_content)),0,100);?>...

    </li>

RSS feed structure

<?xml version='1.0' encoding='UTF-8'?>
<rss version='2.0'>
<channel>

<title>Website Title </title>
<link>Website URL</link>
<description>Website description</description>
<language>en-us</language>

<item>
<title>Item/Article Title</title>
<link>Item/Article URL </link>
<description>Items/Article description </description>
</item>

</channel>
</rss>