Sunday, March 18, 2012

How to check error reporting in php?


// Error report genaral


ini_set(‘display_errors’,1);
error_reporting(E_ALL|E_STRICT);


//only want to see Warning Messages and not Notice Messages


ini_set(‘display_errors’,1);
error_reporting(E_ALL);


//all Error Reporting off, simply use this:


error_reporting(0);

How to suffle a string in php?


//Php array suffle example


<?php
$string = 'abcdef';
$shuffled = str_shuffle($string);


// This will echo something like: bfdaec
echo $shuffled;
?>

Saturday, March 17, 2012

How to check website loading time in php?

// here the code 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>website time load</title>
<?
$starttime = microtime();
$startarray = explode(" ", $starttime);
$starttime = $startarray[1] + $startarray[0];
?>
</head>


<body>
<?
$endtime = microtime();
$endarray = explode(" ", $endtime);
$endtime = $endarray[1] + $endarray[0];
$totaltime = $endtime - $starttime;
$totaltime = round($totaltime,10);
echo "Seconds To Load: ";
printf ("%f\n", $totaltime);
?>
</body>
</html>


Friday, March 16, 2012

How to include digital font in css?


// code in your css
//src: font file source.


@font-face {
font-family: digital;
src: url("path-to-the-font-file/digital.otf") format("opentype");
}




h1 { font-family: "digital",Helvetica,Arial,sans-serif; font-size:43px; line-height:37px; font-weight:normal;}


h2 { font-family: "digital",Helvetica,Arial,sans-serif; font-size:16px;line-height:14px; font-weight:normal;}


h3 { font-family: "digital",Helvetica,Arial,sans-serif; font-size:16px;line-height:14px; font-weight:normal; color:#c4161c; margin:6px 0 6px 0;}

Wednesday, March 14, 2012

How to increase file upload limit in php?

//Edit in your  php.ini

memory_limit = 32M
upload_max_filesize = 10M
post_max_size = 20M

How to increase file upload limit in php using .htaccess?

php_value memory_limit 36M
php_value post_max_size 36M
php_value upload_max_filesize 32M 

Tuesday, March 13, 2012

How to connect FTP using simple php function?


<?php
//Connect to the FTP server
$ftpstream = @ftp_connect('example.com');
$login = @ftp_login($ftpstream, 'username', 'password');
if($login) {
//Ftp now connected.. make your code here
}
else
{
//  Ftp Not Connectd
}

//Close FTP connection
ftp_close($ftpstream);
?>

Monday, March 12, 2012

How to get value dynamic in php using ajax?


Step one:

//Save  below content to  ajax.js

function createAjaxObj(){
var httprequest=false
if (window.XMLHttpRequest){ // if Mozilla, Safari etc
httprequest=new XMLHttpRequest()
if (httprequest.overrideMimeType)
httprequest.overrideMimeType('text/xml')
}
else if (window.ActiveXObject){ // if IE
try {
httprequest=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
httprequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return httprequest
}

var ajaxpack=new Object()
ajaxpack.basedomain="http://"+window.location.hostname
ajaxpack.ajaxobj=createAjaxObj()
ajaxpack.filetype="txt"
ajaxpack.addrandomnumber=0 //Set to 1 or 0. See documentation.

ajaxpack.getAjaxRequest=function(url, parameters, callbackfunc, filetype){
ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
if (ajaxpack.addrandomnumber==1) //Further defeat caching problem in IE?
var parameters=parameters+"&ajaxcachebust="+new Date().getTime()
if (this.ajaxobj){
this.filetype=filetype
this.ajaxobj.onreadystatechange=callbackfunc
this.ajaxobj.open('GET', url+"?"+parameters, true)
this.ajaxobj.send(null)
}
}

ajaxpack.postAjaxRequest=function(url, parameters, callbackfunc, filetype){
ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
if (this.ajaxobj){
this.filetype=filetype
this.ajaxobj.onreadystatechange = callbackfunc;
this.ajaxobj.open('POST', url, true);
this.ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
this.ajaxobj.setRequestHeader("Content-length", parameters.length);
this.ajaxobj.setRequestHeader("Connection", "close");
this.ajaxobj.send(parameters);
}
}

//ACCESSIBLE VARIABLES (for use within your callback functions):
//1) ajaxpack.ajaxobj //points to the current ajax object
//2) ajaxpack.filetype //The expected file type of the external file ("txt" or "xml")
//3) ajaxpack.basedomain //The root domain executing this ajax script, taking into account the possible "www" prefix.
//4) ajaxpack.addrandomnumber //Set to 0 or 1. When set to 1, a random number will be added to the end of the query string of GET requests to bust file caching of the external file in IE. See docs for more info.

//ACCESSIBLE FUNCTIONS:
//1) ajaxpack.getAjaxRequest(url, parameters, callbackfunc, filetype)
//2) ajaxpack.postAjaxRequest(url, parameters, callbackfunc, filetype)



//////EXAMPLE USAGE ////////////////////////////////////////////
/* Comment begins here

//Define call back function to process returned data
function processGetPost(){
var myajax=ajaxpack.ajaxobj
var myfiletype=ajaxpack.filetype
if (myajax.readyState == 4){ //if request of file completed
if (myajax.status==200 || window.location.href.indexOf("http")==-1){ if request was successful or running script locally
if (myfiletype=="txt")
alert(myajax.responseText)
else
alert(myajax.responseXML)
}
}
}

/////1) GET Example- alert contents of any file (regular text or xml file):

ajaxpack.getAjaxRequest("example.php", "", processGetPost, "txt")
ajaxpack.getAjaxRequest("example.php", "name=George&age=27", processGetPost, "txt")
ajaxpack.getAjaxRequest("examplexml.php", "name=George&age=27", processGetPost, "xml")
ajaxpack.getAjaxRequest(ajaxpack.basedomain+"/mydir/mylist.txt", "", processGetPost, "txt")

/////2) Post Example- Post some data to a PHP script for processing, then alert posted data:

//Define function to construct the desired parameters and their values to post via Ajax
function getPostParameters(){
var namevalue=document.getElementById("namediv").innerHTML //get name value from a DIV
var agevalue=document.getElementById("myform").agefield.value //get age value from a form field
var poststr = "name=" + encodeURI(namevalue) + "&age=" + encodeURI(agevalue)
return poststr
}

var poststr=getPostParameters()

ajaxpack.postAjaxRequest("example.php", poststr, processGetPost, "txt")
ajaxpack.postAjaxRequest("examplexml.php", poststr, processGetPost, "xml")

Comment Ends here */


Step two:
//save this below content to index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="text/javascript" src="ajax.js" ></script>
</head>

<body>

<script type="text/javascript">
function processGetPost(){
var myajax=ajaxpack.ajaxobj
var myfiletype=ajaxpack.filetype
if (myajax.readyState == 4){ //if request of file completed
if (myajax.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful or running script locally
if (myfiletype=="txt")
alert(myajax.responseText)
else
alert(myajax.responseXML)
}
}
}

ajaxpack.getAjaxRequest("test.htm", "", processGetPost, "txt")
</script>
</body>
</html>


//index.php end

Step Three:
//save this below content as test.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
Output for this file
</body>
</html>
// test.htm end

Friday, March 9, 2012

How to change upper to lowercase,lower to uppercase,firstletter to upper case in php?


<?php
$foo = 'welcome';
$foo = ucfirst($foo);            

//Output

Welcome

$bar = 'WELCOME!';
$bar = ucfirst($bar);              // WELCOME
$bar = ucfirst(strtolower($bar));

//Output
 Welcome

?>


<?php
$str = "Php Scripts Here";
$str = strtolower($str);
echo $str;

//Output
 php scripts here

?>

<?php
$str = "Php Scripts Here";
$str = strtoupper($str);
echo $str;

// Output
PHP SCRIPTS HERE
?>

Thursday, March 8, 2012

How to make a simple calculator function using php?


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Simple Calculator function</title>
  </head>
  <body>
<?php
function showForm() {
?>
    <table border="0" cellpadding="2" cellspacing="2" style="font:12px Arial, Helvetica, sans-serif">
        <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
        <tr>
            <td width="111" align="right" bgcolor="#CCCCCC"><strong>Number:</strong></td>
            <td width="293" bgcolor="#CCCCCC"><input type="text" maxlength="3" name="number" size="4" value="<?=$_POST['number'];?>"  /></td>
        </tr>
       
        <tr>
            <td align="right" bgcolor="#CCCCCC"><strong>Another number:</strong></td>
            <td bgcolor="#CCCCCC"><input type="text" maxlength="4" name="number2" size="4"  value="<?=$_POST['number2'];?>"/></td>
        </tr>
       
        <tr>
            <td align="right" valign="top" bgcolor="#CCCCCC"><strong>Operator:</strong></td>
          <td bgcolor="#CCCCCC"><table width="100%" border="0" cellspacing="2" cellpadding="2">
            <tr>
              <td><input type="radio" name="opt" value="+" />+</td>
              <td><input type="radio" name="opt" value="-"   />-</td>
              <td><input type="radio" name="opt" value="*"  />*</td>
              <td><input type="radio" name="opt" value="/" />/</td>
            </tr>
            <tr>
              <td><input type="radio" name="opt" value="^2" />x<sup>2</sup></td>
              <td><input type="radio" name="opt" value="sqrt" />sqrt</td>
              <td><input type="radio" name="opt" value="^" />^</td>
              <td>&nbsp;</td>
            </tr>
          </table> </td>
        </tr>
        <tr>
            <td align="right" bgcolor="#CCCCCC"><strong>Rounding:</strong></td>
            <td colspan="2" bgcolor="#CCCCCC"><input type="text" name="rounding" value="4" size="4" maxlength="4" /> <small>(Enter how many digits you would like to round to)</small>            </td>
          </tr>
       
        <tr>
            <td align="right" bgcolor="#CCCCCC">&nbsp;</td>
            <td bgcolor="#CCCCCC"><input type="submit" value="Calculate" name="submit" /></td>
        </tr>
        </form>
    </table>
    <?php
}

if (empty($_POST['submit'])) {
    showForm();
} else {
showForm();
    $errors = array();
    $error = false;
   
    if (!is_numeric($_POST['number'])) {
        (int)$_POST['number'] = rand(1,200);
    }
   
    if (empty($_POST['number'])) {
        (int)$_POST['number'] = rand(1,200);
    }
   
    if (!is_numeric($_POST['number2'])) {
        (int)$_POST['number2'] = rand(1,200);
    }
   
    if (empty($_POST['number2'])) {
        (int)$_POST['number2'] = rand(1,200);
    }
   
    if (empty($_POST['rounding'])) {
        $round = 0;
    }
   
    if (!isset($_POST['opt'])) {
        $errors[] = "You must select an operation.";
        $error = true;
    }
   
    if (strpbrk($_POST['number'],"-") and strpbrk($_POST['number2'],"0.") and $_POST['opt'] == "^") {
        $errors[] = "You cannot raise a negative number to a decimal, this is impossible. <a href=\"http://www.tuxradar.com/practicalphp/4/6/4\">Why?</a>";
        $error = true;
    }
   
    if ($error != false) {
        echo "We found these errors:";
        echo "<ul>";
        foreach ($errors as $e) {
            echo "<li>$e</li>";
        }
        echo "</ul>";
    } else {
        switch ($_POST['opt']) {
            case "+":
                $result = (int)strip_tags($_POST['number']) + (int)strip_tags($_POST['number2']);
                echo "The answer to " . (int)strip_tags($_POST['number']) . " $_POST[opt] " . (int)strip_tags($_POST['number2']) . " is $result.";
                break;
            case "-";
                $result = (int)strip_tags($_POST['number']) - (int)strip_tags($_POST['number2']);
                echo "The answer to " . (int)strip_tags($_POST['number']) . " $_POST[opt] " . (int)strip_tags($_POST['number2']) . " is $result.";
                break;
            case "*";
                $result = (int)strip_tags($_POST['number']) * (int)strip_tags($_POST['number2']);
                echo "The answer to " . (int)strip_tags($_POST['number']) . " $_POST[opt] " . (int)$_POST['number2'] . " is $result.";
                break;
            case "/";
                $result = (int)strip_tags($_POST['number']) / (int)strip_tags($_POST['number2']);
                $a = ceil($result);
                    echo "<br />";
                    echo "<hr />";
                    echo "<h2>Rounding</h2>";
                    echo "$result rounded up is $a";
                    echo "<br />";
                    $b = floor($result);
                    echo "$result rounded down is $b";
                    echo "<br />";
                    $h = round($result,(int)$_POST['rounding']);
                    echo "$result rounded to $_POST[rounding] digits is " . $h;
                break;
            case "^2":
                $result = (int)strip_tags($_POST['number']) * (int)strip_tags($_POST['number2']);
                $a = (int)$_POST['number2'] * (int)$_POST['number2'];
                    echo "The answer to " . (int)$_POST['number'] . "<sup>2</sup> is " . $result;
                    echo "<br />";
                    echo "The answer to " . (int)$_POST['number2'] . "<sup>2</sup> is " . $a;
                break;
            case "sqrt":
                $result = (int)strip_tags(sqrt($_POST['number']));
                $sqrt2 = (int)strip_tags(sqrt($_POST['number2']));
                echo "The square root of " . (int)strip_tags($_POST['number']) . " is " . $result;
                    echo "<br />";
                    echo "The square root of " . (int)strip_tags($_POST['number2']) . " is " . $sqrt2;
                    echo "<br />";
                    echo "The square root of " . (int)strip_tags($_POST['number']) . " rounded to " . strip_tags($_POST[rounding]) . " digits is " . round($result,(int)$_POST['rounding']);
                    echo "<br />";
                    echo "The square root of " . (int)strip_tags($_POST['number2']) . " rounded to " . strip_tags($_POST[rounding]) . " digits is " . round($sqrt2,(int)strip_tags($_POST['rounding']));
                break;
            case "^":
                $result = (int)strip_tags(pow($_POST['number'],$_POST['number2']));
                $pow2 = (int)strip_tags(pow($_POST['number2'],$_POST['number']));
                echo (int)$_POST['number'] . "<sup>" . strip_tags($_POST[number2]) . "</sup> is " . $result;
                    echo "<br />";
                    echo (int)$_POST['number2'] . "<sup>" . strip_tags($_POST[number]) . "</sup> is " . $pow2;
                    break;
        }
           
    }
}
?>
  </body>
</html>

How to create a compressed zip file using php?


<?
// Create Compressed File.
function createZip()
     {
    $file_to_compress = "sample.txt"; //put any type of file
    $file_to_produce="sample.txt.zip";
   $data = implode("", file($file_to_compress));
   $zipdata = gzencode($data, 9);
   $filep = fopen($file_to_produce, "w");
   fwrite($filep, $zipdata);
     }
echo createZip(); // call the function.it will create a zip file which has place this file location.
 ?>

Wednesday, March 7, 2012

How to check file upload image validation in javascript?


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Image Extension Validation</title>
</head>
<script type="text/javascript" language="javascript">
//Image Extension Validation
function img_path()
{
var file_path=document.getElementById('file').value;
if(file_path.match(".jpeg$")==".jpeg" || file_path.match(".gif$")==".gif" || file_path.match(".GIF$")==".GIF" || file_path.match(".JPEG$")==".JPEG" || file_path.match(".JPG$")==".JPG" ||file_path.match(".jpg$")==".jpg")
{
return true;
}
else
{
alert("Upload  .jpg/.gif  file olny");
return false;
}

}
</script>
<body>
<form name="image" enctype="multipart/form-data" method="post" >
<table width="568" cellspacing="0" cellpadding="0" >
     <tr >
              <td colspan="2"   valign="top" >&nbsp;</td>
     </tr>
 <tr>
 <td width="126" align="left" valign="top">File Choose*</td>
<td width="310"  align="left" valign="top" style="padding-left:10px;">
  <input type="file" name="file" id="file" style="height:22px;">
               <input name="submit" type="submit" value="Upload" onClick="return img_path()">
</td>
</tr>
</table>
</form>

</body>
</html>


How to change www to non-www in header url using htaccess?


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]
</IfModule>

Monday, March 5, 2012

How to change non-www to www in header url using htaccess?


<IfModule mod_rewrite.c>
RewriteEngine on

RewriteCond %{HTTP_HOST} ^(testweb\.com).*$ [I]
RedirectRule ^/(.*)$ http://www.testweb.com/$1 [I,R=301]

</IfModule>

Friday, March 2, 2012

How to redirect a page on before window closing time?


<script type="text/javascript" language="javascript">
window.onbeforeunload = showPic; // This is the browser window close function.
var redirecting= false;
var show_popup = true;

function showPic() {
if(show_popup)
{
    if (redirecting) return;
    setTimeout(function()
{
      setTimeout(function()
 {
            redirecting= true;
            location.href= 'http://www.google.com'; // Redirecting Url.
      }, 1000);
    }, 0);
    return '*****************************************************\n\n Wait! we have lanuch a new website \.\n If you interested to view that please click the cancel button. \n\n*****************************************************';
 }
};
//This function used to hide the popup scripts
function disablePOP()
{
  show_popup = false;
}

</script>

How to check page visit count using javascript cookie?


Here the code for check visiting count using java script cokkie.

<html>
<head>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
window.onload = initPage;

function initPage() {
var now = new Date();
var expireDate = new Date();
expireDate.setMonth(expireDate.getMonth()+6);
 
var hitCt = parseInt(cookieVal("pageHit"));
hitCt++;

var lastVisit = cookieVal("pageVisit");
if (lastVisit == 0) {
lastVisit = "";
}

document.cookie = "pageHit=" + hitCt + ";expires=" + expireDate.toGMTString();
document.cookie = "pageVisit=" + now + ";expires=" + expireDate.toGMTString();

var outMsg = "You have visited this page " + hitCt + " times.";
if (lastVisit != "") {
outMsg += "<br />Your last visit was " + lastVisit;
}
document.getElementById("cookieData").innerHTML = outMsg;
}

function cookieVal(cookieName) {
var thisCookie = document.cookie.split("; ");

for (var i=0; i<thisCookie.length; i++) {
if (cookieName == thisCookie[i].split("=")[0]) {
return thisCookie[i].split("=")[1];
}
}
return 0;
}


</script>
<div id="cookieData"></div>
</body>
</html>

Thursday, March 1, 2012

How to open a file and read, write content in the file using php?


<?php
//File Read
$filename = "content.txt";
$fget = fopen($filename, 'r');
$theData = fread($fget, filesize($filename));
fclose($fget);
echo $filecontent;

//File Write
$filename = "content.txt";
$fget = fopen($filename, 'w') or die("can't open file");
$filecontent = "Test content1\n";
fwrite($fget, $stringData);
$filecontent = "Test content2\n";
fwrite($fget, $filecontent);
fclose($fget);

?>

How to Fix Page Not Found error using htaccess?

step 1. Create a file name 404.html or 404.php what ever you want.. in your root directory

step 2. Enter some  text  like sorry your search page not found in the 404.php or 404.html..

step 3. Enter your valid redirect url path with a link.

step 4. add in  your .htaccess  file below the content.


ErrorDocument 404 /index.htm
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /404.htm [L]
</IfModule>

How to create contact form in php with validation and email function?


<?php
if($_POST['cmdsubmit']=='Submit'){
$name=$_POST['name'];
$fromemail=$_POST['email'];
$subject=$_POST['subject'];
$message=$_POST['message'];
$today = date("D M j G:i:s");  
$msgSubject="Contact Us....";
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: ".$fromemail."<".$fromname.">\n";
$message='
<table width="500" cellpadding="2" cellspacing="10" bgcolor="#ffffff" style="font-family:arial;font-size:11px">
<tr><td><b>Enquiry</b></td></tr>
<tr><td colspan=4>Name:</td><td  >'.$name.'</td></tr>
<tr><td colspan=4>Email:</td><td >'.$fromemail.'</td></tr>
<tr><td colspan=4>Subject:</td><td >'.$subject.'</td></tr>
<tr><td colspan=4>Mesage:</td><td  width =300>'.$message.'</td></tr>
<tr><td colspan=4>Send time : </td><td >'.$today.'</td></tr>
</table> <br><br> By <br>';
mail('phpcodeblog.gmail.com',$msgSubject,$message,$headers);
$Sentmsg="Mail Has Been Sent";
}
?>
<script type="text/javascript" language="JavaScript">

function trim(s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}


function isValid(){
  var fobj = document.forms['frmmail'];
  var errors = '';

  if (trim(fobj.elements['name'].value).length == 0) errors += 'Name cannot be empty!\n';
  if (trim(fobj.elements['email'].value).length == 0) errors += 'Email cannot be empty!\n';
   if (trim(fobj.elements['subject'].value).length == 0) errors += 'subject cannot be empty!\n';
  if (trim(fobj.elements['message'].value).length == 0) errors += 'message cannot be empty!\n';
  var reg = new RegExp(/^[^@ ]+@[^@ ]+\.[^@ ]+$/);
  if(!fobj.elements['email'].value.match(reg))errors += 'Invalid Email Address!\n';

  if (errors.length > 0) {
    alert(errors);
    return false;
  } else return true;
   
}
</script>
<table width="65%"  border="0" cellspacing="0" cellpadding="0">

      <tr>
<form method="post" action="mail.php"  name="frmmail"  onsubmit="return isValid();">
        <td colspan="3"><h3 >Contact Form  </h3>
          <span class="contact1"><b>(All fields are Mandatory)&nbsp;&nbsp;&nbsp;</b></span><b>&nbsp;</b>
 
 <table width="73%"  border="0" cellpadding="3" cellspacing="4">

        <tr>

            <td width="15%" align="right" valign="middle" class="contact1"> Name&nbsp;&nbsp;&nbsp;&nbsp;</td>

            <td width="85%"><input name="name" type="text" style="width:200px " ></td>
          </tr>

          <tr>

            <td align="right" valign="middle" class="contact1"> E-mail&nbsp;&nbsp;&nbsp;&nbsp;</td>

            <td><input name="email" type="text" style="width:200px " ></td>
          </tr>

          <tr>

            <td align="right" valign="middle" class="contact1">Subject&nbsp;&nbsp;</td>

            <td><input name="subject" type="text" maxlength = "100" style="width:200px "></td>
          </tr>

          <tr>

            <td align="right" valign="middle" class="contact1">Message</td>

            <td><textarea name="message" rows="5" style="width:200px "></textarea></td>
          </tr>

          <tr>

            <td height="30" align="right">&nbsp;</td>

            <td><input type="submit" value="Submit" name="cmdsubmit"></td>
          </tr>
      </table>  </td>
      </form></tr>
 
    </table>

How to solve header already sent error in php?

* Remove  unwanted space "?>" after ending with  the bottom of the file.
* Use @ symbol at beginning of the URL redirected..

How to join two tables left or right or inner?


<?php
// Joining Tables with Left ,Right,Inner

mysql_connect("localhost", "root", "pass") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());

//Left Join tables
$query =  mysql_query("SELECT namne, age, designation FROM emp LEFT JOIN empdesig ON  emp.eid=empdesig.id");

// Right Join tables
$query =  mysql_query("SELECT name, age, designation FROM emp RIGHT JOIN empdesig ON emp.pid=empdesig.id");


// Inner Join

$query =  mysql_query("SELECT * FROM emp a INNER JOIN empdesif b  ON a.empid = b.empdesig");

?>

Wednesday, February 29, 2012

How to join two tables in mysql?

<?php
// Simple Join Query
mysql_connect("localhost", "root", "pass") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());

$query = "SELECT emp.empname, empdesig.designation FROM emp, empdesig WHERE emp.empname = empdesig.empname";
   
$result = mysql_query($query) or die(mysql_error());

//display record empname with designation.

while($rec = mysql_fetch_array($result))
   {
    echo $rec['empname']. " :- ". $rec['designation']."<br>";
    }
?>

How to update table records and displaying in sorting order.

<?php
mysql_connect("localhost", "root", "pass") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());

//update Query
$result = mysql_query("UPDATE emp SET fieldname='robin' WHERE fieldname='rock'")
or die(mysql_error()); 

$result = mysql_query("SELECT * FROM emp WHERE fieldname='robin'") or die(mysql_error()); 

$row = mysql_fetch_array( $result );
echo $row['fieldname']." - ".$row['age'];

//Delete Query

mysql_query("DELETE FROM emp WHERE fieldname='robin'") or die(mysql_error());

//Order By [sorting ASC] Query

$result = mysql_query("SELECT * FROM emp WHERE fieldname='robin' order by fieldname ASC") or die(mysql_error()); 

//Order By [sorting DESC] Query

$result = mysql_query("SELECT * FROM emp WHERE fieldname='robin' ORDER BY fieldname DESC") or die(mysql_error()); 


//Group by Query

$query = mysql_query("SELECT fieldname, MIN(age) FROM emp GROUP BY fieldname") or die(mysql_error());

?>

How to create a table and insert records and retrieve data?


<?php
// mysql Connection
mysql_connect("localhost", "root", "pass") or die(mysql_error());
mysql_select_db("dbname") or die(mysql_error());

//emp table create
mysql_query("CREATE TABLE emp(id INT NOT NULL AUTO_INCREMENT,PRIMARY KEY(id),empname VARCHAR(30), empid INT)") or die(mysql_error());

//insert records to emp table
mysql_query("INSERT INTO emp (empname, empid) VALUES('melvin', '101' ) ") or die(mysql_error());

mysql_query("INSERT INTO emp (empname, empid) VALUES('rudie', '102' ) ")  or die(mysql_error());

// get data
$result = mysql_query("SELECT * FROM emp")or die(mysql_error());
$rec = mysql_fetch_array( $result );

// print the result
echo "empname: ".$rec['empname'];
echo "empid: ".$rec['empid'];
?>


Tuesday, February 28, 2012

How to get database Table structure detail ?



<?php
$db="dbname";
$username="root";
$password="";
$host="localhost";

$connection = @mysql_connect($host,$username,$password,false,2) or die("Unable to connect Mysql server");
@mysql_select_db($db,$connection) or die ("unable to connect Database");

$result = mysql_query('select * from orders');
if (!$result) {
    die('Query failed: ' . mysql_error());
}
/* get table column data */
$i = 0;
while ($i < mysql_num_fields($result))
{

echo "Information for column $i:<br />\n";
$data = mysql_fetch_field($result, $i);
if (!$data) {
echo "No information available<br />\n";
}
echo "<pre>
blob:         $data->blob
max_length:   $data->max_length
multiple_key: $data->multiple_key
name:         $data->name
not_null:     $data->not_null
numeric:      $data->numeric
primary_key:  $data->primary_key
table:        $data->table
type:         $data->type
unique_key:   $data->unique_key
unsigned:     $data->unsigned
zerofill:     $data->zerofill
</pre>";
$i++;
   }
mysql_free_result($result);
?>


Result
-----------


Information for column 0:

blob:         0
max_length:   2
multiple_key: 0
name:         orders_id
not_null:     1
numeric:      1
primary_key:  1
table:        orders
type:         int
unique_key:   0
unsigned:     0
zerofill:     0

.
.
.
.
.
Information for column 10:

blob:         0
max_length:   2
multiple_key: 0
name:         order_name
not_null:     1
numeric:      1
primary_key:  0
table:        orders
type:         string
unique_key:   0
unsigned:     0
zerofill:     0



How to connect mysql database in PHP?


<?php
$server="localhost";
$dbname="mydb";
$username="root";
$password="";

$connection=mysql_connect($server,$username,$password);

if(!$connection)
{
die("couldnot connected:".mysql_error());
}
if(mysql_query("create database mydb",$connection))
{
echo "database created";
}
else
{
echo die("database create faild".mysql_error());
}
?>