Popular Posts

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Feb 20, 2014

Send mail using SMTP in PHP


Using PHP mailer you can send email usning SMTP.

<?php

function send_mail($mailAddress, $desc) {
    require_once('../phpmailer/class.phpmailer.php');
    include("../phpmailer/class.smtp.php");
    // optional, gets called from within class.phpmailer.php if not already loaded

    $mail = new PHPMailer();

    //$body             = file_get_contents('contents.html');
    //$body             = eregi_replace("[\]",'',$body);

    $mail->IsSMTP(); // telling the class to use SMTP
    //$mail->Host       = "10.48.1.45"; // Virtual SMTP server IP
    $mail->SMTPDebug = 2;                     // enables SMTP debug information (for testing)
    // 1 = errors and messages
    // 2 = messages only
    $mail->SMTPAuth = true;                        // enable SMTP authentication
    $mail->SMTPSecure = "tls";                    // sets the prefix to the servier
    $mail->Host = "ssl://smtp.gmail.com";      // sets GMAIL as the SMTP server
    $mail->Port = 587;                                 // set the SMTP port for the GMAIL server
    $mail->Username = "mail@gmail.com";  // GMAIL username Any ID of lafarge
    $mail->Password = "password";            // GMAIL password of the ID

    $mail->SetFrom('mail@domail.com', 'From Me'); // From whom the mail is sent
    $mail->AddReplyTo("mail@domail.com", "Hello Sera");

    $mail->Subject = "SMTP MAIL";
    $mail->Body = "You have successfully entered to sera's world " . "<a href='http://jubayerdevs.blogspot.com'>" . "Click here" . "</a>";
    $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test

    $address = "mail@domail.com";
    if ($address == '') {
        echo "<script>alert('No mail address found for this user. Set a mail address please');</script>";
        die();
    }

    $mail->AddAddress($address, "Lafarge Procurement Software");

    //$mail->AddAttachment("examples/images/phpmailer.png");      // attachment
    //$mail->AddAttachment("examples/images/phpmailer_mini.gif"); // attachment

    if (!$mail->Send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "<script>alert('Successfully Submitted');</script>";
    }
}
?>

Aug 19, 2013

Easy Way to Insert Data into Mysql Table from a CSV or Excel File



Reading each row from excel/csv file and then insert to mysql table is a old way.we can use mysql inbuilt query. The same thing in sqlserver and .net we use bulk insert to insert data from excel to sqlserver.

first create a page named it index.html


<html>
<head>
<script> // This function will pop a window which will tell the 
 
                 function popitup(url)
                {
                        new_wind=window.open(url,'name','height=700,width=1500');
                        if (window.focus) {new_wind.focus();
                        return false;
                }
               }
        </script>
</head>
<body>
Add  data : The file should be a .csv file  <a href="index.html" 
 onclick="return popitup('index.html')"
  > Check the format here </a> </br></br> 
 will be directed to ins_data.php-->
        <form action="ins_data.php" method="post" enctype="multipart/form-data">
                <label for="file">   </label>
                <input  type="file" name="file" id="file" />
          </br></br>      <input type="submit" value="Load data" 
   name="button1"/>
        </form>
</div>
</body>
                </html>
 
 
 Create new file named it ins_data.php
 
 
 
<?php
         if (isset($_POST['button1'])) //  Do  THE FOLLOWING WHEN BUTTON IS PRESSED
        {
                echo "button on is pressed";
                 if ($_FILES["file"]["error"] > 0)
                {
         echo "Error: " . $_FILES["file"]["error"] . 
   "You have not selected a file or some other error <br />";
                }
                else
                {       //Errorless  start 
                        $file_name=$_FILES["file"]["name"];echo $file_name;
                        $file_type=$_FILES["file"]["type"];
                        if($file_type!='text/csv')
                        {
                                echo "Please the input file should be a .csv file";
                        }
                        else
                        {       
      //      only executed if file is .csv
       echo "its correct";
                                
   // Creating a temporary copy on the server 
     $location=""; //write the location of the uploaded file 
     // upload file to server
     move_uploaded_file($_FILES["file"]["tmp_name"], 
     $location . $_FILES["file"]["name"]);
                                                                                
                connect_db(); // MYSQL connection settings
                // I have provided a sample query : 
        // Please make changes as per your requirement 
                $q="LOAD DATA INFILE '$file_name' INTO TABLE t_log 
                              FIELDS TERMINATED BY \"\t\" 
                              LINES TERMINATED BY \"\n\" 
                              ( Lang,Doc_Type,Title,Issue,Keywords )";
                mysql_query($q) or die(mysql_error());
                        }
                }
}

?>
<?php
function connect_db()
{
        //  db config 
        $con = mysql_connect("localhost","username","password");
        if (!$con)
        {
                die('Could not connect: ' . mysql_error());
        }
        // enter your database name
        mysql_select_db("dbname", $con);
}
?> 
 
 
 

Aug 8, 2012

Get Current Page Name(PHP)




<?php
function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}
?>

Get the current page URL using this code:
<?php
  echo curPageURL();
?>

Get Only the page name:

<?php
function curPageName() {
 return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}

echo "The current page name is ".curPageName();
?>

 

Dec 11, 2011

Show data from mysql in cell(PHP)

<table>
<tr><th>Search Jobs By Categories</th></tr>
<tr><td>
<?php

$query = "SELECT id, job_category_name FROM job_category WHERE id!=1 ORDER BY _sort ASC";
$result = mysql_query($query) or die ("Query failed");

//get the number of rows in our result so we can use it in a for loop
$numrows = (mysql_num_rows ($result));


// loop to create rows
if($numrows >0){
echo "<table width ='100%' border = '1' cellspacing = '0' cellpadding = '0'>";
// loop to create columns
$position = 1;
while ($friendList = mysql_fetch_array($result)){
if($position == 1){echo "<tr>";}
echo "<td><a href='../search_jobs/jobs_by_category.php?id=".$friendList['id']."'><br />".$friendList['job_category_name']."</a><br /></td> ";
if($position == 2){echo "</tr> "; $position = 1;}else{ $position++;}
}//while

$end = "";
if($position != 1){
for($z=(3-$position); $z>0 ; $z--){
$end .= "<td></td>";
}
$end .= "</tr>";
}

echo $end."</table> ";
}//if

?>


</td></tr>
</table>

Nov 27, 2011

Get output in JSON format(PHP)

--
-- Table structure for table `test_table`
--

CREATE TABLE IF NOT EXISTS `test_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(20) NOT NULL,
  `sort_order` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

--
-- Dumping data for table `test_table`
--

INSERT INTO `test_table` (`id`, `title`, `sort_order`) VALUES
(1, 'Article 1', '2'),
(2, 'Article 2', '5'),
(3, 'Article 3 ', '4'),
(4, 'Article 4', '1'),
(5, 'Article 5', '3');


<?php
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('extdb') or die(mysql_error());

$q = mysql_query("SELECT * FROM test_table");
while($e = mysql_fetch_assoc($q))
{
$output[] = $e;   
}
print(json_encode($output));

?>



OUTPUT:

[{"id":"1","title":"Article 1","sort_order":"2"},{"id":"2","title":"Article 2","sort_order":"5"},{"id":"3","title":"Article 3 ","sort_order":"4"},{"id":"4","title":"Article 4","sort_order":"1"},{"id":"5","title":"Article 5","sort_order":"3"}]

Nov 21, 2011

Sending email from localhost with php

A lot of developers set up PHP on their local machine to test server side development. Here's a little trick how to be able to send email from localhost so you can test email without any difficulty.

1. Go to your php.ini file and change SMTP = localhost to SMTP = aspmx.l.google.com and uncomment sendmail_from and put in your sending gmail address.

2. Go to cmd and type iisreset

3. In php, test it with mail("[youremail]@gmail.com", "subject", "body");


Note: This only works when sending email to google hosted email addresses.

Nov 14, 2011

How to validate an email in php5?

I have use ereg to validate email address. But it gives an error.
return ereg("^[a-zA-Z0-9]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$", $email);
Deprecated: Function ereg() is deprecated



PHP5 does not support ereg function.so the alternative way is to use the filter_var() function, which gives you a lot of handy validation and sanitization options.

filter_var($email, FILTER_VALIDATE_EMAIL)
If you don't want to change your code that relied on your function, just do:
function isValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL);
}



Oct 29, 2011

Rotate Txt using css


<style>
#rotate {
width:20px;
height:auto;
float:left;
font-size:11px;
font-family:Verdana;
-webkit-transform: rotate(-90deg);
-moz-transform:rotate(-90deg);
filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}
</style>

 <th width="22%"><div id="rotate"><?php echo $rec_event->event_name; ?></div></th>

Input Only decimal number in php(javascript)


<%--
    Document   : decimlOnly
    Created on : Dec 21, 2009, 4:29:43 PM
    Author     : user02
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
           <script>
               function intOnly(i) {
                var t = i.value;
                if(t.length>0) {
                    t = t.replace(/[^\d\.]+/g, '');
                }
                var s = t.split('.');
                if(s.length>1) {
                    s[1] = s[0] ;//+ '.' + s[1];
                    s.shift(s);
                }
                i.value = s.join('');
            }

            function decimalOnly(i) {
                var t = i.value;
                if(t.length>0) {
                    t = t.replace(/[^\d\.]+/g, '');
                }
                var s = t.split('.');
                if(s.length>1) {
                    s[1] = s[0]+ '.' + s[1];
                    s.shift(s);
                }
                i.value = s.join('');
            }

        </script>
    </head>
    <body>
     test  <input type="text" onchange="decimalOnly(this);" onkeyup="decimalOnly(this);" onkeypress="decimalOnly(this);">
    </body>
</html>

Oct 19, 2011

Dynamic Menu In PHP With Access Level

Make tables:


CREATE TABLE IF NOT EXISTS `sys_menu` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) COLLATE latin1_general_ci NOT NULL,
  `name_alias` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `descrip` text COLLATE latin1_general_ci,
  `links` varchar(100) COLLATE latin1_general_ci NOT NULL,
  `target` varchar(20) COLLATE latin1_general_ci NOT NULL,
  `folder_name` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `modules` varchar(50) COLLATE latin1_general_ci NOT NULL,
  `dependency` int(1) NOT NULL,
  `dependency_to` varchar(100) COLLATE latin1_general_ci NOT NULL,
  `access_mode` int(2) NOT NULL,
  `access_type` varchar(25) COLLATE latin1_general_ci NOT NULL,
  `admin_sort` int(3) NOT NULL,
  `_sort` int(3) NOT NULL,
  `_show` int(1) NOT NULL,
  `_group` varchar(20) COLLATE latin1_general_ci NOT NULL,
  `_date_time` datetime NOT NULL,
  `_subid` int(3) NOT NULL,
  `_referto` int(3) NOT NULL,
  `_group_level` int(3) NOT NULL,
  `_mainid` int(3) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=152 ;

INSERT INTO `sys_menu` (`id`, `name`, `name_alias`, `descrip`, `links`, `target`, `folder_name`, `modules`, `dependency`, `dependency_to`, `access_mode`, `access_type`, `admin_sort`, `_sort`, `_show`, `_group`, `_date_time`, `_subid`, `_referto`, `_group_level`, `_mainid`) VALUES
(1, 'Configuration', '', NULL, '#', '', '', '', 0, '', 0, '', 0, 1, 1, 'main', '0000-00-00 00:00:00', 0, 0, 0, 0),
(2, 'Company Add/ View', '', NULL, '../gc/company_list.php?mode=', '', '', '', 0, '', 0, '', 0, 1, 1, 'sub', '0000-00-00 00:00:00', 138, 0, 0, 0)

CREATE TABLE IF NOT EXISTS `user_level` (
  `levelid` int(11) NOT NULL AUTO_INCREMENT,
  `level` varchar(150) COLLATE latin1_general_ci NOT NULL,
  `levelgroupid` int(2) NOT NULL,
  `processing_type` int(2) NOT NULL,
  `menugroup` varchar(200) COLLATE latin1_general_ci NOT NULL,
  `menuid` varchar(250) COLLATE latin1_general_ci NOT NULL,
  `approval` int(1) NOT NULL,
  PRIMARY KEY (`levelid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci ROW_FORMAT=DYNAMIC AUTO_INCREMENT=106 ;

INSERT INTO `user_level` (`levelid`, `level`, `levelgroupid`, `processing_type`, `menugroup`, `menuid`, `approval`) VALUES
(1, 'General User GC', 1, 0, '7,8,9,95', '0', 0),
(2, 'Advance User GC', 1, 0, '1,7,8,9,95', '5', 0),
(103, 'General User WT', 3, 0, '', '', 0),
(104, 'Advance User WT', 3, 0, '', '', 0),
(100, 'Administrator', 100, 100, '1,7,8,9,95,101,116,122', '2,3,4,5,6,93,94,97,100,102,103,104106,107,108,109,110,111,112,113,114,117,118,119,120,121,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140, 142, 147,148, 149, 150, 151', 0),
(101, 'General User PT', 2, 0, '101', '106,107,108,109,110', 0),
(102, 'Advance User PT', 2, 0, '1,7,101', '102,103,104,106,107,108,109,110,111,112,113,114', 0);

PHP CODE:


function getMenu() {
$target = "";
 $user = getUser();
 $emp_row = find("select ul.menugroup, ul.menuid, ul.level from user u 
 left join user_level ul on ul.levelid=u.userlevel where u.username='$user'
 ");
$menugroup  =  $emp_row->menugroup;
$menuid  =  $emp_row->menuid;
$level  =  $emp_row->level;
echo "<ul>";
    $q = mysql_query("Select id, name, links, dependency, dependency_to, target from sys_menu where _group like '%main%' and _show = 1 and id in($menugroup) order by _sort") or trigger_error(mysql_error(), E_USER_ERROR);
    //$q = mysql_query("Select id, name, links, dependency, dependency_to, target from sys_menu where _group like '%main%' and _show = 1 order by _sort") or trigger_error(mysql_error(), E_USER_ERROR);
while ($d = mysql_fetch_object($q)) {
if ($d->dependency !=1) {
if ($d->target !="") {
$target = "target = $d->target";
}
 
$links = "$d->links";
echo "<li><a href='$links' $target>$d->name</a>";
            
$q_sub = mysql_query("Select id, name, links, target from sys_menu where _subid = $d->id and _show = 1 and id in($menuid) order by _sort") or trigger_error(mysql_error(), E_USER_ERROR);
//$q_sub = mysql_query("Select id, name, links, target from sys_menu where _subid = $d->id and _show = 1 order by _sort") or trigger_error(mysql_error(), E_USER_ERROR);
         
if (mysql_num_rows($q_sub) !=0 ) {
echo "<ul>";
while ($d_sub = mysql_fetch_object($q_sub)){
$links = "$d_sub->links";
echo "<li><a href='$links'>&#187; $d_sub->name</a>";
//-------------sub_sub menu begain here--------------
$q_sub_sub = mysql_query("Select id, name, links, target from sys_menu where _subid = $d_sub->id and _show = 1 and id in($menuid) order by _sort") or trigger_error(mysql_error(), E_USER_ERROR);
if (mysql_num_rows($q_sub_sub) !=0)
{
echo "<ul>";
while($d_sub_sub = mysql_fetch_object($q_sub_sub))
{
$links = "$d_sub_sub->links";
echo "<li><a href='$links'>&#187; $d_sub_sub->name</a></li>";
}
echo "</ul>";
} else {
echo "</li>";
}
//end-------------------------------
}
echo "</ul>";
          } else {
              echo "</li>";
        }

} else {
         
$links = "$d->links";
echo "<li><a href='$links'/>$d->name</a>
                    <ul>";
            $qq = mysql_query("Select id, category_name from $d->dependency_to where _group like '%main%' order by _sort ") or trigger_error(mysql_error(), E_USER_ERROR);
            while($dd = mysql_fetch_object($qq)) {
$links = "$d->links";
                echo "<li>Please generate</li>";
            }
            echo "</ul>
                </li>";
            }
       }
  echo "<li><a href='../common/modules.php?logout=true' onClick='return log_out()'>Sign out</a></li>";
echo "</ul>";
}

<div class="grid_16">
<div id="myslidemenu" class="jqueryslidemenu">
<?php getMenu(); // call the getMenu() Function  ?>
</div>
</div>

Oct 16, 2011

Search in PHP

Create a file activities_report.php

<form action="activities_report.php" method=POST>
<table border="0" width="100%">
<tr>

</tr>
</form>


<?php
require_once 'search_functions.php';
$cond = build_activities_filter_conditions(&$_POST);

$selectSQL = "SELECT
`activities`.`activities_id`,
`activities`.`suit_no`  as suit_no,
`activities`.`activities_date`,
`activities`.`details`,
`activities`.`next_activities_date`,
`activities`.`action_details`,
`activities_type`.`activities_type`,
`ulis_info`.`ulis_name` as ulis_name,
`activities`.`activity_type`,
`activities`.`next_activities_type`
FROM
`activities`
Inner Join `activities_type` ON `activities`.`activity_type` = `activities_type`.`activities_type_id`
Inner Join `ulis_info` ON `activities`.`ulis_info_id` = `ulis_info`.`ulis_info_id`
WHERE $cond
";

$rec = query($selectSQL);
$sl=0;


Then Create another file named it search_functions.php

function build_activities_filter_conditions($var,$alis_name=''){
    $ret = ' 1 ';
    extract($var);
    $ret .= ($from_date!="") ? " AND ".$alis_name."activities_date>='$from_date'" : "";
    $ret .= ($to_date!="") ? " AND ".$alis_name."activities_date<='$to_date'" : "";
    $ret .= ($ulis_no!="") ? " AND ".$alis_name."ulis_name LIKE '$ulis_no%'" : "";
    $ret .= ($suit_no!="") ? " AND ".$alis_name."suit_no='".$suit_no."'" : "";
    $ret .= ($activites_type!="") ? " AND ".$alis_name."activity_type='$activites_type'" : "";
        
    return $ret;
}


Upload files in PHP


You can easily Upload files in php.

$path_parts3 = pathinfo($_FILES['payment_document']['name']);
 mkdir("../documents/payment/payment_document/$pa_id");
 move_uploaded_file($_FILES['payment_document']['tmp_name'],
   "../documents/payment/payment_document/$pa_id/".$_FILES['payment_document']['name']);
 $payment_document = $_FILES['payment_document']['name'];

<form name="lbpfrm" action="" method="post" enctype="multipart/form-data">
<input type="file" name="payment_document" />
</form>

Upload multiple file

//echo sizeof($FILES['ulis_branch_info_doc'])." OOO ";
 for($i=0;$i<count($_FILES['ulis_branch_info_doc']['name']);$i++) {
     if($_FILES['ulis_branch_info_doc']['name'][$i]!='') {
   
 $path_parts = pathinfo($_FILES['ulis_branch_info_doc']['name'][$i]);
 mkdir("../documents/ulis/branch_info/$ulis_id");
 move_uploaded_file($_FILES['ulis_branch_info_doc']['tmp_name'][$i],
         "../documents/ulis/branch_info/$ulis_id/".$i.$_FILES['ulis_branch_info_doc']['name'][$i]);

      }
 }

Oct 12, 2011

Show multiple labels in combobox in php


function comboFurn($id)
{
   // echo "Testid - $id" ;
 

  // Searching for Levels of Categories
$checkParent = mysql_query("Select page_parent_id as parentid from psgfurn_pages where id = '$id' ") or die(mysql_error());
$dataParent = mysql_fetch_object($checkParent);

if ($dataParent->parentid !=0)
{
alert("1 yes");
$checkParent1 = mysql_query("Select page_parent_id as parentid from psgfurn_pages where id = '$dataParent->parentid' ") or die(mysql_error());
$dataParent1 = mysql_fetch_object($checkParent1);

if ($dataParent1->parentid !=0)
{
alert("2 yes");
$checkParent2 = mysql_query("Select page_parent_id as parentid from psgfurn_pages where id = '$dataParent1->parentid' ") or die(mysql_error());
$dataParent2 = mysql_fetch_object($checkParent2);

if ($dataParent2->parentid !=0)
{
alert("3 yes");
$mainCategory = "";
$parentCategory = "";
} else {
$mainCategory = $dataParent1->parentid;
$parentCategory = $dataParent->parentid;
}

} else {
$parentCategory = $id;
$mainCategory = $dataParent->parentid;
}

} else {
$parentCategory = "";
$mainCategory = $id;
}


// End Category




//alert("Main Category - $mainCategory /n Parent Category - $parentCategory");

/*   $only_main = $only_main;
   $layer = $layer;



if(!empty($only_main)){
$aq = "AND id = $only_main";
}
*/
// For Main Category
    $q = mysql_query("Select id, page_name from psgfurn_pages where _group ='main'") or die(mysql_error());

    while($d = mysql_fetch_object($q))
    {
$selected = "";
$categoryMessage = "";
$value = $d->id;

/* if($chk_main_layer == 1){

}else{

  }*/
($d->id == $mainCategory)  ?  $selected = "selected" : $selected = "";
if ($d->id == $id)
{
$categoryMessage = " (Dont Select)";
$value = $only_main;
}

echo "<option value='$value' $selected>$d->page_name $categoryMessage</option>";


// For 2nd Level Category
$q2 = mysql_query("Select id, page_name from psgfurn_pages where parentid = '$d->id' and _group = 'sub' ") or die(mysql_error());
if (mysql_num_rows($q) !=0)
{
while($d2 = mysql_fetch_object($q2))
{
$selected = "";
$categoryMessage = "";
$value = $d2->id;

($d2->id == $parentCategory)  ?  $selected = "selected" : $selected = "";


if ($d2->id == $id)
{
$categoryMessage = " (Already Selected)";
$value = $d2->id;
}

echo "<option value='$value' $selected>&nbsp;&nbsp;&nbsp;&nbsp; - $d2->category_name $categoryMessage</option>";


// For 3rd Level Category
/*$q3 = mysql_query("Select id, category_name from psgfurn_category where parentid = '$d2->id' and _group = 'sub'  ") or die(mysql_error());

if ((mysql_num_rows($q3) !=0) && ($layer != 2))
{
while($d3 = mysql_fetch_object($q3))
{
if ($d3->id != $id)
echo "<option value='$d3->id' >&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; -- $d3->category_name</option>";
// echo "<option value='$d->id-$d2->id-$d3->id' >&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; -- $d3->category_name</option>";
}
}*/

}
}

    }

//End Combox Box Looping
}

Sep 18, 2011

Keep The Searched Values In The Fields In PHP



<script type="text/javascript">
  $(document).ready(function(){
      var __postBack =  '<?php echo json_encode($_POST); ?>';
      var obj = jQuery.parseJSON(__postBack);
     
      $.each(obj,function(key, value){
          $("input[name="+key+"]").val(value);
          $("select[name="+key+"]").val(value);
          $("textarea[name="+key+"]").val(value);
     });
  });
</script>

How to load data in a combobox without reloading the page from other page in PHP



Write the code in page a.php
<select name="company_id" id="company_id" >
                                                   <option></option>
                                                  
                                                   <?php
                                                   $getCompany = "select customer_id, company_name from customer WHERE customet_type = 1";
                                                   $getCompanyResult = mysql_query($getCompany);
                                                   while($getCompanyRows = mysql_fetch_object($getCompanyResult)){
                                                   ?>
                                                   <option value="<?php echo $getCompanyRows->customer_id ; ?>" <?php if($getCompanyRows->customer_id == $var->company_id){ echo "selected"; } ?> ><?php echo $getCompanyRows->company_name ; ?></option>
                                                  
                                                   <?php
                                                   }
                                                   ?>
                                                   </select>
<a href="#" onClick="window.open('b.php?hide_menu=1','popup','width=960,height=530,scrollbars=no,scrollbars=yes,toolbar=no,directories=no,location=no,menubar=no,status=no,left=300,top=300'); return false">Add New Data</a>

In Page B:
Write some code to insert the data in database.
<script language="javascript">
//alert(window.opener.document.getElementById('company_id').value);
var optionstr = '<option></option>';
   <?php
   $getCompany = "select customer_id, company_name from customer WHERE customet_type = 1";
   $getCompanyResult = mysql_query($getCompany);
   while($getCompanyRows = mysql_fetch_object($getCompanyResult)){
   ?>
   optionstr +='<option value="<?php echo $getCompanyRows->customer_id ; ?>"><?php echo $getCompanyRows->company_name ; ?></option>';
   <?php
   }
   ?>
window.opener.document.getElementById('company_id').innerHTML= optionstr;
</script>


Aug 13, 2011

Using CASE in mysql


Some days ago i have face a little problem in sql query.
The problem was say i have a table like this

Create the table and dumping the data

Create table student_marks(
id int(10) not null auto_increment,
subject_name varchar(10),
student_name varchar(10),
marks varchar(12),
primary key(id)
);

INSERT INTO student_marks(subject_name, student_name, marks)
Values('Bangla', 'sagar', '75');

INSERT INTO student_marks(subject_name, student_name, marks)
Values('Bangla', 'jubayer', '80');

INSERT INTO student_marks(subject_name, student_name, marks)
Values('Bangla', 'sujon', '72');

INSERT INTO student_marks(subject_name, student_name, marks)
Values('English', 'sagar', '70');

INSERT INTO student_marks(subject_name, student_name, marks)
Values('English', 'jubayer', '85');


mysql> select * from student_marks;
+----+--------------+--------------+-------+
| id | subject_name | student_name | marks |
+----+--------------+--------------+-------+
|  1 | Bangla       | sagar        | 75    |
|  2 | Bangla       | jubayer      | 80    |
|  3 | Bangla       | sujon        | 72    |
|  4 | English      | sagar        | 70    |
|  5 | English      | jubayer      | 85    |
+----+--------------+--------------+-------+
5 rows in set (0.03 sec)

And the output will be

+--------------+--------+---------+
| student_name | Bangla | English |
+--------------+--------+---------+
| jubayer      |     80 |      85 |
| sagar        |     75 |      70 |
| sujon        |     72 |       0 |
+--------------+--------+---------+
3 rows in set (0.06 sec)

To solve this problem we have to use if/else or CASE in the query.

So the query will be like this:

mysql>  SELECT student_name,
    ->      SUM(CASE when subject_name LIKE 'bangla' THEN marks else 0 end) as B
angla,
    ->      SUM(CASE when subject_name LIKE 'english' THEN marks else 0 end) as
English
    ->      FROM student_marks GROUP BY student_name;

This query give me the out put what i expected....
Now i am facing a new problem... if the subject_name is number of n then what will be th solution?

Find how much old you r:
select *, case when ((datediff(DATE(NOW()), dob)/365)>18) then 1 else 0 end as adult from users;

Dec 29, 2010

Login Script (Rebember Me)



To make a login system with remember me option follow the steps and try to understand the code...

step1: Make a database and a table.
DROP DATABASE loginDB;
CREATE DATABASE loginDB;
USE loginDB;
CREATE TABLE tbl_Login(
id int(2) NOT NULL AUTO_INCREMENT,
email varchar(45) NOT NULL,
password varchar(45) NOT NULL,
primary key (id)
);
insert into tbl_Login (email,password) VALUES ('jubayer1',SHA('123456'));

step2: Create a file named it config.php then type the code.This file the database connection.

<?php
$connect = mysql_connect('localhost','root','1111111111') or die(mysql_error());
$selectDB = mysql_select_db('loginDB') or die(mysql_error());
?>

step3: Create a file named it login.php.
<?
require_once('config.php');
session_start();
$msg = "";
if(isset($_POST['posted'])){
$email = mysql_escape_string(trim($_POST['email']));
$password = mysql_escape_string(trim($_POST['password']));
if(!empty($email) && !empty($password)){
$getInfo = "SELECT * FROM tbl_Login WHERE email='$email' AND password=SHA('$password')";
$result = mysql_query($getInfo) or die(mysql_error());
if(mysql_num_rows($result)==1){
while($rows = mysql_fetch_array($result)){
$_SESSION['email'] = $rows['email'];
$_SESSION['password'] = $rows['password'];
if(isset($_POST['rebember'])){
setcookie('email', $rows['email'], time() + (60 * 60 * 24 * 7));    // expires in 7 days
setcookie('password', $rows['password'], time() + (60 * 60 * 24 * 7));  // expires in 7 days
}
$home = "logged_user.php";
header ('Location:'.$home);
}
}else{
 $msg = "Not found in the database...";
}
}else{
 $msg = "Empty password/email";
}
}
?>
<html>
<head>
<title>Login</title>
</head>
<body>
<table width="50%">
<tr><td>
<fieldset><legend>Login</legend>
<? echo $msg; ?>
<form name="loginFrm" action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">
<label>Email</label>&nbsp;<input type="text" name="email" /><br /><br />
<label>Password</label>&nbsp;<input type="password" name="password" /><br />
<input type="hidden" name="posted" value="true" />
<label><input type="checkbox" name="rebember" value="true" /></label>&nbsp;<label>Rebember me for seven days</label><br />
<input type="reset" name="reset" value="Reset" />&nbsp;<input type="submit" name="submit" value="Login" /><br />
</form>
<label><a href="#"><label>Forgot password</label></a>
</fieldset>
</td>
</tr>
</table>
</body>
</html>






step4: Create a file named it auth_user.php

<?php
session_start();
if($_SESSION['email'] == "" && $_SESSION['password']==""){
$url = 'login.php';
header('Location:'.$url);
}
?>

step5: Create a file named it logOut.php

<?php
session_start();
session_unset();
session_destroy();
if(isset($_COOKIE['email']) && isset($_COOKIE['password'])){
   setcookie("email", "", time()-60*60*24*100, "/");
   setcookie("password", "", time()-60*60*24*100, "/");
}
if($_SESSION['email'] !="" && $_SESSION['password'] !=""){
$url = 'login.php';
header('Location:'.$url);
}else{
$url = 'login.php';
header('Location:'.$url);
}
?>

step6: Create a file named it logged_user.php

<?
session_start();
include 'auth_user.php';
$user = $_SESSION[email];
echo '<br>';
?>
&nbsp;&nbsp;&nbsp;&nbsp;<p align="right"><a href="logOut.php">logOut</a></p>
<h1>Hello [<?=$user;?>]</h1>
<hr />