Friday, March 29, 2013

Fatal error: Allowed memory size in wordpress


When you install of word press and word press plugin of admin section.
if you facing problem  "Fatal error: Allowed memory size of 33554432 bytes exhausted".



This type error message show 


  1. Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 15552 bytes)in /home/mydomainusername/public_html/blog_wp/wp-includes/media.php on line 253
  2. Fatal error: Allowed memory size of 33554432 bytes exhausted (tried to allocate 122880 bytes) in /home/mydomainusername/public_html/blog/wp-admin/admin-header.php on line 126



Following Point solved "Fatal error" problem .


1. If you have access to your PHP.ini file, change the line in PHP.ini
If your line shows 32M try 64M:
memory_limit = 128M ; Maximum amount of memory a script may consume (128MB)

2. If you don't have access to PHP.ini  file , Please try adding this to an .htaccess file:
php_value memory_limit 128M

3. Try adding this line to your wp-config.php file:
Increasing memory allocated to PHP
define('WP_MEMORY_LIMIT', '128M');

4. Talk to your server  host.


 I finally got this problem fixed! using Following below instruction

Very easy handing user end!
if you not got "php.ini" in  "wp-admin" . you  Create a file called "php.ini" in the "wp-admin" folder of wordpress install. 
Add the following text to the file;
memory_limit = 256M ;







What are the difference between DDL, DML DCL and TCL commands?

Following difference between DDL, DML DCL and  TCL commands



Data definition language(DDl)
DDL statements are used to build and modify the structure of your tables and other objects in the database. When you execute a DDL statement, it takes effect immediately.

  1. CREATE - to create objects in the database
  2. ALTER - alters the structure of the database
  3. DROP - delete objects from the database
  4. TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
  5. COMMENT - add comments to the data dictionary
  6. RENAME - Rename an object/Table

Data Manipulation Language(DML)
DML statements are used to work with the data in tables. When you are connected to most multi-user databases (whether in a client program or by a connection from a Web page script), you are in effect working with a private copy of your tables that can’t be seen by anyone else until you are finished (or tell the system that you are finished). You have already seen the SELECT statement; it is considered to be part of DML even though it just retreives data rather than modifying it.

  1. SELECT - retrieve data from the a database
  2. INSERT - insert data into a table
  3. UPDATE - updates existing data within a table
  4. DELETE - deletes all records from a table, the space for the records remain
  5. MERGE - UPSERT operation (insert or update)
  6. CALL - call a PL/SQL or Java subprogram
  7. EXPLAIN PLAN - explain access path to data
  8. LOCK TABLE - control concurrency
Data Control Language (DCL)
DCL is Stand for  Data Control Language. It is used to create roles, permissions, and referential integrity as well it is used to control access to database by securing it.

  1. GRANT - gives user's access privileges to database
  2. REVOKE - withdraw access privileges given with the GRANT command

Transactional Control Language(TCL)
TCL is Stand for Transactional Control Language. It is used to manage different transactions occurring within a database.
  1. COMMIT - save work done
  2. SAVEPOINT - identify a point in a transaction to which you can later roll back
  3. ROLLBACK - restore database to original since the last COMMIT
  4. SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use 
 ROLLBACK is used for revoking the transactions until last commit.
COMMIT is used for commiting the transactions to the database.
Once we commit we cannot rollback. Once we rollback we cannot commit.
Commit and Rollback are generally used to commit or revoke the transactions that are with regard to DML commands.



NOTE:
DML commands can't be rollback when a DDL command is executed immediately after a DML. DDL after DML means "auto commit". The changes will return on disk not on the buffer. If the changes return on the buffer it is possible to rollback not from the disk


Monday, March 25, 2013

Output Buffering using php


PHP - Caching Pages with Output Buffering

There are 3 Following  basic functions you can use It.


ob_start() any output will be saved in PHP's internal buffer and not yet printed to the screen. This includes HTML and echoed or printed php statements. Header statements are the exception as they are still sent to the browser.


<?php
ob_start(); // Turns on output buffering
?> 



 ob_get_contents() will return a string value of the current contents of the buffer. This will prove very useful for caching purposes when placed at the end of pages. More on that in a bit.



<?php
// Stores the contents of the buffer in a variable as a string
$contents = ob_get_contents();
?>


 ob_end_flush() will print all the contents of the buffer just as you would expect to see it if output buffering was never turned on.


<?php
ob_end_flush(); // Turn off buffering and print the contents
?> 

How to Clear Browser Cache Using HTML CODE or PHP CODE

we have  clear the browser cached page or to force the browser to re-download the content of a page, you can use  the following HTML code in the header tags (<head>) of the page. This code will ask the browser to ignore any saved copies of the page, and to re-download page content.



HTML CODE Before used Head Tag 

<!-- no cache headers -->
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="Cache-Control" content="no-cache">
<!-- end no cache headers -->

If you doing  work with PHP, you can do the exact same using this PHP code:

PHP Code:

header ("Expires: ".gmdate("D, d M Y H:i:s", time())." GMT");  
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");  
header ("Cache-Control: no-cache, must-revalidate");  
header ("Pragma: no-cache");

Thursday, March 21, 2013

Difference between for and for each loop..?


They works almost same way and same speed as foreach loop will takes time for getting next element while iterating array while for loop will takes time to re-initialize the variable.Following Difference  for and for each loop.


  1. For can be used to run statements for a fixed number of times, 
    Foreach can be used to run statements for dynamically generated arrays(may be result of database query).We can also used for loop for dynamically generated array(may be result of database query). Foreach is the ideal way to iterate dynamic array. The reason behind this, we don't know the index of array as it may be associate result from database query. So if we use foreach than it will iterate the result one by one. 
  2. Foreach will works only and only with arrays.
    For will works for any logical operation and i will continue until given condition fails.There is not much execution time difference.

  3. For loop can be more optimized if we know the count of array and index of array.
    Foreach is better when we have dynamic array without knowing index of array and size of an array.
  4. For loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. there is need to specify the loop bounds( minimum or maximum).
    int k = 0;
    for (int i = 1; i <= 5; i++) 
    k = k + i ; 
    }



    Foreach statement repeats a group of embedded statements for each element in an array or an object collection.you do not need to specify the loop bounds minimum or maximum.
    int k = 0;
    int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 }; 
    foreach (int i in tempArr ) 
    k = k+ i ; 
    }

Tuesday, March 19, 2013

Speed Up Mysql Queries

You have Given  Tips Using Speed Up  Mysql Queries/Database . Following point remember using mysql query.

  • Use persistent connections to the database to avoid connection overhead.
  • Check all tables have PRIMARY KEYs on Columns/Fields with high cardinality (many rows match the key value). Well,`gender` column has low cardinality (selectivity), unique user id column has high one and is a good candidate to become a primary key.
  • All references between different tables should usually be done with indices (which also means they must have identical data types so that joins based on the corresponding Columns/Fields will be faster). Also check that fields that you often need to search in (appear frequently in WHERE, ORDER BY or GROUP BY clauses) have indices, but don’t add too many: the worst thing you can do is to add an index on every column of a table (I haven’t seen a table with more than 5 indices for a table, even 20-30 Columns/Fields big). If you never refer to a column in comparisons, there’s no need to index it.
  • Using simpler permissions when you issue GRANT statements enables MySQL to reduce permission-checking overhead when clients execute statements.
  • Use less RAM per row by declaring Columns/Fields only as large as they need to be to hold the values stored in them.
  • Use leftmost index prefix — in MySQL you can define index on several Columns/Fields so that left part of that index can be used a separate one so that you need less indices.
  • When your index consists of many Columns/Fields, why not to create a hash column which is short, reasonably unique, and indexed? Then your query will look like:
  • Consider running ANALYZE TABLE (or myisamchk --analyze from command line) on a table after it has been loaded with data to help MySQL better optimize queries.
  • Use CHAR type when possible (instead of VARCHAR, BLOB or TEXT) — when values of a column have constant length: MD5-hash (32 symbols), ICAO or IATA airport code (4 and 3 symbols), BIC bank code (3 symbols), etc. Data in CHAR Columns/Fields can be found faster rather than in variable length data types Columns/Fields.
  • Don’t split a table if you just have too many Columns/Fields. In accessing a row, the biggest performance hit is the disk seek needed to find the first byte of the row.
  • A column must be declared as NOT NULL if it really is — thus you speed up table traversing a bit.
  • If you usually retrieve rows in the same order like expr1, expr2, ..., make ALTER TABLE ... ORDER BY expr1, expr2, ... to optimize the table.
  • Don’t use PHP loop to fetch rows from database one by one just because you can — use IN instead,
  • Example: SELECT * FROM `tableNAME` WHERE `id` IN (27,7,17,1,3);
  • Don’t use REPLACE (which is DELETE+INSERT and wastes ids): use INSERT … ON DUPLICATE KEY UPDATE instead (i.e. it’s INSERT + UPDATE if conflict takes place). The same technique can be used when you need first make a SELECT to find out if data is already in database, and then run either INSERT or UPDATE. Why to choose yourself — rely on database side.
  • Tune MySQL caching: allocate enough memory for the buffer (e.g. SET GLOBAL query_cache_size = 1000000) and define query_cache_min_res_unit depending on average query resultset size.
  • Use column default value, and insert only those values that differs from the default. This reduces the query parsing time.
  • Use INSERT DELAYED or INSERT LOW_PRIORITY (for MyISAM) to write to your change log table. Also, if it’s MyISAM, you can add DELAY_KEY_WRITE=1 option — this makes index updates faster because they are not flushed to disk until the table is closed.
  • Think of storing users sessions data (or any other non-critical data) in MEMORY table — it’s very fast.
  • For your web application, images and other binary assets should normally be stored as files. That is, store only a reference to the file rather than the file itself in the database.
  • If you have to store big amounts of textual data, consider using BLOB column to contain compressed data (MySQL’s COMPRESS() seems to be slow, so gzipping at PHP side may help) and decompressing the contents at application server side. Anyway, it must be benchmarked.
  • If you often need to calculate COUNT or SUM based on information from a lot of rows (articles rating, poll votes, user registrations count, etc.), it makes sense to create a separate table and update the counter in real time, which is much faster. If you need to collect statistics from huge log tables, take advantage of using a summary table instead of scanning the entire log table every time.
  • Divide complex queries into several simpler ones — they have more chances to be cached, so will be quicker.
  • Group several similar INSERTs in one long INSERT with multiple VALUES lists to insert several rows at a time: quiry will be quicker due to fact that connection + sending + parsing a query takes 5-7 times of actual data insertion (depending on row size). If that is not possible, use START TRANSACTION and COMMIT, if your database is InnoDB, otherwise use LOCK TABLES — this benefits performance because the index buffer is flushed to disk only once, after all INSERT statements have completed; in this case unlock your tables each 1000 rows or so to allow other threads access to the table.
  • When loading a table from a text file, use LOAD DATA INFILE (or my tool for that), it’s 20-100 times faster.
  • Log slow queries on your dev/beta environment and investigate them. This way you can catch queries which execution time is high, those that don’t use indexes, and also — slow administrative statements (like OPTIMIZE TABLE and ANALYZE TABLE)
  • Tune your database server parameters: for example, increase buffers size.
  • If you have lots of DELETEs in your application, or updates of dynamic format rows (if you have VARCHAR, BLOB or TEXT column, the row has dynamic format) of your MyISAM table to a longer total length (which may split the row), schedule running OPTIMIZE TABLE query every weekend by crond. Thus you make the defragmentation, which means more speed of queries. If you don’t use replication, add LOCAL keyword to make it faster.
  • Don’t use ORDER BY RAND() to fetch several random rows. Fetch 10-20 entries (last by time added or ID) and make array_random() on PHP side. There are also other solutions.
  • Consider avoiding using of HAVING clause — it’s rather slow.
  • In most cases, a DISTINCT clause can be considered as a special case of GROUP BY; so the optimizations applicable to GROUP BY queries can be also applied to queries with a DISTINCT clause. Also, if you use DISTINCT, try to use LIMIT (MySQL stops as soon as it finds row_count unique rows) and avoid ORDER BY (it requires a temporary table in many cases).
  • When I read “Building scalable web sites”, I found that it worth sometimes to de-normalise some tables (Flickr does this), i.e. duplicate some data in several tables to avoid JOINs which are expensive. You can support data integrity with foreign keys or triggers.
  • If you want to test a specific MySQL function or expression, use BENCHMARK function to do that.

Monday, March 18, 2013

Elements of HTML

Elements of HTML(Hyper Text Markup Language)


HTML markup tags are usually called HTML tags


  • HTML tags are keywords (tag names) surrounded by angle brackets like <html>
  • HTML tags normally come in pairs like <b> and </b>
  • The first tag in a pair is the start tag, the second tag is the end tag
  • The end tag is written like the start tag, with a forward slash before the tag name
  • Start and end tags are also called opening tags and closing tags



  1. A – How to display hyperlink?
  2. B – How to display text in BOLD style? 
  3.  Body – How and where to write content in the HTML file? 
  4.  Br – How to create a line break in html page? 
  5.  Code – How to display computer code in html page? 
  6.  Div – How to display division (section) in the html content?
  7.  Font – How to format text in color, size and font style in HTML? 
  8.  Form – How to display HTML form to submit data to other page?
  9.  Input – How to display Check box, FileUpload control, Image button, password textbox, radiobutton, reset button, submit button, multi-line textbox and button on the html page?
  10.  How to limit the number of characters allowed in the text box?
  11. IFrame – How to display a sub window in the html page? 
  12. H1 to H6- How to display headings in html page? 
  13.  Head – How & where to write title, meta, link and script tags in html page?
  14.  Hr – How to display horizontal line in html page? 
  15.  HTML – What is the use of html tag in html page?
  16.  Img – How to display image or picture in html page?
  17.  Label – how to display a label or associate a control with a label in html page? 
  18.  FieldSet – Legend – How to group or create a block of html controls in html page? 
  19.  OL/UL – LI – How to display ordered and un-ordered list in html page? 
  20.  Link - How to reference external css file in html page? 
  21.  Meta – How & why to write meta tags in html page? 
  22.  P – How to display a paragraph in html page? 
  23. Select - OptGroup – Option – How to display a dropdown list in html page? 
  24.  How to display a list box in html page?
  25.  How to display a list box and enable user to select multiple items from the listbox?
  26.  Pre – How to display pre-formatted content in html page? 
  27.  Script – How to write client side scripting language code in html page?
  28.  Span- How to write inline text with style in html page?
  29.  Style – How to specify CSS style information for an element or write CSS style class in the html page? 
  30.  Sub – How to write subscript text in html page? 
  31.  Sup- How to write superscript text in html page? 
  32.  Table, Tr, Th, Td – How to write data in tabular format in html page?
  33.  TextArea 
  34.  Title 

Friday, March 15, 2013

How to convert Currency / Indian Rupees using php

How to Currency convert  / Indian Rupees using php. You have  convert between that currency and all other currencies. Following  code using  easy convert to  Currency / Indian Rupees.


<?php
function currency($from_Currency,$to_Currency,$amount)
{
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);


$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";

$result = file_get_contents($url);

$result = explode('"', $result);


//print_r($result);

$converted_amount = explode(' ', $result[3]);
//print_r($converted_amount);

 $conversion_a = $converted_amount[0];

// $conversion_f= round($conversion_a, 0);
  $conversion_f=$conversion_a;
return $conversion_f;
}
/* CURRENCY  name code && fullname   */
/* Code - CURRENCY name */
/*
CAD - Canadian Dollar
CHF - Swiss Franc
CNY - Chinese Yuan Renminbi
DKK - Danish Krone
EUR - Euro
GBP - British Pound
HKD - Hong Kong Dollar
HUF - Hungarian Forint
INR - Indian Rupee
JPY - Japanese Yen
MXN - Mexican Peso
MYR - Malaysian Ringgit
NOK - Norwegian Krone
NZD - New Zealand Dollar
PHP - Philippine Peso
RUB - Russian Ruble
SEK - Swedish Krona
SGD - Singapore Dollar
THB - Thai Baht
TRY - Turkish Lira
USD - US Dollar
ZAR - South African Rand */

/* End here */
/* For Examples 1 */
$from_Currency="USD"; // 
$to_Currency="INR";
$number_of_value=1; //Number of value  convert 


echo $number_of_value." ".$from_Currency." Dollar Convert ".$to_Currency." (indian Rupee): ".currency($from_Currency,$to_Currency,$number_of_value).$to_Currency."<br><br>"; 
/* For Examples 2 */
$from_Currency="EUR";
$to_Currency="INR";
$number_of_value=1; 
echo $number_of_value." ".$from_Currency."  Convert ".$to_Currency." (indian Rupee): ".currency($from_Currency,$to_Currency,$number_of_value).$to_Currency."<br><br>"; 

/* For Examples 3 */
$from_Currency="INR";
$to_Currency="USD";
$number_of_value=100; 

echo $number_of_value." ".$from_Currency."(indian Rupee) Convert ".$to_Currency." (Dollar): ".currency($from_Currency,$to_Currency,$number_of_value).$to_Currency."<br><br>"; 



?>

Wednesday, March 13, 2013

Website Secure And Safe From Hackers Tips


Web  Internet provides same business opportunities to both large and small business owners.
Unfortunately, this growth also attract Hackers to misuse the Website data & can easily destroy their online branding.

I was exploring the internet for online security techniques & online website attack methods.
While searching I got Josh Duck Blog & there was very good information about website security.
You want to Website   Secure And Safe From Hackers. Using Following Tips  for secure your online projects / Website.

(A) Securing Your PHP Code – Server Security
Remote Code Execution
Register Globals
User Uploaded Files
Form Validation
Keeping Code Private


(B) Securing Your PHP Code – Databases
Magic Quotes
SQL injection
A Better Solution
Physical Access
General Security Rules

(C) Securing Your PHP Code – XSS
Allowing Some HTML
Cross Site Request Forgeries
Preventing Bogus Requests
Watch Your Subdomains
HTTP Only Cookies
XSS Attack?
Attack Types
XSS Example
Escaping Data

Tuesday, March 12, 2013

How To Find & Replace String in Mysql

You can find a string in a  field and replace it with another string using Mysql Query




update [table_name] set [field_name] = replace([field_name],'[string_to_find]','[string_to_replace]');

Just like - update user set name = replace(surname,'gupta','sharma');

Redirect Old Domain to New Domain using .htaccess


 we can add the following lines to your .htaccess file located at the root of your old domain:
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} ^olddomain.com$ [OR]
  RewriteCond %{HTTP_HOST} ^www.olddomain.com$
  RewriteRule (.*)$ http://www.newdomain.com/$1 [R=301,L]
</IfModule>

To redirect a single page to a new location on the same domain, use the following syntax:
Redirect 301 /old/old.htm http://www.domain.com/new.htm

Php Array Functions

We can used Following  Php Array Functions.

Syntax of Array

array(  key =>  value
     , ...
     )
// key may only be an integer or string
// value may be any value of any type



List 
  1. array_change_key_case — Returns an array with all string keys lowercased or uppercased
  2. array_chunk — Split an array into chunks
  3. array_count_values — Counts all the values of an array
  4. array_diff_assoc — Computes the difference of arrays with additional index check
  5. array_diff — Computes the difference of arrays
  6. array_fill — Fill an array with values
  7. array_filter — Filters elements of an array using a callback function
  8. array_flip — Exchanges all keys with their associated values in an array
  9. array_intersect_assoc — Computes the intersection of arrays with additional index check
  10. array_intersect — Computes the intersection of arrays
  11. array_key_exists — Checks if the given key or index exists in the array
  12. array_keys — Return all the keys of an array
  13. array_map — Applies the callback to the elements of the given arrays
  14. array_merge_recursive — Merge two or more arrays recursively
  15. array_merge — Merge two or more arrays
  16. array_multisort — Sort multiple or multi-dimensional arrays
  17. array_pad — Pad array to the specified length with a value
  18. array_pop — Pop the element off the end of array
  19. array_push — Push one or more elements onto the end of array
  20. array_rand — Pick one or more random entries out of an array
  21. array_reduce — Iteratively reduce the array to a single value using a callback function
  22. array_reverse — Return an array with elements in reverse order
  23. array_search — Searches the array for a given value and returns the corresponding key if successful
  24. array_shift — Shift an element off the beginning of array
  25. array_slice — Extract a slice of the array
  26. array_splice — Remove a portion of the array and replace it with something else
  27. array_sum — Calculate the sum of values in an array.
  28. array_unique — Removes duplicate values from an array
  29. array_unshift — Prepend one or more elements to the beginning of array
  30. array_values — Return all the values of an array
  31. array_walk — Apply a user function to every member of an array
  32. array — Create an array
  33. arsort — Sort an array in reverse order and maintain index association
  34. asort — Sort an array and maintain index association
  35. compact — Create array containing variables and their values
  36. count — Count elements in a variable
  37. current — Return the current element in an array
  38. each — Return the current key and value pair from an array and advance the array cursor
  39. end — Set the internal pointer of an array to its last element
  40. extract — Import variables into the current symbol table from an array
  41. in_array — Return TRUE if a value exists in an array
  42. key — Fetch a key from an associative array
  43. krsort — Sort an array by key in reverse order
  44. ksort — Sort an array by key
  45. list — Assign variables as if they were an array
  46. natcasesort — Sort an array using a case insensitive “natural order” algorithm
  47. natsort — Sort an array using a “natural order” algorithm
  48. next — Advance the internal array pointer of an array
  49. pos — Get the current element from an array
  50. prev — Rewind the internal array pointer
  51. range — Create an array containing a range of elements
  52. reset — Set the internal pointer of an array to its first element
  53. rsort — Sort an array in reverse order
  54. shuffle — Shuffle an array
  55. sizeof — Get the number of elements in variable
  56. sort — Sort an array
  57. uasort — Sort an array with a user-defined comparison function and maintain index association
  58. uksort — Sort an array by keys using a user-defined comparison function
  59. usort — Sort an array by values using a user-defined comparison function

Sunday, March 10, 2013

Check execution time of script using php


We have checked the execution time of your script.Following  code Use

<?php
// Write this line at the top of script
$start = (float) array_sum(explode(‘ ‘,microtime()));

/*
your code here
*/

// Write these lines at the bottom of script
$end = (float) array_sum(explode(' ',microtime()));
echo sprintf(“%.4f”, ($end-$start));
?>

If you want to increase the execution time limit then use these:

1. set_time_limit(int $seconds)

(Note – will not work in Safe Mode)

2. ini_set(‘max_execution_time’, 300); //300 seconds = 5 minutes

(Note – ini_set will not work in Safe Mode)

3. Via .htaccess

php_value max_execution_time 90


For ex.
It will determine the time taken for a php script to execute




<!-- put this at the top of the page start here-->
<?php
   $mtime = microtime();
   $mtime = explode(" ",$mtime);
   $mtime = $mtime[1] + $mtime[0];
   $starttime = $mtime;
;?>
<!-- put this at the top of the page end  here-->
<!-- put other code and html in here -->


<!-- put this code at the bottom of the page start -->
<?php
   $mtime = microtime();
   $mtime = explode(" ",$mtime);
   $mtime = $mtime[1] + $mtime[0];
   $endtime = $mtime;
   $totaltime = ($endtime - $starttime);
   echo "This page was created in ".$totaltime." seconds";
?>

<!-- put this code at the bottom of the page end  -->

Saturday, March 9, 2013

Password Generator and Random Number String Function


We want to Random Number String & Password Generator Function using any technology ( like php, jsp, asp, java)


Random Number String generator function

function r($len){
$keyset = “abcdefghijklmnopqrstuvwxyz0123456789?;
$randkey = “”;
for ($i=0; $i<$len; $i++)
{
$randkey = $randkey . $keyset[mt_rand(0, strlen($keyset)-1)];
}
return $randkey;
}

Strong Password generator function

function generatePassword($length=9, $strength=0) {
$vowels = ‘aeuy’;
$consonants = ‘bdghjmnpqrstvz’;
if ($strength & 1) {
$consonants .= ‘BDGHJLMNPQRSTVWXZ’;
}
if ($strength & 2) {
$vowels .= “AEUY”;
}
if ($strength & 4) {
$consonants .= ’23456789';
}
if ($strength & 8) {
$consonants .= ‘@#$%’;
}

$password = ”;
$alt = time() % 2;
for ($i = 0; $i < $length; $i++) {
if ($alt == 1) {
$password .= $consonants[(rand() % strlen($consonants))];
$alt = 0;
} else {
$password .= $vowels[(rand() % strlen($vowels))];
$alt = 1;
}
}
return $password;
}



Calculating Age using MySQL

We want to  Calculating Age Current date from Date of Birth in MySQL.Following Given many option find out  age.



SELECT NOW()  - Returns the current date and time
Output- 2013-03-09 14:16:44
SELECT CURDATE()  - Returns the current date
Output- 2013-03-09


1. SELECT DATE_FORMAT(NOW(), '%Y') - DATE_FORMAT('1981-10-25', '%Y') - (DATE_FORMAT(NOW(), '00-%m-%d') < DATE_FORMAT('1981-10-25', '00-%m-%d'))
AS age
output- 31

2. SELECT YEAR(DATE_SUB(NOW(), INTERVAL TO_DAYS('1981-10-25') DAY)) AS age
output- 31

3. SELECT ROUND(DATEDIFF(CURDATE(),'1981-10-25')/365) AS age 
output- 31

MySQL Date Functions

DATE_SUB() - The DATE_SUB() function subtracts a specified time interval from a date.
CURTIME() - Returns the current time
DATE() - Extracts the date part of a date or date/time expression
EXTRACT() -Returns a single part of a date/time
DATE_ADD()- Adds a specified time interval to a date
DATEDIFF()- Returns the number of days between two dates
DATE_FORMAT()- Displays date/time data in different formats
TO_DAYS() - Return the date argument converted to days

More function see it

Thursday, March 7, 2013

Sorting Alphanumeric using mysql query


Several times ,I have need to sort alphanumeric rows in a database by number (i.e. emp1, emp2, emp3,emp10,emp15 etc.) in Project .  you  want to sorting alphanumeric using mysql query. Follwing code use.



The Data
For our purposes, we’ll be using the following table:

Table: sorting_image
 -------------------------- -------------
| alphanumeric VARCHAR(77) | idnumber INT |
 -------------------------- -------------
| image1                    | 1           |
| image2                    | 2           |
| image3                    | 3           |
| image4                    | 4           |
| image5                    | 5           |
| image6                    | 6           |
| image7                    | 7           |
| image8                    | 8           |
| image9                    | 9           |
| image10                   | 10          |
| image11                   | 11          |
| image12                   | 12          |
 -------------------------- -------------

 Sorting by the column idnumber, 



 Query: SELECT alphanumeric, idnumber
       FROM sorting_image
       ORDER BY idnumber
 -------------------------- -------------
| alphanumeric VARCHAR(77) | idnumber INT |
 -------------------------- -------------
| image1                    | 1           |
| image2                    | 2           |
| image3                    | 3           |
| image4                    | 4           |
| image5                    | 5           |
| image6                    | 6           |
| image7                    | 7           |
| image8                    | 8           |
| image9                    | 9           |
| image10                   | 10          |
| image11                   | 11          |
| image12                   | 12          |
 -------------------------- -------------

if you sorting by the alphanumeric column, we get unexpected results:

 Query: SELECT alphanumeric, idnumber
       FROM sorting_image
       ORDER BY alphanumeric
 -------------------------- -------------
| alphanumeric VARCHAR(77) | idnumber INT |
 -------------------------- -------------
| image1                    | 1           |
| image10                   | 10          |
| image11                   | 11          |
| image12                   | 12          |
| image2                    | 2           |
| image3                    | 3           |
| image4                    | 4           |
| image5                    | 5           |
| image6                    | 6           |
| image7                    | 7           |
| image8                    | 8           |
| image9                    | 9           |
 -------------------------- -------------

 Solution

 Obviously, desired Results not come. Since we’re sorting alphabetically, the entries are actually in the correct order, but we need to find a way to sort numerically as called Natural Sorting . Please use  in mysql query "sort by length"  column value.


 Query: SELECT alphanumeric, idnumber
       FROM sorting_image
       ORDER BY LENGTH(alphanumeric), alphanumeric
 -------------------------- -------------
| alphanumeric VARCHAR(77) | idnumber INT |
 -------------------------- -------------
| image1                    | 1           |
| image2                    | 2           |
| image3                    | 3           |
| image4                    | 4           |
| image5                    | 5           |
| image6                    | 6           |
| image7                    | 7           |
| image8                    | 8           |
| image9                    | 9           |
| image10                   | 10          |
| image11                   | 11          |
| image12                   | 12          |
 -------------------------- -------------


Wednesday, March 6, 2013

Find out Name and Domain name in email column of table database


   Email Extract


We have find out Name  in email id  of table database. Find below query find name in email id.

Name of email id
select SUBSTR(email, 1, (INSTR(email, '@')-1)) as name from emails

Domain name of email id
select SUBSTR(email, INSTR(email, '@')+1) as name from emails

Tuesday, March 5, 2013

Made multi color Button using css

We have Made multicolor  Button using css in webpage. Following css and html code   use.

Css Code

.buttonnewlink{height:auto; -moz-border-radius:5px; -webkit-border-radius:5px; -khtml-border-radius:5px; border-radius:5px;  padding:8px;*padding:5px; display:inline; overflow:hidden; background-image:-moz-linear-gradient(0% 22px 90deg, #de9e0a, #9f2222); background-image:-webkit-gradient(linear, 0% 0%, 0% 70%, from(#de9e0a), to(#9f2222)); background-color:#de9e0a; float:right; margin:-20px 27px 0 0px;}
.buttonnewlink a{font-family:"Trebuchet MS", Arial, Helvetica, sans-serif; font-size:16px; color:#fff; font-weight:bold; text-decoration:none;}
.buttonnewlink a:hover{text-decoration:none; color:black;}

HTML code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>

<BODY>
<div class="buttonnewlink"><a href="#">Booking Now</a></div>
</BODY>
</HTML>

Output



headers already sent Error session

          We   get  error / Warning headers already sent in  session using php Programming. Following code    solution you solve problem


Warning: session_start(): Cannot send session cookie - headers already sent

Step one :- Search & Open PHI.INI


Step Two:- Search session.cache_limiter 



Step three:- put " public " in front of session.cache_limiter 

Set Value

session.cache_limiter =public


Monday, March 4, 2013

Customize Generate url using htaccess




Please Use below code rewrite url using Htaccess


# For security reasons, Option followsymlinks cannot be overridden.
#Options +FollowSymlinks
Options +SymLinksIfOwnerMatch
<IfModule mod_rewrite.c>
RewriteEngine On

# main list

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} !=/favicon.ico
  RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]

RewriteRule ^index/.html$ index.php [L,QSA]
</IfModule>
//////////////////////////////

Also Redirect module enable in httpd.conf
"Below line  Remove # (By Default )"
'#LoadModule rewrite_module modules/mod_rewrite.so'
After That
'LoadModule rewrite_module modules/mod_rewrite.so'

save file restart wamp server