Flicker Images

Find programmers and grapic design experts at ScriptLance.com

Tuesday, November 22, 2011

Deleting Duplicate data from MySQL database in PHP

I am making an application from data import from excel file. In application user may be import several time or different file may be contains same data. But I always need unique data row from other calculation. So I badly need delete Duplicated row from table after importing data from excel file.
For Solve this problem I found couple of solution on web.

Solution 1: If table contain a primary key
Table :

 
  create table TableName1 (
  ID int(11) NOT NULL AUTO_INCREMENT ,
  CODE varchar(20) , 
  NAME varchar(100) ,
  PRIMARY KEY (ID)
  ) 
  
Data
ID CODE NAME
1 A1001 Mahfuz
2 A1002 Lemon
3 A1001 Mahfuz
4 A1002 Lemon
5 A1003 Babu


 <?php
 $conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}
if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}



$sql = "DELETE FROM TableName1
USING TableName1, TableName1 AS vtable
WHERE vtable.id > TableName1.id
AND TableName1.CODE = vtable.CODE
And TableName1.NAME = vtable.NAME";

mysql_query($sql);

$sql_check = "SELECT NAME,
COUNT(NAME) AS NumOccurrences
FROM TableName1
GROUP BY NAME
HAVING ( COUNT(NAME) > 1 )";
$result = mysql_query($sql_check);

if (mysql_num_rows($result) == 0) {
    echo "No Duplicate rows found";
}
?>

Solution 2: If table have no primary key
Table :

 create table TableName1 ( 
  CODE varchar(20) , 
  NAME varchar(100)
)
Data
CODE NAME
A1001 Mahfuz
A1002 Lemon
A1001 Mahfuz
A1002 Lemon
A1003 Babu


 <?php

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}
if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}



$sql1 = " CREATE TEMPORARY TABLE temp_TableName1 as select * from TableName1 group By code,name";

mysql_query($sql1);

$sql2 = " TRUNCATE TABLE TableName1 ";

mysql_query($sql2);

$sql3 = " INSERT INTO TableName1 SELECT * FROM temp_TableName1 ";

mysql_query($sql3);

$sql_check = "SELECT NAME,
COUNT(NAME) AS NumOccurrences
FROM TableName1
GROUP BY NAME
HAVING ( COUNT(NAME) > 1 )";
$result = mysql_query($sql_check);

if (mysql_num_rows($result) == 0) {
    echo "No Duplicate rows found";
}

?>
Share:

Sunday, November 20, 2011

what is difference between mysql_fetch_assoc, mysql_fetch_row,mysql_fetch_object and mysql_fetch_array


Definition :

  • mysql_fetch_array():-

    Fetch a result row as an associative array, a numeric array, or both by default it fetches both.
Returns an array of strings that corresponds to the fetched row, or FALSE  if there are no more rows. The type of returned array depends on how result_typeis defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works).
  • mysql_fetch_row() :-

    Get a result row as an numeric array
Returns an numerical array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array.
  • mysql_fetch_object :-

    Fetch a result row as an object
Returns an object with string properties that correspond to the fetched row, orFALSE;if there are no more rows.
  • mysql_fetch_assoc() :-

    Fetch a result row as an associative array
Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead. mysql_fetch_assoc() is equivalent to callingmysql_fetch_array() with MYSQL_ASSOC for the optional second parameter. It only returns an associative array.

Example:

<?php

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}
  
if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}

$sql = "SELECT id as userid, fullname, userstatus 
        FROM   sometable
        WHERE  userstatus = 1";

$result = mysql_query($sql);

if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//       then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_array ($result)) {
    echo $row[0];
    echo $row[1];
    echo $row[2];
}

while ($row = mysql_fetch_array ($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

while ($row = mysql_fetch_array ($result)) {
    echo $row[0];
    echo $row["fullname"];
    echo $row[2];
}

while ($row = mysql_fetch_row($result)) {
    echo $row[0];
    echo $row[1];
    echo $row[2];
}

while ($row = mysql_fetch_object($result)) {
    echo $row->userid;
    echo $row->fullname;
    echo $row->userstatus;
}

while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}


mysql_free_result($result);
?>


Performance
Using both  mysql_fetch_array() and mysql_fetch_assoc()  is not significantly slower than using mysql_fetch_row(),
Speed-wise, the function is identical to mysql_fetch_array(), and almost as quick as mysql_fetch_row() (the difference is insignificant).
mysql_fetch_object() is similar to mysql_fetch_array(), with one difference - an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).
Share:

Thursday, November 17, 2011

How to create a 'Close page' message for unsaved web form data?




I'm creating an PHP web application and I want to implement logic to warn the user when they are navigating away from a page they've edited. I found some solution on the .


For this solution we bound a JavaScript function to the unload event:
 window.onbeforeunload  

I use following code in different aspect
For all type of Input .


$(document).ready(function() { 
    $(":input").one("change", function() { 
        window.onbeforeunload = function() { return 'You will lose data changes.'; } 
    }); 
    $('.noWarn').click(function() { window.onbeforeunload = null; }); 
});

Your input elements probably do not exist when the code is executed. Try using the .live function to detect changes on all input elements, or wrap your code in a $(document).ready() handler.

$('input').live("change", function () {
    window.onbeforeunload = function () { return "Your changes have not been saved?" };
});

For specific input type on body

$(document).ready(function() {

    //----------------------------------------------------------------------
    // Don't allow us to navigate away from a page on which we're changed
    //  values on any control without a warning message.  Need to class our 
    //  save buttons, links, etc so they can do a save without the message - 
    //  ie. CssClass="noWarn"
    //----------------------------------------------------------------------
    $('input:text,input:checkbox,input:radio,textarea,select').one('change', function() {
        $('BODY').attr('onbeforeunload',
        "return 'Leaving this page will cause any unsaved data to be lost.';");
    });

    $('.noWarn').click(function() { $('BODY').removeAttr('onbeforeunload'); });

});

Best solution for form base: In this solution if you are change something in your form then when you want to leave from this page user can get a message for confirmation.

function formIsDirty(form)
      {
          for (var i = 0; i < form.elements.length; i++)
          {
              var element = form.elements[i];
              var type = element.type;
              if (type == "checkbox" || type == "radio")
              {
                  if (element.checked != element.defaultChecked)
                  {
                      return true;
                  }
              }
              else if (type == "hidden" || type == "password" || type == "text" ||
                       type == "textarea")
              {
                  if (element.value != element.defaultValue)
                  {
                      return true;
                  }
              }
              else if (type == "select-one" || type == "select-multiple")
              {
                  for (var j = 0; j < element.options.length; j++)
                  {
                      if (element.options[j].selected !=
                          element.options[j].defaultSelected)
                      {
                          return true;
                      }
                  }
              }
          }
          return false;
      }

      window.onbeforeunload = function(e)
      {
          e = e || window.event;  
// You put your from ID
          if (formIsDirty(document.forms['fromid'])) 
          {
              // For IE and Firefox
              if (e)
              {
                  e.returnValue = "You have unsaved changes.";
              }
              // For Safari
              return "You have unsaved changes.";
          }
      };

Share:

Wednesday, November 16, 2011

how we get current date ,month and year( C#.net)



You can get Current day, month, and year using this class


public class MY_Date
{
    /// <summary>
    /// Current Month
    /// </summary>
    public static string CurMonth = GetCurrentMonth();
        /// <summary>
        /// Current Year
        /// </summary>
        public static string CurYear =GetCurrentYear();

    /// Current Month
    /// </summary>
    public static DateTime Yesterday = GetYesterday();
        /// <summary>
        /// Current Year
        /// </summary>
    public static DateTime Tomorrow = GetTomorrow();
     
private static string GetCurrentYear()
{
DateTime dt = DateTime.Now;
            return dt.Year.ToString();
        }
private static string GetCurrentMonth()
{
DateTime dt = DateTime.Now;
            return dt.Month.ToString();
        }
/// <summary>
        /// last day of the year for today.
        /// </summary>
        static DateTime LastDayOfYear()
        {
   return LastDayOfYear(DateTime.Today);
        }

        /// <summary>
        /// last day of the year for the selected day's year.
        /// </summary>
        static DateTime LastDayOfYear(DateTime d)
        {
   // 1
   // Get first of next year
   DateTime n = new DateTime(d.Year + 1, 1, 1);
   // 2
   // Subtract 1 from it
   return n.AddDays(-1);
        }
    /// <summary>
        /// Gets the first day of the current year.
        /// </summary>
        static DateTime FirstDayOfYear()
        {
   return FirstDayOfYear(DateTime.Today);
        }

        /// <summary>
        /// Finds the first day of year of the specified day.
        /// </summary>
        static DateTime FirstDayOfYear(DateTime y)
        {
   return new DateTime(y.Year, 1, 1);
        }
   
    /// <summary>
        /// Gets the next day, tomorrow.
        /// </summary>
        private static DateTime GetTomorrow()
        {
   return DateTime.Today.AddDays(1);
        }
   /// <summary>
        /// Gets the previous day to the current day.
        /// </summary>
        private static DateTime GetYesterday()
        {
   // Add -1 to now
   return DateTime.Today.AddDays(-1);
        }

}
Share:

Game Reviews

BTemplates.com

Powered by Blogger.

Search This Blog

Video Of Day

Find Us OIn Facebook

Blogroll

Contact

Tackle the Web with up to 5 new .COMs, $5.99 for the 1st year!

Advertisement