How to replace line break with comma(,) or something else in notepad.

I want to remove line break and replace it with comma(,) in note pad. Like below :


And i want to turn them into a paragraph with a comma at the end of each one? Like below:





Sollution :

Steps :

  1.  Open the find and replace dialog. CTRL+H
  2.  Then select match regular expressions at the bottom.
  3.  Search for this [\r\n]+
  4.  Replace with ,


If you like this post don't forgot to leave a comment.

Chears 
Happy coading :)

Export data into CSV file using PHP

If you want to export data from mysql or any other database using php. Then first time its looking very complex but here you can find easy solution of every complex looking problem.

What do you need :

You need to arrange your data into array in key value combination. like below screne shot format  -


Explain :  In the above screne shot Index (Student, Net Fees, Total Payments, Balance Due, Current Month, Last Payment) will be display the heading into CSV.


Below Is My Functions:
 

 // This Function Is Used To Write Csv File.
 function array2csv(array &$array)
 {
    if (count($array) == 0) {
   return null;
    }
    $df = fopen("php://output", 'w');
    fputcsv($df, array_keys(reset($array)));
    foreach ($array as $row) {
    fputcsv($df, $row);
    }
    fclose($df);
 }

 
 // This Function Is Used To Force Download The File.
 function forceDownload($filename) 
  {
      $now = date("D, d M Y H:i:s");
      header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
      header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
      header("Last-Modified: {$now} GMT");
        // force download  
      header("Content-Type: application/force-download");
      header("Content-Type: application/octet-stream");
      header("Content-Type: application/download");
      // disposition / encoding on response body
      header("Content-Disposition: attachment;filename={$filename}");
      header("Content-Transfer-Encoding: binary");
  } 

 
Method Of Uses : You just need to pass your array into this function and rest of 
work it do its self.
 
Calling of function : 
 
<?php
 
//Suppose my above screne shot data is stored into $newArr.

forceDownload("Fee&discountReport_" . date("Y-m-d") . ".csv");
echo array2csv($newArr);
die();
 
?>
 
 
Your csv will be look something like below screneshot: 
 
 
 
 
If you like this post please don't forget to leave a comment.
 
Chears 
Happy Coding :) 
 

How to show loader while actual image is downloading

When internet is slow and image size is big then its take some time to display compleate image. During this time no image is showing. If you want to display a loading image untill image is not loading compleately. Just add a background image to all images using css: 
Like below :-



Below is the css code :


#prodlist img {
  background: url("../image/imgloading.gif") no-repeat scroll center center rgba(0, 0, 0, 0);
}



If you like this post don't forgot to post a comment. 

Chears :)

Happy coding ..

How To Import Database From Command Prompt

When a database size is very big and then you are trying to import it using mysql. Then it can't be imported it display several errors like "MySQL server has gone away obstructing import of large dumps" or "Exceeds Max Allowed Packet for MySQL" or some thing else. 
The easy solution to resolve these errors you have to import your data threw command prompt. Below is the steps to import database using command prompt :-




Steps :

1- Run command Prompt By ctrl+R if your operating system is window.

2- Go to bin folder of mysql in your server. In my scenario i installed wamp server in C drive.

C:\wamp\www\bin\mysql\mysql5.5.24\bin\

Command Syntax :

   C:\wamp\www\bin\mysql\mysql5.5.24\bin\mysql -u -p databaseName < pathOfYourSqlFileYouWantToImport >


Example :

C:\wamp\www\bin\mysql\mysql5.5.24\bin\mysql -u root -p careyguides < d:/carey_guides.sql  

Now press enter and then its ask your database password. In my scenario my database username is root and password is blank so i simply press enter again with out typing anything.


If you like this post please don't forget to post a comment for appreciation.

Chears .. Happy Coding guys :)

SMTP 451 error: CodeIgniter Email

I believe that the problems occurs only when the SMTP server is exceptionally strict and enforces 822bis section 2.3 rule in the header of the email as well. The problem with my scenario occured when the subject of the email was too large and had to occupy two lines. I think that Codeigniter has a bug in that particular function and doesn’t end the line of the subject correctly.





How to fix the SMTP 451 error in Codeigniter :


  1. Navigate to system/libraries/Email.php
  2. Go to _prep_q_encoding function
  3. Change the following code located at line 320 from:



     if ((strlen($temp) + strlen($char)) >= $limit)
     {
$output .= $temp.$this->crlf;
$temp = '';
      }

      to :

     if ((strlen($temp) + strlen($char)) >= $limit)
     {
//$output .= $temp.$this->crlf;
$output .= $temp."\n";
$temp = '';
      }

      
     4.  Change the return of the function from:

          return $str;

     to :

          return str_replace(array("\n"), array("\r\n"), $str);


I am submit a working fix as i was content with my hack. So there you go. If you are encountering the SMTP 451 error I advise to give this hack a try and let me know if that worked out for you.

If you like this post don't forgot to leave a comment.

Chears :)
Happy coding ...

Print your html using jquery

I have some content of my site into a table and i want to print whole content of my table. Please see below screne shot -


Print your html using jquery


Solution :

Below is my javascript function which is used to print content when i click on print icon .

<script type="text/javascript">

function printContent(data){
        var popupWindow = window.open('','printwin', 'scrollbars=yes, resizable=yes,left=100,top=100,width=600,height=600');
         popupWindow.document.write('<html>\n<head>\n');
         popupWindow.document.write('<title></title>\n');
         popupWindow.document.write('<script>\n');
         popupWindow.document.write('function print_win(){\n');
         popupWindow.document.write('\nwindow.print();\n');
         popupWindow.document.write('\nwindow.close();\n');
         popupWindow.document.write('}\n');
         popupWindow.document.write('<\/script>\n');
         popupWindow.document.write('</head>\n');
         popupWindow.document.write('<body onload="print_win()">\n');
         popupWindow.document.write('<style type="text/css">table tr th a{float: left;text-decoration:none;color:#464646;font-family:MyriadProSemibold;font-size:16px;font-weight: bold;}table tr th {background: none repeat scroll 0 0 #e6e6e6;border-bottom: 1px solid #747474;color: #464646;font-family:MyriadProSemibold;font-size: 14px;font-weight: normal;padding: 1.5% 1.5px;} table tr td{border-bottom:1px solid #747474;color: #464646;font-family: MyriadProRegular;font-size:14px;font-weight:normal;    padding:1.5% 1.5px;vertical-align:top;}</style>\n');
         popupWindow.document.write(data);
         popupWindow.document.write('</body>\n');
         popupWindow.document.write('</HTML>\n');
         popupWindow.document.close();
  }


</script>

 Below is my html code :

Suppose below is html which i want to print :-

<table id="print_report">
<tr><th>User</th><th>Views</th><th>Print</th></tr>
<tr><td>Rakesh sharma</td><td>911</td><td>2</td></tr>
<tr><td>Salman ahmad</td><td>231</td><td>7</td></tr>

<tr><td>Ritesh singh</td><td>44</td><td>8</td></tr>
</table> 

 Call of function :  Below is my jquery code 

<script type="text/javascript">

     $("#print_icon").click(function(){
             var data = $("#print_report").html();  // Its return the table content.

             printContent(data);  // Here is calling the function by passing table data.
       });


</script>

Output :   When you click on print icon then like below screne shot an print pop display.




If you like this post please don't dont forget to leave a comment.





Chears ..
Happy coding :)

Create stored procedure for insert and update operation in mysql/sql

Benifit and Advantage of stored procedure :

Stored procedure is single time complied when you creating it first time. It means if you are using stored procedure then you don't need to compile every time. So it saving the compile time.
Its increase the execution time of your query.
If error is comes in your query then its roll back your previous statement.

Creating My First Stored Procedure :

I am very coragious to learn new thing. So today i started to use stored procedure and below is my first simple stored procedure which i creted to perform insert and update operation. Its easy to use stored procedure. Because you don't need to run same query again and again. It reduce the execution time of your site.

See example -




create procedure ADD_PRODUCT(
    IN ID INT(20),
    IN PRODUCT_NAME VARCHAR(255),
    IN PRODUCT_SKU VARCHAR(20),
    IN PRODUCT_FILE VARCHAR(255),
    IN IS_ACTIVE TINYINT(1),
    IN IS_PRINTABLE TINYINT(1)
)
BEGIN
 DECLARE lastInsertid int default 0;
 IF ID = 0 THEN
  INSERT INTO products(product_name, PRODUCT_DESCRIPTION, product_sku, product_image, is_active, is_printable)
  VALUES(PRODUCT_NAME, PRODUCT_DESCRIPTION, PRODUCT_SKU, PRODUCT_FILE, IS_ACTIVE, IS_PRINTABLE);
  SET lastInsertid = LAST_INSERT_ID();
 ELSE
  UPDATE products SET
   product_name= PRODUCT_NAME,
   product_sku= PRODUCT_SKU,
   product_image= PRODUCT_FILE,
   is_active= IS_ACTIVE,
   is_printable= IS_PRINTABLE
  WHERE id = ID;
 END IF;

 SELECT lastInsertid as "INSERTED_ID";
END;




If you like this post please don't forgot to leave a comment.

Chears ..
Happy Coding :)

Difference between ISSET and EMPTY function

Every developer have confusion in there mind while they are using ISSET() and EMPTY() .He/She always confuse where he have to use ISSET function or where they have to use !EMPTY function in php. But as of now no one have confusion in there mind because i am going to describe the difference between these two very useful function of php.

ISSET() :  ISSET checks the variable to see if it has been set, in other words, it checks to see if the variable is any value except NULL or not assigned a value. ISSET returns TRUE if the variable exists and has a value other than NULL. That means variables assigned a " ", 0, "0", or FALSE are set, and therefore are TRUE for ISSET.

EMPTY() : EMPTY checks to see if a variable is empty. Empty is interpreted as: " " (an empty string), 0 (0 as an integer), 0.0 (0 as a float), "0" (0 as a string), NULL, FALSE, array() (an empty array), and "$var;" (a variable declared, but without a value in a class.

Value of variable ($var) isset($var) empty($var)
“” (an empty string) bool(true) bool(true)
” ” (space) bool(true)
FALSE bool(true) bool(true)
TRUE bool(true)
array() (an empty array) bool(true) bool(true)
NULL bool(true)
“0? (0 as a string) bool(true) bool(true)
0 (0 as an integer) bool(true) bool(true)
0.0 (0 as a float) bool(true) bool(true)
var $var; (a variable declared, but without a value) bool(true)
NULL byte (“\ 0?) bool(true)

Now have a look below example for better explanation of each scenario :-

A Non Declared Variable :
If I try to use a variable I haven't declared in a conditional statement to check to see if it was set, the check for both ISSET and EMPTY would look like this:

if ( isset($aNonDeclaredVariable)) -- This would be FALSE
if ( empty($aNonDeclaredVariable)) -- This is TRUE

A Variable Set to NULL :

$nullVar = NULL;

if ( isset($nullVar)) -- This would be FALSE
if ( empty($nullVar)) -- This is TRUE

This example would most likely come up if you have default NULL values set up in your database. You get the value back from your database, and check it in a conditional. Here again you want to use ISSET. EMPTY would come up true for your NULL value which mostly likely will lead to an incorrect result in your conditional.

An Empty String :

$singleQuoteVar =  '' ;    //Single quote empty variable.
$dblQuoteVar =  "" ;     // Double quote empty variable.

if ( isset($singlequoteVar))      --   This would be TRUE
if ( empty($singlequoteVar))   --   This is TRUE

if ( isset($dblquoteVar))     --   This would be TRUE
if ( empty($dblquoteVar))  --   This is TRUE

Where can you run into trouble here? They're both the same. The problem usually comes up when your using a form. For example, in a textarea input the results back would be "" if nothing was entered, or a user put a space in the form. The same with an input box. What you normally want to know is, is the field blank. It might be better here to check for an empty string directly, something like:

if ( $_POST['foo'] == "" )

A Zero Value :

$zeroValue = 0 ;

if ( isset($zeroValue))     --   This would be TRUE
if ( empty($zeroValue))  --   This is TRUE

The problem here, is we have both set a specific value, 0, in our variable, and according to the definition of EMPTY, it is empty, thus TRUE. What we normally check for when a zero value may be expected is "not empty," like so:

if ( ! empty($zeroValue))  -- This is FALSE

In order for "not empty" to be true, there needs to be some value other than
"" (an empty string), 0 (0 as an integer), 0.0 (0 as a float), "0" (0 as a string), NULL, FALSE, array() (an empty array), and "$var;" (a variable declared, but without a value in a class, as we defined above.

"Not EMPTY" is a good check any time you want to check if there is an actual value in the variable. This is a good check when you assigned a value statically, that could be changed dynamically during the course of running the program.

A Declared Array :

$arrVar = array() ;

if ( isset($arrVar))     --   This would be TRUE
if ( empty($arrVar))  --   This is TRUE

By now you should be getting the hang of this.

A Boolean Value :

$TrueBoolValue  = TRUE  == 1;
$FalseBoolValue = FALSE == 0;

if ( isset($TrueBoolValue))      --   This would be TRUE
if ( empty($TrueBoolValue))   --   This is FALSE

if ( isset($FalseBoolValue))     --   This would be TRUE
if ( empty($FalseBoolValue))  --   This is TRUE

Both variables have been set to a boolean value, which translates to a 1 in the case of TRUE. ISSET is set to 1 and thus TRUE, EMPTY is not empty thus it is FALSE.

In the case of FALSE, which translates in PHP to 0. Remember for ISSET "0" is TRUE, but for EMPTY "0" is empty, and thus EMPTY "0" is TRUE for being empty.

An Object :

class TestObj
{
public function teststr()
{
$str = "The object under test" ;
return $str ;
}}
$test     = new TestObj ;
$teststr = $test->testrun() ;

if ( isset($test))       --   This would be TRUE
if ( empty($test))    --   This is FALSE
if ( ! empty($test))  --   This is TRUE

if ( isset($test2))      --  This would be TRUE
if ( empty($test2))   --  This is FALSE
if ( ! empty($test2)) --  This is TRUE

The first test is just an object with no properties. This says we have set the variable, and it is not empty. A change in PHP in 5.0 made objects with no properties no longer considered empty. It's a blob full of object structure and data so it's not empty. The second test is a variable set by returning a result from an object method. Again the variable is set and is not empty.

One other gotcha, you should be aware of, is that both ISSET and EMPTY only check a variable. You can't put a statement together inside the parenthesis, something like ISSET(trim($stringVar)). It will throw an exception. Use ISSET and EMPTY only with a single variable like ISSET($stringVar). Do all your algorithms before doing your check.


If you like this please don't forget to leave a comment

Happy Coding :)

Remove html tags in MYSQL/SQL database query.

I am facing a serious problem in mysql query while sorting a column in database. If i am sorting a column of table having rows with and with out html tags then i am not getting correct sorting order due to html tags added before some of the text Like below :-






Solutions :  To prevent this problem we need first to ignore html tags and then run sorting query to perform sorting operation. But the question is how we can do this. After alot of troubling and googling finally i find out the sollution. Here is a sql function which will solve my problem and ofcouse your also. 

Method of users :-

Step 1 -
First of all you need to run below function in your sql/mysql database. Just copy and paste into your database.

DROP FUNCTION IF EXISTS fnStripTags;
DELIMITER |
CREATE FUNCTION fnStripTags( Dirty varchar(4000) )
RETURNS varchar(4000)
DETERMINISTIC 
BEGIN
  DECLARE iStart, iEnd, iLength int;
    WHILE Locate( '<', Dirty ) > 0 And Locate( '>', Dirty, Locate( '<', Dirty )) > 0 DO
      BEGIN
        SET iStart = Locate( '<', Dirty ), iEnd = Locate( '>', Dirty, Locate('<', Dirty ));
        SET iLength = ( iEnd - iStart) + 1;
        IF iLength > 0 THEN
          BEGIN
            SET Dirty = Insert( Dirty, iStart, iLength, '');
          END;
        END IF;
      END;
    END WHILE;
    RETURN Dirty;
END;
|
DELIMITER ;

Step 2 - Now we need to call the above function in our query like below "SELECT fnStripTags(message) FROM notes ORDER BY message desc"   

Chears..
Happy Coding :)

Validate multiple comma seprated email in PHP

If you want to validate mutiple email entered into text box with comma seprated below is a simple function which can fullfil your need into javascript.Your just need to pass your comma seprated email into below function and rest of all it do itself. 




Lets understand by an example :


Suppose we have multiple comma seprated email ids  and now we want to validate each email format should be correct like below -

var email = "phpsollutions@gmail.com, xyz@gmail.com, abc@yahoomail.com";

multipleEmailValidate(email);

Now below is the function to validate comma seprated email:


function multipleEmailValidate(email){   //In Email Variable Number Of Emails Comes With Comma Seprated eg(phpsollutions@gmail.com, xyz@gmail.com)
    var filterforemail = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    if (email != ''){
        var result = email.split(',');
        for (var i = 0; i < result.length; i++){
            if (result[i] != ''){
                if(!filterforemail.test($.trim(result[i]))){
                    alert('Please check, ' + result[i] + ' email addresses not valid');
                    return false;
                }
            }
        }
    }
    return true;
}



Happy coding :)
Chears

How do we “restore” notepad after crash?

Recently i am working on notepad++ editor. While working on that suddenly a error shows in front of my screen and it display a message that " Notepadd++: a free(GNU) source code editor has stopped working " like below preview but when i click on Close program button my notepad is goes to restart and when i again open my file it was blank. I get shocked because all of the datas are very important.
So i started to find out the sollution that how can i roll back my data. After doing some googling i figure out the problem .Every work which we are doing  into notepad create a back up file it self. Then i take a long breath and feel relax. After few minutes i roll back my all of that datas.








Sollution :

Go to the directory where your notepad is installed. In my case i installed windows-7 OS in my pc . So i go into the
C://User/Administrator/AppData/Roming/Notepad++/backup

When you go into the backup folder all the files in which you are working in notepad++ till now you will see the copy file is generated in backup folder with there generation data.


If you like this post don't forgot to leave a comment.

Chears ....
Happy coding :0

ns_error_unexpected unexpected error in tinymce editor

Recently i face a very intresting problem with tinymce editor. when i load tinymce editor from ajax on my page i show an error on inspector ie "ns_error_unexpected" and it stoped loading of my tinymce editor. After doing alot's of googling finally i find out the sollution.

Problem Reason :
-------------------
Actually the problem is that when you remove the tinymce by using tinymce.remove() .Its showning "ns_error_unexpected" error.

Sollution :

-----------
By using try, catch you can pass away by this problem. You just need to be simply add a try catch code below before initiliazing editor code like below :

<script type="text/javascript">


try {
tinymce.remove();
} catch (e) {}

tinymce.init({
    selector: "textarea",
    setup: function (editor)
    {
        editor.on('change', function () {
        tinymce.triggerSave();
        });
    },
    plugins: [
    "advlist autolink lists link image charmap print preview anchor",
    "searchreplace visualblocks code fullscreen",
    "insertdatetime media table contextmenu paste "
    ],
    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter  alignright alignjustify | bullist numlist outdent indent | link image"
});


</script>


Please don't forgot to leave a comment if you like this post.

Chears ... 
Happy coding :)

How to Delete record from different table with out using sub query using sql or mysql.

If i want to delete record from a single table i just need to run a simple delete command like below .

Query to delete single record :

DELETE FROM
    `first_table`   
         WHERE
              `my_value`='FooBar';  


Now suppose i want to delete record from two different table then every person first comes in there mind using join with delete command like below :

Query with join return error :

DELETE FROM
    `first_table`
          INNER JOIN `second_table` ON `second_table`.`id_column`=`first_table`.`id_column`
             WHERE
               `my_value`='FooBar'; 

But you know above query return an error something like below :

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN `second_table` ON `second_table`.`id_column`=`my_table`.`id_column` WHERE `my_va' ne 1


The Solution :

Sticking with the query above we can get it to work with a simple amendment. All we need to do is put the name of the table we’re deleting from between the words ‘DELETE’ and ‘FROM’ like below.

Query with join  :

DELETE `first_table` FROM
    `first_table`
        INNER JOIN `second_table` ON `second_table`.`id_column`=`first_table`.`id_column`
         WHERE
           `my_value`='FooBar'; 


If you like this post don't forgot to leave a comment 

Chears  :)