Tuesday, September 14, 2010

PreparedStatement in java with update

PreparedStatement in java with update sql statement:
Here listed below code for update the record using PreparedStatementin java


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.text.*" %>

String userName = "root",password = "",url = "jdbc:mysql://localhost:3306/test",
driver = "com.mysql.jdbc.Driver";
String siteUrl="http://localhost:8080/demo/";
Connection conn=null;
try {
    Class.forName(driver).newInstance();
    conn = DriverManager.getConnection(url, userName,password);
}catch(Exception ee) {
    out.print("There are some problems");
    out.print(ee.toString());
Systen.exit(0);
}

String acDecMsg="";
String sqlAdminActDea=null;
if(request.getParameter("admin_id")!=null && request.getParameter("stat")!=null) {
    int d_admin_id=Integer.parseInt(request.getParameter("admin_id").toString());
    int stat=Integer.parseInt(request.getParameter("stat").toString());
    if(d_admin_id!=1) {
        PreparedStatement psAdminActDea= null;
        sqlAdminActDea="Update admin_info set active_stat=? , update_date=? where admin_id=?";
        psAdminActDea = conn.prepareStatement(sqlAdminActDea);
        psAdminActDea.setInt(1,stat);
        psAdminActDea.setTimestamp(2, new java.sql.Timestamp( now.getTime()) );
        psAdminActDea.setInt(3,d_admin_id);
        if(psAdminActDea.executeUpdate()>0) {
            acDecMsg=stat>0?"<font color='green'><b>Record activated.</b></font>":"<font color='green'><b>Record deactivated.</b></font>";
        } else {
            acDecMsg="<font color='red'><b>This record not found.</b></font>";
        }
        psAdminActDea.close();
        psAdminActDea=null;
    } else {
        acDecMsg="<font color='red'><b>You can not make active/deactive your self.</b></font>";
    }
}

Current date validation in javascript

Current date validation in javascript

<script>
var month=9,day=5,year=2012;
var dateNow = new Date();
dateNow=new Date((dateNow.getMonth()+1)+"/"+dateNow.getDate()+"/"+dateNow.getFullYear());
var Date2 = new Date(month+"/"+day+"/"+year);

if (Date2 >= dateNow)
{
  alert('yes');
}
</script>

Monday, September 13, 2010

PreparedStatement in java with select


PreparedStatement in java with select sql statement:
Here listed below code for select the records using PreparedStatementin java

<%@ page import="java.sql.*" %>
<%@ page import="java.util.Date" %>
<%@ page import="java.text.*" %>

String userName = "root",password = "",url = "jdbc:mysql://localhost:3306/test",driver = "com.mysql.jdbc.Driver";
Connection conn=null;
try {
    Class.forName(driver).newInstance();
    conn = DriverManager.getConnection(url, userName,password);
}catch(Exception ee) {
    out.print("There are some problems");
    out.print(ee.toString());
}
String sqlAdminTypeList="select *from admin_type order by admin_type_text";
PreparedStatement psAdminTypeList= null;
psAdminTypeList = conn.prepareStatement(sqlAdminTypeList);
ResultSet rsAdminTypeList=psAdminTypeList.executeQuery();
StringBuilder sbAdminTypeList=new StringBuilder();
while(rsAdminTypeList.next()) {
sbAdminTypeList.append("<option value=\""+rsAdminTypeList.getInt("admin_type_id")+"\">"+rsAdminTypeList.getString("admin_type_text")+"</option>");
}
rsAdminTypeList.close();
rsAdminTypeList=null;

Thursday, August 19, 2010

Add a new record in existing XML file

Add a new record in existing XML file



The xml file having the columns as listed below:
ID,author,title,url



full xml file's format is listed below:

blogs.xml
=====================================================
<?xml version="1.0"?>
<blogs>
    <article>
        <ID>1</ID>
      <author>Amit</author>
      <title>Auto Resume Broken Progress Bar File Uploader Applet</title>
      <url>http://amitkgaur.blogspot.com/2010/10/file-upload-applet-with-auto-resume.html</url>
  </article>
    <article>
        <ID>2</ID>
      <author>Amit</author>
      <title>Screen Recorder</title>
      <url>http://amitkgaur.blogspot.com/2010/09/desktop-screen-recorder.html</url>
  </article>
</blogs>
=====================================================


and you want to add a new record(s), then use the listed below my php code.
You need to change it according your requirements.

addNew.php
=====================================================
<?php
$fullXmlFile="blogs.xml";

$ID="3";
$author="Amit Gaur";
$title="How to get clipboard data from webpage.";
$url="http://amitkgaur.blogspot.com/2011/06/how-to-get-clipboard-data-from-webpage.html";

$xmlObj = simplexml_load_file($fullXmlFile);
$sxeObj = new SimpleXMLElement($xmlObj->asXML());
$articleObj = $sxeObj->addChild("article");
$articleObj->addChild("ID", $ID);
$articleObj->addChild("author", $author);
$articleObj->addChild("title", $title);
$articleObj->addChild("url", $url);
$sxeObj->asXML($fullXmlFile);

The above code will add the new record at the last position in the xml file.
=====================================================





Wednesday, August 18, 2010

Google chart api 3d

Here is the simple example of Google 3d chart. just use listed below code.
I have everything explained in commented.

Google 3D chart
Google 3D Chart.















<html>
<head>
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<script type="text/javascript">
    // Load Google Visualization API with piechart package.
    google.load('visualization', '1', {'packages':['piechart', 'imagepiechart', 'barchart','imageBarChart','linechart']});
    // load API.
    google.setOnLoadCallback(initChart);
    // Populates datas and draw it.
    function initChart() {
        var dTable = new google.visualization.DataTable();
        // Add two columns
        dTable.addColumn('string', 'Names');
        dTable.addColumn('number', 'Percentage');
       
        //Add fie rows
        dTable.addRows(5);
       
        //set the 5 values
        dTable.setValue(0, 0, 'Java');
        dTable.setValue(0, 1, 50);
       
        dTable.setValue(1, 0, 'ASP.Net');
        dTable.setValue(1, 1, 30);
       
        dTable.setValue(2, 0, 'PHP');
        dTable.setValue(2, 1,10);
       
        dTable.setValue(3, 0, 'ASP');
        dTable.setValue(3, 1, 7);
       
        dTable.setValue(4, 0, 'Java Applet');
        dTable.setValue(4, 1, 3);
        //draw it   
        var pChart = new google.visualization.PieChart(document.getElementById('programmingLanguages3DChart'));
        pChart.draw(dTable, {width: 400, height: 240, is3D: true, title: 'Programming Languages 3D Chart'});
    }
</script>
</head>
<body>
    <div id='programmingLanguages3DChart' ></div>
</body>
</html>

Thursday, August 12, 2010

Search any word in entire tables of mysql database

Search any word in entire tables of mysql database

Suppose there are lot of tables in the database. and you want to search a word or sentence in the tables.
For this you need to look into each table, which having varchar or text or any character based type fields.
It is very lazy, tough and time killing task to look into each table for those fields manually and then generate it's sql manually.

I have recently worked on this type of task,so I have created this PHP code. It will show the sql in where it will find the search term. You can convert it in any other sql for example sql server, oracle etc.



 <?php

class DBUtil {
    public $utilMySqlServerIP;
    public $utilDB ;
    public $utilUser;
    public $utilPass;
    public $link,$isDBConnect;
    public function __construct() {
        $this->utilMySqlServerIP = "localhost"; $this->utilUser = "root"; $this->utilPass = "";
        $this->utilDB = "realated_se4"; $this->utilAns=false;
        try {
            $this->link = mysql_connect($this->utilMySqlServerIP, $this->utilUser, $this->utilPass);
            if (!is_resource($this->link)) { $this->isDBConnect=false; }
            else { $this->isDBConnect=true; }
            mysql_select_db($this->utilDB,$this->link);
        } catch(Exception $ee) { $this->link=false; }
    }
  
    public function showTableNames() {
        try    {
            $result = mysql_query("show tables", $this->link);
            if(mysql_num_rows($result)>0) { return $result; } else { return false; }  
        } catch(Exception $ee) { return (false); }
    }
  
    public function showTableColumn($tblName) {
        try    {
            $result = mysql_query("SHOW COLUMNS FROM ".$tblName, $this->link);
            if(mysql_num_rows($result)>0) { return $result; } else { return false; }  
        } catch(Exception $ee) { return (false); }
    }
    public function exeQuery($query, $isPrint=0) {
        try    {
            if($isPrint==1) { echo $query; }
            $result = mysql_query($query, $this->link);
            if(mysql_num_rows($result)>0) { return $result; } else { return false; }  
        } catch(Exception $ee){ return (false); }
    }
    public function __destruct() { }
}

////////////////////////////////////////////////////////
$db=new DBUtil();
$tbRs=$db->showTableNames();
$term="search term";
$number=0;
$tmpSql=" select [COLS] from [TABLENAME] where [WHERES]";
while($tbName = mysql_fetch_array($tbRs, MYSQL_BOTH)) {
    $colRs=$db->showTableColumn($tbName[0]);
    $startSql=$tmpSql; $fnd=0; $comma=",";     $cols=""; $where="";
    while($col = mysql_fetch_array($colRs,MYSQL_BOTH)) {
         $vFound=stripos($col[1], "varchar");
        $tFound=stripos($col[1], "text");
        $charFound=stripos($col[1], "char");
        $longFound=stripos($col[1], "longtext");
        $mediumFound=stripos($col[1], "mediumtext");
        $tinyFound=stripos($col[1], "tinytext");
      
        if($vFound!== false || $tFound!== false || $charFound!== false || $longFound!== false || $mediumFound!== false || $tinyFound!== false ) {
            if($fnd==0) {
                $fnd=1;      $cols.="`".$col[0]."`";  $where.= "`".$col[0]."`"." like '%".$term."%' ";
            } else {
                $cols.=","."`".$col[0]."`";      $where.=" or "."`". $col[0] ."`"." like '%".$term."%' ";
            }
        }
    }
    $startSql=str_replace("[TABLENAME]", $tbName[0], str_replace("[WHERES]", $where, str_replace("[COLS]", $cols, $startSql)));
    if(stripos($startSql,"like '%")!== false) {
        $rs=$db->exeQuery($startSql, 0);
        if($rs) { echo "<p></p>[".(++$number)."]== ".$startSql."<hr>";    }
    }
}
?>

Post data in Facebook wall

Post data in Facebook wall


 Just wait for the PHP page, that will post your message(s) in facebook wall.....




 

Get mac address ip address in jsp java

Get MAC address (Physical Address) and IP Address of client machine in jsp java

How to get MAC address (Physical Address) and IP Address of client machine.
listed below code that is show client machine's MAC address
(Physical Address) and IP Address.

use listed below code and you will find something like that:

100.202.202.201
11-26-7Z-50-89-9B

 The "100.202.202.201" is the IP Address and "11-26-7Z-50-89-9B" is the
Mac Address of the client machine.


import these packages:

<%@ page import="java.net.*" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>


<%
InetAddress inetAddress;
StringBuilder sb = new StringBuilder();
String ipAddress="",macAddress="";
int i=0;
try {
    inetAddress=InetAddress.getLocalHost();
    ipAddress=inetAddress.getHostAddress();
    NetworkInterface network=NetworkInterface.getByInetAddress(inetAddress);
     byte[] hw=network.getHardwareAddress();
    for(i=0; i<hw.length; i++)
        sb.append(String.format("%02X%s", hw[i], (i < hw.length - 1) ? "-" : ""));   
    macAddress=sb.toString();
} catch(Exception e) {
    out.print("<br/>"+e.toString());
    macAddress="-";
}
out.print("<br/>"+ipAddress);
out.print("<br/>"+macAddress);
%>

Wednesday, August 11, 2010

Check if an element exists in jQuery

Check if an element exists in jQuery


Some times you need to check element in jQuery that is it exists or not

you can use listed below code:


if ($('#txtID).length) { 
        // put here your code 
    } 

Tuesday, July 27, 2010

Another way to clear FCKeditor value in javascript

Another way to clear FCKeditor value in javascript.
===================================================
Here I am telling you another way that how can you only clear FCKeditor value in javascript.
Assuming the you are using PHP as a server type script.

<?php
include_once("FCKeditor/fckeditor.php") ;
$sBasePath = "FCKeditor/" ;
// instance name as FCKeditor1
$oFCKeditor = new FCKeditor('FCKeditor1') ; 
$oFCKeditor->BasePath = $sBasePath ;
$oFCKeditor->Value = "test data";
$oFCKeditor->Create() ;
?>

<input name="resetButton" type="button" title="Reset" onclick="doClear();"  value="Reset"/>
<script>
function doClear(){
     var MyFCKeditor___Frame=document.getElementById("FCKeditor1___Frame");
     MyFCKeditor___Frame.src="FCKeditor/editor/fckeditor.html?InstanceName=FCKeditor1&Toolbar=Default";
    return false;
}
</script>


Note that, use same name/id in javascript here I am using "FCKeditor1" as a name.

Thursday, July 22, 2010

Show facebook bio and fan list.

Show facebook bio and fan list.

Here is the listed below link, click on it and find your
facebook bio with fan list

Show facebook bio and fan list.

Wednesday, July 21, 2010

event delegation in jQuery

event delegation in jQuery




$("#btnId").click(function(){
    // put your code here ;
});

Download gmail attachment in PHP

Download gmail attachment in PHP

If you want to download gmail attachment by PHP code?,  then here is the code that will do it.
just copy and paste the entire code and run it.



<?php
class ImapMail
{
    var $dirPath,$deleteEmails=false;
    var $imapInBox;
    function __construct($mailHost,$emailLogin,$pass) {
        $this->imapInBox=imap_open($mailHost,$emailLogin,$pass) or die("Unable to connect:".imap_last_error());
    }
    function getdecodevalue($msg,$bodyType) {
        if($bodyType==0 || $bodyType==1) {
            $msg = imap_base64($msg);
        }
        if($bodyType==2) {
            $msg = imap_binary($msg);
        }
        if($bodyType==3 || $bodyType==5) {
            $msg = imap_base64($msg);
        }
        if($bodyType==4) {
            $msg = imap_qprint($msg);
        }
        return $msg;
    }

    function downLoadAttachment($dirPath,$deleteEmails=false) {
        $nAttachment = 0;
        $dirPath = str_replace('\\', '/', $dirPath);
        if (substr($dirPath, strlen($dirPath) - 1) != '/') {
            $dirPath .= '/';
        }
        $message = array();
        $message["attachment"]["type"][0] = "text";
        $message["attachment"]["type"][1] = "multipart";
        $message["attachment"]["type"][2] = "message";
        $message["attachment"]["type"][3] = "application";
        $message["attachment"]["type"][4] = "audio";
        $message["attachment"]["type"][5] = "image";
        $message["attachment"]["type"][6] = "video";
        $message["attachment"]["type"][7] = "other";
       
        $nEmails = imap_search($this->imapInBox, 'ALL', SE_UID);
        $j=-1;
        for ($j = 0; $j < count($nEmails); $j++) {
            $j++;
            $messStructure = imap_fetchstructure($this->imapInBox, $nEmails[$j] , FT_UID);
            $overview = imap_fetch_overview($this->imapInBox,$j ,0);
        echo '<span>Read/Unread'.($overview[0]->seen ? 'read' : 'unread').'</span>';
        echo  '<span>Subject:: '.$overview[0]->subject.'</span> ';
        echo  '<span>From:: '.$overview[0]->from.'</span>';
        echo '<span>On:: '.$overview[0]->date.'</span>';
            $body = imap_fetchbody($this->imapInBox,$j ,2);
            echo $body;
            if(isset($messStructure->parts)) {
                $parts = $messStructure->parts;
                $fpos=2;
                for($i = 1; $i < count($parts); $i++) {
                $message["pid"][$i] = ($i);
                $part = $parts[$i];
                if(isset($part->disposition) && $part->disposition == "ATTACHMENT") {
                    $message["type"][$i] = $message["attachment"]["type"][$part->type] . "/" . strtolower($part->subtype);
                    $message["subtype"][$i] = strtolower($part->subtype);
                    $fileName=$part->dparameters[0]->value;
                    $mess = imap_fetchbody($this->imapInBox,$j+1,$fpos); 
                    $fp=fopen($dirPath.$fileName, 'w');
                    $data=$this->getdecodevalue($mess,$part->type);   
                    fwrite($fp,$data);
                    fclose($fp);
                    $nAttachment++;
                    $fpos+=1;
                }
            }
                if ($this->deleteEmails) {
                    //imap_delete($this->imapInBox,$j+1);
                }
            }
        }
        if ($this->deleteEmails) {
            //imap_expunge($this->imapInBox);
        }
        imap_close($this->imapInBox);
        return ("Completed ($nAttachment attachment(s) downloaded into $dirPath)");
    }
}

$mailHost="{imap.gmail.com:993/imap/ssl}INBOX";
$emailLogin="FULL-GMAIL-ID-HERE";
$pass="PASSWORD-HERE";
$dirPath=$_SERVER['DOCUMENT_ROOT']."test/gmail/";
$deleteEmails=false;
$mailObj=new ImapMail($mailHost,$emailLogin,$pass);
echo $mailObj->downLoadAttachment($dirPath,$deleteEmails=false);
?>




Friday, July 16, 2010

Insert value in auto increment column

How to insert automatically values in NOT NULL auto_increment and PRIMARY KEY column.

Suppose you have listed below table:

CREATE TABLE `testtest` (
  `id` bigint(20) NOT NULL auto_increment,
  PRIMARY KEY  (`id`)
) ; 
This table have only one column "id", and this column have attribute of  NOT NULL auto_increment and PRIMARY KEY.


you need to use listed below sql :

insert into testtest values(null)

OR

insert into testtest values('')

Thursday, July 15, 2010

change UL element text by class name

Change UL element text by class name.

var elements = document.getElementsByClassName("form-errors")[0];
//alert(elements.innerHTML);
elements.innerHTML=elements.innerHTML+"<br/><br/>";