Home

Thursday, May 26, 2011

PHP cURL functions tutorial

cURL is a library which allows you to connect and communicate to many different types of servers with many different types of protocols. Using cURL you can:
  • Implement payment gateways’ payment notification scripts.
  • Download and upload files  from remote servers.
  • Login to other websites and access members only sections.
PHP cURL library is definitely the odd man out. Unlike other PHP libraries where a whole plethora of functions is made available, PHP cURL wraps up a major parts of its functionality in just four functions.
A typical PHP cURL usage follows the following sequence of steps.
curl_init – Initializes the session and returns a cURL handle which can be passed to other cURL functions.
curl_opt – This is the main work horse of cURL library. This function is called multiple times and specifies what we want the cURL library to do.
curl_exec – Executes a cURL session.
curl_close – Closes the current cURL session.
Below are some examples which should make the working of cURL more clearer.
The below piece of PHP code uses cURL to download Google’s RSS feed.
<?php
/**
* Initialize the cURL session
*/

$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/

curl_setopt($ch, CURLOPT_URL,
‘http://news.google.com/news?hl=en&topic=t&output=rss’);
/**
* Ask cURL to return the contents in a variable
* instead of simply echoing them to the browser.
*/

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
/**
* Execute the cURL session
*/

$contents = curl_exec ($ch);
/**
* Close cURL session
*/

curl_close ($ch);
?>

As you can see, curl_setopt is the pivot around which the main cURL functionality revolves. cURL functioning is controlled by way of passing predefined options and values to this function.
The above code uses two such options.
  • CURLOPT_URL: Use it  to specify the URL which you want to process. This could be the URL of the file you want to download or it could be the URL of the script to which you want to post some data.
  • CURLOPT_RETURNTRANSFER: Setting this option to 1 will cause the curl_exec function to return the contents instead of echoing them to the browser.

MYSQL Coalesce Function

Table Contact_Info

Name Business_Phone Cell_Phone Home_Phone
Jeff 531-2531 622-7813 565-9901
Laura NULL 772-5588 312-4088
Peter NULL NULL 594-7477
and we want to find out the best way to contact each person according to the following rules:
1. If a person has a business phone, use the business phone number.
2. If a person does not have a business phone and has a cell phone, use the cell phone number.
3. If a person does not have a business phone, does not have a cell phone, and has a home phone, use the home phone number.
We can use the COALESCE function to achieve our goal:
SELECT Name, COALESCE(Business_Phone, Cell_Phone, Home_Phone) Contact_Phone
FROM Contact_Info;

Result:
Name Contact_Phone
Jeff 531-2531
Laura 772-5588
Peter 594-7477

MySQL ISNULL

Table Sales_Data

store_name Sales
Store A 300
Store B NULL
The following SQL,
SELECT SUM(ISNULL(Sales,100)) FROM Sales_Data;
returns 400. This is because NULL has been replaced by 100 via the ISNULL function.

SQL CASE

Table Store_Information

store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
San Francisco $300 Jan-08-1999
Boston $700 Jan-08-1999

if we want to multiply the sales amount from 'Los Angeles' by 2 and the sales amount from 'San Diego' by 1.5, we key in,
SELECT store_name, CASE store_name
  WHEN 'Los Angeles' THEN Sales * 2
  WHEN 'San Diego' THEN Sales * 1.5
  ELSE Sales
  END
"New Sales",
Date
FROM Store_Information

"New Sales" is the name given to the column with the CASE statement.
Result:
store_name New Sales Date
Los Angeles $3000 Jan-05-1999
San Diego $375 Jan-07-1999
San Francisco $300 Jan-08-1999
Boston $700 Jan-08-1999

Subquery

Table Store_Information

store_name Sales Date
Los Angeles $1500 Jan-05-1999
San Diego $250 Jan-07-1999
Los Angeles $300 Jan-08-1999
Boston $700 Jan-08-1999
Table Geography
region_name store_name
East Boston
East New York
West Los Angeles
West San Diego

SELECT SUM(Sales) FROM Store_Information
WHERE Store_name IN
(SELECT store_name FROM Geography
WHERE region_name = 'West')

Result:
SUM(Sales)
2050

Monday, May 9, 2011

How to Create Random Numbers & Characters

 
<script language="javascript" type="text/javascript">
function randomString() {
 var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
 var string_length = 8;
 var randomstring = '';
 for (var i=0; i<string_length; i++) {
  var rnum = Math.floor(Math.random() * chars.length);
  randomstring += chars.substring(rnum,rnum+1);
 }
 document.randform.randomfield.value = randomstring;
}
</script>
 
<form name="randform">
<input type="button" value="Create Random String" onClick="randomString();">&nbsp;
<input type="text" name="randomfield" value="">
</form> 

Friday, May 6, 2011

Simple Pagination in PHP

<head>
<title>Simple Pagination in PHP</title>
<style type="text/css">
/*---------------------Pagignation CSS --------------*/
#tnt_pagination {
    display:block;
    text-align:left;
    height:22px;
    line-height:21px;
    clear:both;
    padding-top:3px;
    font-family:Arial, Helvetica, sans-serif;
    font-size:12px;
    font-weight:normal;


}
#tnt_pagination a:link, #tnt_pagination a:visited{
    padding:7px;
    padding-top:2px;
    padding-bottom:2px;
    border:1px solid #EBEBEB;
    margin-left:10px;
    text-decoration:none;
    background-color:#F5F5F5;
    color:#0072bc;
    width:32px;
    font-weight:normal;
    }
#tnt_pagination a:hover {
    background-color:#DDEEFF;
    border:1px solid #BBDDFF;
    color:#0072BC;   
}
#tnt_pagination .active_tnt_link {
    padding:7px;
    padding-top:2px;
    padding-bottom:2px;
    border:1px solid #BBDDFF;
    margin-left:10px;
    text-decoration:none;
    background-color:#DDEEFF;
    color:#0072BC;
    cursor:default;
}
#tnt_pagination .disabled_tnt_pagination {
    padding:7px;
    padding-top:2px;
    padding-bottom:2px;
    border:1px solid #EBEBEB;
    margin-left:10px;
    text-decoration:none;
    background-color:#F5F5F5;
    color:#D7D7D7;
    cursor:default;
}
.pagination{
padding: 2px;
}
.pagination ul{
margin: 0;
padding: 0;
text-align: left; /*Set to "right" to right align pagination interface*/
font-size: 11px;
padding-top:5px;
height:15px !important;
height:20px;
}
.pagination li{
list-style-type: none;
display: inline;
padding-bottom: 1px;
}
.pagination a, .pagination a:visited{
padding: 0 5px;
border: 1px solid #9aafe5;
text-decoration: none;
color: #2e6ab1;
}
.pagination a:hover, .pagination a:active{
border: 1px solid #2b66a5;
color: #000;
background-color: #FFFF80;
}
.pagination a.currentpage{
background-color: #2e6ab1;
color: #FFF !important;
border-color: #2b66a5;
font-weight: bold;
cursor: default;
}
.pagination a.disablelink, .pagination a.disablelink:hover{
background-color: white;
cursor: default;
color: #929292;
border-color: #929292;
font-weight: normal !important;
}
.pagination a.prevnext{
font-weight: bold;
}
</style>
</head>
<body>
<?php
$con = mysql_connect('localhost','root','') or die("database error:".mysql_error());
if($con)
{
    mysql_select_db("database_name") or die("Database Connection Error.");
}


$query = "SELECT * FROM table_name";
$result = mysql_query($query);
$num_record = mysql_num_rows($result);
   
$total_records = mysql_num_rows($result);//here is the total records
$records_per_page = 1;//how many results per page
$total_pages = ceil($total_records / $records_per_page);//total number of pages
$page = intval($_GET['p']);//current page


if ($page < 1 || $page > $total_pages) $page = 1;//be sure is a number
$offset = ($page - 1) * $records_per_page;//position
                   
$limit = " LIMIT $offset, $records_per_page";//sql we need to add IMPORTANT
   
$sql = "SELECT * FROM table_name $limit";
$rs = mysql_query($sql) or die("Database Error :".mysql_error());


if($num_record > 0 )
{
?>
<p><span style="font-size:12px;">Result</span></p>
<table cellpadding="3" cellspacing="0" border="1" width="90%" align="center">
        <tr>
            <th width="10%" align="center">No.</th>
            <th width="90%">Skill</th>
        </tr>
        <?
        if($_GET['p'])
        {
            if($_GET['p'] == 2)
            {
                $i=$records_per_page;
            }
            else if($_GET['p']==1)
            {
                $i= 0;
            }
            else
            {
                $i= (($_GET['p'] * $records_per_page) - $records_per_page);
            }
        }
        else
        {
            $i = 0;
        }
        while($row=mysql_fetch_array($rs))
        {   
        $i++;
            ?>
            <tr>
                <td align="center"><?= $i; ?>.</td>
                <td><?= $row['column_name']; ?></td>
            </tr>
            <?
            }
        $a = $total_records;
        $b = $records_per_page;//$records_per_page-1;
        if($a>$b)
        {
        ?>
        <tr><td colspan="2">
                <table width="100%" cellpadding="0" cellspacing="0">
                    <tr><td align="center">
                    <div class="pagination">
                    <?php   
                    $display_pages=2;//how many pages to display
                    ?><ul><li><?
                    echo "<a title='Start'  href='?p=1' class='prevnext'>Start »</a> ";//Start
                    if ($page>1) echo "</a><a class='prevnext disablelink' title='Previous' href='?p=".($page-1)."'>« Prev</a> "; //Previous
                    
                    for ($i = $page; $i <= $total_pages && $i<=($page+$display_pages); $i++) {
                          if ($i == $page) echo "<li><a class='currentpage' > $i </span>";//not printing the link
                          else echo "</a>&nbsp;<a title='page $i' href='?p=$i'> $i</a>&nbsp;";//link
                    }
                    
                    if (($page+$display_pages)< $total_pages) echo "..."; //etcetera...
                    if ($page<$total_pages) echo "<a title='Next' href='?p=".($page+1)."'>Next »";//Next
                    echo "</a>&nbsp;<a title='End' href='?p=$total_pages' class='prevnext'>End »</a>";//end
                    ?>
                    </div>
                    </td></tr>
                </table>
        </td></tr>
        <?
            }
        ?>
    </table>
<? }
else
{ ?>
<p align="center"><span style="color:#F00;" >No record found.</span>&nbsp;&nbsp;&nbsp;&nbsp;</p>
<? } ?>
</body>

Tuesday, May 3, 2011

How do I sumbit a form with a textarea upon enter ?

function isEnterPressed(e,frm){
var keycode=null;
if (e!=null){
        if (window.event!=undefined){
                if (window.event.keyCode) keycode = window.event.keyCode;
                else if (window.event.charCode) keycode = window.event.charCode;              
        }else{
                keycode = e.keyCode;              
        }
}
if(keycode == 13)
{  
    document.forms["myform"].submit();
    document.getElementById('message').value="";
    document.getElementById('message').focus();
}
}
<form name="myform">
         <textarea name="message" id="message" onkeyup="if(isEnterPressed(event,this.form)){}" ></textarea>
</form>


Auto Load and Refresh Div every 10 Seconds with jQuery.

<script src="js/jquery.js"></script>

INDEX.PHP
<script>
var auto_refresh = setInterval(
function()
{
$('#load_chat').fadeOut('slow').load('chatdetails.php').fadeIn("slow");
}, 10000);
</script>
 <div style="display: block;" id="load_chat">Hi This is Testing...</div> 

chatdetails.php
<?php
$sql = mysql_query("Select id form Messages");
$record_count=mysql_num_rows($sql);
echo $record_count;
?>
rathoddhirendra.blogspot.com-Google pagerank and Worth