Home

Friday, July 20, 2012

MySQL LEFT, RIGHT JOIN tutorial

For example we have two tables: products and buyers with the following structures.
Table products:
mysql> SELECT * FROM products;
+----+--------------+--------------+
| id | product_name | manufacturer |
+----+--------------+--------------+
|  1 | Shoes        | Company1     |
|  2 | Laptop       | Company2     |
|  3 | Monitor      | Company3     |
|  4 | DVD          | Company4     |
+----+--------------+--------------+
4 rows in set (0.00 sec)
Table buyers:
mysql> SELECT * FROM buyers;
+----+------+------------+----------+
| id | pid  | buyer_name | quantity |
+----+------+------------+----------+
|  1 |    1 | Steve      |        2 |
|  2 |    2 | John       |        1 |
|  3 |    3 | Larry      |        1 |
|  4 |    3 | Michael    |        5 |
|  5 | NULL | Steven     |     NULL |
+----+------+------------+----------+
5 rows in set (0.00 sec)

Left Join

mysql> SELECT buyer_name, quantity, product_name FROM buyers LEFT JOIN products ON
 buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve      |        2 | Shoes        |
| John       |        1 | Laptop       |
| Larry      |        1 | Monitor      |
| Michael    |        5 | Monitor      |
| Steven     |     NULL | NULL         |
+------------+----------+--------------+
5 rows in set (0.00 sec)

What happened?
Mysql starts with the left table (buyers). For each row from the table buyers mysql scans the table products, finds the id of the product and returns the product name. Then the product name is joined with the matching row from the table buyers. For unmatched rows it returns null.
To make it simpler, the above query is same as (except the unmatched rows are not returned):
mysql> SELECT buyers.buyer_name, buyers.quantity, products.product_name FROM buyer
s,products WHERE buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve      |        2 | Shoes        |
| John       |        1 | Laptop       |
| Larry      |        1 | Monitor      |
| Michael    |        5 | Monitor      |
+------------+----------+--------------+
4 rows in set (0.00 sec)

Right Join

mysql> SELECT buyer_name, quantity, product_name FROM buyers RIGHT JOIN products ON 
buyers.pid=products.id;
+------------+----------+--------------+
| buyer_name | quantity | product_name |
+------------+----------+--------------+
| Steve      |        2 | Shoes        |
| John       |        1 | Laptop       |
| Larry      |        1 | Monitor      |
| Michael    |        5 | Monitor      |
| NULL       |     NULL | DVD          |
+------------+----------+--------------+
5 rows in set (0.00 sec)
What happens here is Mysql starts with the Right table (products). For each id from the table products MySQL scans the left table - buyers to find the matching pid. When it finds the matching pid it returns the buyer_name and the quantity. For unmatched rows it returns null. From my example above it returns NULL for DVD because no one bought DVD.

Monday, April 30, 2012

Uploading Files Like GMail Attachments

<html>
<head>
<title>E-mail with Attachment</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
var upload_number = 2;
function addFileInput() {
     var d = document.createElement("div");
     var file = document.createElement("input");
     file.setAttribute("type", "file");
     file.setAttribute("name", "attachment"+upload_number);
     d.appendChild(file);
     document.getElementById("moreUploads").appendChild(d);
     upload_number++;
}
</script>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){

 
   $to="rathod.dhirendra@gmail.com";
   $subject="E-mail with attachment";
 
   $from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";

  
   $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

 
   $headers = "From: $from\r\n" .
   "MIME-Version: 1.0\r\n" .
      "Content-Type: multipart/mixed;\r\n" .
      " boundary=\"{$mime_boundary}\"";

   $message=$_POST['question'];

 
   $message = "This is a multi-part message in MIME format.\n\n" .
      "--{$mime_boundary}\n" .
      "Content-Type: text/html; charset=\"iso-8859-1\"\n" .
      "Content-Transfer-Encoding: 7bit\n\n" .
   $message . "\n\n";

   // now we'll process our uploaded files
   foreach($_FILES as $userfile){    
      $tmp_name = $userfile['tmp_name'];
      $type = $userfile['type'];
      $name = $userfile['name'];
      $size = $userfile['size'];

    
      if (file_exists($tmp_name)){
         // check to make sure that it is an uploaded file and not a system file
         if(is_uploaded_file($tmp_name)){
    
            // open the file for a binary read
            $file = fopen($tmp_name,'rb');
    
            // read the file content into a variable
            $data = fread($file,filesize($tmp_name));

            // close the file
            fclose($file);
    
            // now we encode it and split it into acceptable length lines
            $data = chunk_split(base64_encode($data));
         }    

         $message .= "--{$mime_boundary}\n" .
            "Content-Type: {$type};\n" .
            " name=\"{$name}\"\n" .
            "Content-Disposition: attachment;\n" .
            " filename=\"{$fileatt_name}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n";
      }
   }

   $message.="--{$mime_boundary}--\n";
   // now we just send the message
   if (@mail($to, $subject, $message, $headers))
      echo "Message Sent";
   else
      echo "Failed to send";
} else {
?>
<p>Send an e-mail with an attachment:</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="form1">
   <p>Your name: <input type="text" name="fromname"></p>
   <p>Your e-mail: <input type="text" name="fromemail"></p>
   <p>Message : <textarea  name="question" maxlength="1000" cols="25" rows="6"></textarea>  
   <input type="file" name="attachment" id="attachment" onchange="document.getElementById('moreUploadsLink').style.display = 'block';" />
<div id="moreUploads"></div>
<div id="moreUploadsLink" style="display:none;"><a href="javascript:addFileInput();">Attach another File</a></div>

   <p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>
</body>
</html>

Saturday, April 28, 2012

PHP mail form with multiple attachments

<html>
<head>
<title>E-mail with Attachment</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){

   // we'll begin by assigning the To address and message subject
   $to="rathod.dhirendra@gmail.com";
   $subject="E-mail with attachment";

   // get the sender's name and email address
   // we'll just plug them a variable to be used later
   $from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";

   // generate a random string to be used as the boundary marker
   $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

   // now we'll build the message headers
   $headers = "From: $from\r\n" .
   "MIME-Version: 1.0\r\n" .
      "Content-Type: multipart/mixed;\r\n" .
      " boundary=\"{$mime_boundary}\"";

   // here, we'll start the message body.
   // this is the text that will be displayed
   // in the e-mail
   $message=$_POST['question'];

   // next, we'll build the invisible portion of the message body
   // note that we insert two dashes in front of the MIME boundary
   // when we use it
   $message = "This is a multi-part message in MIME format.\n\n" .
      "--{$mime_boundary}\n" .
      "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
      "Content-Transfer-Encoding: 7bit\n\n" .
   $message . "\n\n";

   // now we'll process our uploaded files
   foreach($_FILES as $userfile){
      // store the file information to variables for easier access
      $tmp_name = $userfile['tmp_name'];
      $type = $userfile['type'];
      $name = $userfile['name'];
      $size = $userfile['size'];

      // if the upload succeded, the file will exist
      if (file_exists($tmp_name)){

         // check to make sure that it is an uploaded file and not a system file
         if(is_uploaded_file($tmp_name)){
    
            // open the file for a binary read
            $file = fopen($tmp_name,'rb');
    
            // read the file content into a variable
            $data = fread($file,filesize($tmp_name));

            // close the file
            fclose($file);
    
            // now we encode it and split it into acceptable length lines
            $data = chunk_split(base64_encode($data));
         }
    
         // now we'll insert a boundary to indicate we're starting the attachment
         // we have to specify the content type, file name, and disposition as
         // an attachment, then add the file content.
         // NOTE: we don't set another boundary to indicate that the end of the
         // file has been reached here. we only want one boundary between each file
         // we'll add the final one after the loop finishes.
         $message .= "--{$mime_boundary}\n" .
            "Content-Type: {$type};\n" .
            " name=\"{$name}\"\n" .
            "Content-Disposition: attachment;\n" .
            " filename=\"{$fileatt_name}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n";
      }
   }
   // here's our closing mime boundary that indicates the last of the message
   $message.="--{$mime_boundary}--\n";
   // now we just send the message
   if (@mail($to, $subject, $message, $headers))
      echo "Message Sent";
   else
      echo "Failed to send";
} else {
?>
<p>Send an e-mail with an attachment:</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"
   enctype="multipart/form-data" name="form1">
   <p>Your name: <input type="text" name="fromname"></p>
   <p>Your e-mail: <input type="text" name="fromemail"></p>
   <p>Mod List: <textarea  name="question" maxlength="1000" cols="25" rows="6"></textarea>
   <p>File: <input type="file" name="file1"></p>
   <p>File: <input type="file" name="file2"></p>
   <p>File: <input type="file" name="file3"></p>
   <p>File: <input type="file" name="file4"></p>
   <p>File: <input type="file" name="file5"></p>
   <p>File: <input type="file" name="file6"></p>
   <p>File: <input type="file" name="file7"></p>
   <p>File: <input type="file" name="file8"></p>
   <p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>
</body>
</html>

Sunday, March 18, 2012

How to count day between two dates in php

$startTimeStamp = strtotime("2012/03/01");
$endTimeStamp = strtotime("2012/03/15");

$timeDiff = abs($endTimeStamp - $startTimeStamp);

$numberDays = $timeDiff/86400;  // 86400 seconds in one day
// and you might want to convert to integer
$numberDays = intval($numberDays);

Wednesday, March 7, 2012

Get value of radio button using jQuery

...
<input type="radio" name="age" value="10" />
<input type="radio" name="age" value="20" checked="checked" />
<input type="radio" name="age" value="30" />
...
 
//javascript code
 
<script type="text/javascript">
<!--
    // displays the selected radio button in an alert box
    alert($('input[name=age]:checked').val())
-->
 
var age = $("input[name='age']:checked").val(); 
alert(age);
</script>

Friday, January 27, 2012

Holding the mouse over this marquee stops it from scrolling.

<marquee title="Holding your cursor over this stops the marquee."
            ONMOUSEOVER="this.stop();"
            ONMOUSEOUT="this.start();">
         <H3>Test Marquee</H3>
         <P>Holding the mouse over this marquee stops it from scrolling.</P>
</MARQUEE>

Monday, January 23, 2012

Delete Records with using jQuery and Ajax.

Index.php
<ol class="update">
<?php
$sql="select * from updates order by msg_id desc";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
$message=stripslashes($row["message"]);
$msg_id=$row["msg_id"]; 
?>
<li>
<?php echo $message; ?>
<a href="#" id="<?php echo $msg_id; ?>" class="delete_button">X</a>
</li>
<?php
}
?>
</ol>
 
jQuery code
 
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delete_button").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();

$.ajax({
type: "POST",
url: "deleteajax.php",
data: dataString,
cache: false,

success: function()
{
if(id % 2)
{
parent.fadeOut('slow', function() {$(this).remove();});
}
else
{
parent.slideUp('slow', function() {$(this).remove();});
}
}
});

return false;
});
});
</script>
 
deleteajax.php
<?php
if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
$sql = "delete from updates where msg_id='$id'";
mysql_query( $sql);
}
?>
 
 

Delete Records with Effect using jQuery and Ajax in php

Index.php
<ol class="update">
<?php
$sql="select * from updates order by msg_id desc";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
$message=stripslashes($row["message"]);
$msg_id=$row["msg_id"]; 
?>
<li>
<?php echo $message; ?>
<a href="#" id="<?php echo $msg_id; ?>" class="delete_button">X</a>
</li>
<?php
}
?>
</ol>
jQuery code
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js
"></script>
<script type="text/javascript" src="jquery.color.js"></script>
<script type="text/javascript">
$(function() {
$(".delete_button").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();

$.ajax({
type: "POST",
url: "deleteajax.php",
data: dataString,
cache: false,
beforeSend: function()
{
parent.animate({'backgroundColor':'#fb6c6c'},300).animate({ opacity: 0.35 }, "slow");;
},
success: function()
{
parent.slideUp('slow', function() {$(this).remove();});
}
});

return false;
});
});
</script>
deleteajax.php
<?php
if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
$sql = "delete from updates where msg_id='$id'";
mysql_query( $sql);
}
?>
 

Saturday, January 21, 2012

Example of a SQL Injection Attack.

The easiest way for the login.php to work is by building a database query that looks like this:

SELECT id
FROM logins
WHERE username = '$username'
AND password = '$password’



If the variables $username and $password are requested directly from the user's input, this can easily be compromised. Suppose that we gave "Joe" as a username and that the following string was provided as a password: anything' OR 'x'='x


SELECT id
FROM logins
WHERE username = 'Joe'
AND password = 'anything' OR 'x'='x'



As the inputs of the web application are not properly sanitised, the use of the single quotes has turned the WHERE SQL command into a two-component clause.

The 'x'='x' part guarantees to be true regardless of what the first part contains.

This will allow the attacker to bypass the login form without actually knowing a valid username / password combination!

To stop this kind of attack, you MUST use some inbuilt PHP functions. The one to use for this kind of attack is:
mysql_real_escape_string( );

$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

Tuesday, January 17, 2012

How to convert time according to timezone in php

///Your time zone mention here
$myDateTime = new DateTime('2012-01-12 11:23', new DateTimeZone('Asia/Kolkata'));

///Want to desire time
$myDateTime->setTimezone(new DateTimeZone('Australia/Sydney'));

/* Like another Example */
//$myDateTime->setTimezone(new DateTimeZone('Asia/Baku'));
//$myDateTime->setTimezone(new DateTimeZone('Europe/London'));


echo $myDateTime->format('Y-m-d h:i');?>


Monday, January 16, 2012

Create a CSV file from MySQL with PHP

mysql_connect($server, $login, $password);
mysql_select_db($db);

$fp = fopen("test.csv", "w");

$res = mysql_query("SELECT * FROM $table");

// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
    $line .= $comma . '"' . str_replace('"', '""', $name) . '"';
    $comma = ",";
}
$line .= "\n";
fputs($fp, $line);

// remove the result pointer back to the start
mysql_data_seek($res, 0);

// and loop through the actual data
while($row = mysql_fetch_assoc($res)) {
   
    $line = "";
    $comma = "";
    foreach($row as $value) {
        $line .= $comma . '"' . str_replace('"', '""', $value) . '"';
        $comma = ",";
    }
    $line .= "\n";
    fputs($fp, $line);
   
}

fclose($fp);

Friday, January 13, 2012

How i get the current system time using php?

<?php
$time_now=mktime(date('h')+5,date('i')+30,date('s'));
print "<br>".date('h:i:s',$time_now);
?>

Tuesday, January 10, 2012

How to show and hide div tag using css

<style type="text/css" media="screen">
  
  #slideout {
   position: fixed;
   top: 40px;
   left: 0;
   width: 35px;
   padding: 12px 0;
   text-align: center;
   background: #6DAD53;
   -webkit-transition-duration: 0.3s;
   -moz-transition-duration: 0.3s;
   -o-transition-duration: 0.3s;
   transition-duration: 0.3s;
   -webkit-border-radius: 0 5px 5px 0;
   -moz-border-radius: 0 5px 5px 0;
   border-radius: 0 5px 5px 0;
  }
  #slideout_inner {
   position: fixed;
   top: 40px;
   left: -250px;
   background: #6DAD53;
   width: 200px;
   padding: 25px;
   height: 130px;
   -webkit-transition-duration: 0.3s;
   -moz-transition-duration: 0.3s;
   -o-transition-duration: 0.3s;
   transition-duration: 0.3s;
   text-align: left;
   -webkit-border-radius: 0 0 5px 0;
   -moz-border-radius: 0 0 5px 0;
   border-radius: 0 0 5px 0;
  }
  #slideout_inner textarea {
   width: 190px;
   height: 100px;
   margin-bottom: 6px;
  }
  #slideout:hover {
   left: 250px;
  }
  #slideout:hover #slideout_inner {
   left: 0;
  }
  
 </style>
 
<div id="slideout">
  <img src="image.jpg" alt="Feedback" />
  <div id="slideout_inner">
   <form>
    <textarea></textarea>
    <input type="submit" value="Post feedback"></input>
   </form>
  </div>
 </div> 

How to show and hide div tag using Jquery

<script type="text/javascript">//<![CDATA[
$(window).load(function(){
//$('#song_click').mouseover(function()
$('#song_click').click(function()
{
    $("#song_panel").animate({width:'toggle'},500);      
});
});//]]>
</script>
<div style="display: none;" id="song_panel">
   Test
</div>
<div id="song_click"></div>
rathoddhirendra.blogspot.com-Google pagerank and Worth