Category Archives: Quality Assurance & Testing

How to prevent gaps/holes in a MySQL table AUTO_INCREMENT Primary Key field

prevent-gaps-holes-in-a-mysql-table

Prevent gaps/holes in a MySQL table AUTO_INCREMENT Primary Key field.

 

Generally during the MySQL database development you create tables with a Primary Key, a very simple way to create a primary key is make it Auto-increment and unsigned integer with Not Null property right?

 

I think most of you generally follow the above process. Suppose you are playing a very large database and have a very large number of Ids, I know this is rarely happens but you should aware this one, you might face an issue where the new row insertion will through error.

 

Have a look on MySQL data type and their range

 

INT – A normal-sized integer that can be signed or unsigned.
– If signed, the allowable range is from -2147483648 to 2147483647.
– If unsigned, the allowable range is from 0 to 4294967295.
– Max allowed length is 11 digits.

 

TINYINT – A very small integer that can be signed or unsigned.
– If signed, the allowable range is from -128 to 127.
– If unsigned, the allowable range is from 0 to 255.
– Max allowed length is 4 digits.

 

SMALLINT – A small integer that can be signed or unsigned.
– If signed, the allowable range is from -32768 to 32767.
– If unsigned, the allowable range is from 0 to 65535.
– Max allowed length is 5 digits.

 

MEDIUMINT – A medium-sized integer that can be signed or unsigned.
– If signed, the allowable range is from -8388608 to 8388607.
– If unsigned, the allowable range is from 0 to 16777215.
– Max allowed length is 9 digits.

 

BIGINT – A large integer that can be signed or unsigned.
– If signed, the allowable range is from -9223372036854775808 to 9223372036854775807.

– If unsigned, the allowable range is from 0 to 18446744073709551615.
– Max allowed length is 20 digits.

 

Let a suppose you have specified your primary key as INT so the max number you can enter with in it is 4294967295 (if unsigned),
Yes it is not a small number and will not reach generally but if the system allow deletion of records/data on daily basis then what will happen, one day a new row will not insert and it will reach a max limit as you know once a row deleted that id will not use any more and you will have a lot of holes/gaps in the id that was not used.

 

I think you have got what I want to say. You have a table named as student with simply 2 columns
id and name and your table data are

 

1 student1
2 student2
3 student3
.. ..
20 student 20

 

Now you have deleted 2 and 3 id’s records then these id will never user by auto-increment id (primary key), you can use these id but you should know which id is not used and how to fetch this automatically, it will very hard to find if there are lot of rows.

 

How to fill or use this id or holes or gaps automatically.
Use the below query to insert the id instead of use this automatically. It will return NULL if no gap/hole is there in the primary key.

 


SELECT MIN(st1.id+1)
FROM student st1
LEFT JOIN student st2 ON st2.id = st1.id + 1
WHERE st2.id IS NULL

The above query returns you an id that can be used to insert the new row.

There are some most important note you should take care before using these.

 

You should not have values (id) on other tables associated (as a foreign key) with the deleted primary key. If this happen your rest of life will not fine. You should take care that when you insert a new entry with primary key that was taken from the gap, the gaped value should not be there in the associated tables.

You should clean ALL of your tables when you delete a primary key.

 

30 Top PHP Tips and Tricks & Coding Tutorials

php-tricks-tips-coding-tutorials

Tip #1

<?php
$todayTimestamp = time();
/* Don’t Use.*/
$nextDay = $todayTimestamp + 86400;

/* Do instead.*/
$nextDay = strtotime(‘+1 day’, $todayTimestamp);
?>
The first one will not work exactly if you move into or out of daylight savings time.

An extra problem is that the second example is more readable, specially if you add like 2 weeks and 2 days (‘+2 weeks 2 days’)
Use date_default_timezone_set() function before, if you doing calculation to a specific region.

 

 

Tip #2

Don’t use regexp to filter/match an email or an URL.There are already built-in filters in PHP for that.

<?php
$email = filter_var(‘scriptarticle@gmail.com’, FILTER_VALIDATE_EMAIL);
?>
See documentation on filter_var()

 

 

Tip #3

echo gives you more than one string as parameter.

Using some parameters is going to more faster than blending some variables into a parameter.

<?php
$a = ‘Hello’;
$b = ‘Scriptarticle’;
echo ‘Say ‘ .$a. ‘ to ‘ .$b;

//Below will faster
echo ‘Say ‘, $a ,’ to ‘, $b;
?>

 

 

Tip #4

Use isset() instead of strlen() function

<?php
$str = “434e5”;

if (!isset($str{5})) {
echo ‘String must be at least 5 chars<br />’;
}

if (strlen($str) < 5){
echo ‘String must be at least 5 chars’;
}
?>
isset() needs little more time than strlen() because isset() is a language construct.

When you treat strings as arrays, each character in the string is an element in the array. By determining whether a particular element exists, you can determine whether the string is at least that many characters long. (Note that the first character is element 0, so $str[5] is the sixth character in $str)

 

 

Tip #5

Avoid the use of printf function

Unlike print and echo, printf() is a function with associated function execution overhead. More over printf() is designed to support various formatting schemes. To handle formatting printf() needs to scan the specified string for special formatting code that are to be replaced with variables.

<?php
echo ‘Result:’, $result;
// is better than
printf( “Result.%s”, $result );
?>

 

 

Tip #6

Avoid large string concatenation

When do concatenation string, avoid uniting with large size string. It can obstruct code execution that can display faster.

<?php

//Large string concatenation
$title = ‘this is’;
$body  = ‘..a very large blog..’;
echo “Subject.$title\n\n$body”;

//Avoid large string concatenation
$title = ‘this is’;
$body  = ‘..a very large blog..’;
echo “Subject.$title\n\n”;
echo $body;

?>

 

 

Tip #7

Use boolean data type

PHP is allowing writing Boolean data type with uppercase or lowercase.
But, writing with lowercase is faster than uppercase. When found a constant, PHP do lookup hash constant name.

<?php

if ($var = TRUE) {

}

//this is more faster
if ($var = true) {

}

?>
Boolean value 1 and 0 are faster than true and false.

 

 

Tip #8

Avoid space in your code

The main purpose of code optimization is to get faster code execution, because PHP codes going to execute every time they are requested.

Avoid the use of many spaces ( ) is a good thing. Every space is 1 byte and every tab (\t) is 1 byte. When you’re using four spaces, you’ve been use 4 bytes. It will more effective if you’re using a tab (\t).

 

 

Tip #9

Print Output

PHP is giving some sting functions to printing output into browser and we are often using print() and echo() function.

Print() function behavior like the other function in common and having return value integer 1. Thus, print() can used as part of expression which more complex. Meanwhile, echo() is able to accept more than one parameters all at once, and does not having return value.

<?php
print() ‘string 1’;
echo ‘string 1’;
// using some parameters
echo ‘string 1’, “string 2”, ‘…’;
?>
echo() function string will execution more faster than print(). This differentiate caused by will return status (integer) which expose what process has done or not.

 

 

Tip #10

File Access Optimization

When you need to include a file, recheck file content that will be use. If file not contains PHP codes, use readfile() function to increase performance.
Because files that including with readfile() does not parsing by PHP. It will be different with construction language include() and require(), and files will be evaluated before.

Other side is, readfile() increases attack risk. This risk will be happen when accessing file from URL.
Solution for the attack risk is by using File Handling.

 

 

Tip #11

Use ternary operators instead of if, else

Ternary operators can be very helpful and clean up the code, but don’t over complicate them otherwise your code might become inundated with large amounts of complex ridiculousness.

<?php
$name = (!empty($_GET[‘name’])? $_GET[‘name’] .’Scriptarticle’);
?>

 

 

Tip #12

Class Auto loading

If you have a very large number of classes that could potentially use within one or many sections of your code, you could include all of them within a common header file, or only include the ones that you know that you’re going to use on that page. However, you then need to remember to include new classes whenever we want to use a different one etc.

 

Use PHP function spl_autoload_register() instead of that.
You can use the below function where you will need to pass the name of the class that you’re trying to load as the first parameter of the function. As of PHP 5.3.0 we are able to use anonymous functions, basically a function thas has no name.

<?php
spl_autoload_register(function ($class){
echo ‘We are loading class.’ . $class;
include_once(‘classes/’ . $class . ‘.inc.php’);
echo ‘Class loaded.’;
});

?>

In PHP5, there ia a magic function called as __autoload() for fulfilling the same purpose.

 

 

Tip #13

Referencing

Passing variables by reference is a way to pass variables into functions so that the function can alter the original variable without having to return anything or define it as global etc. A function parameter that is going to be passed in as a reference is proceeded by an ampersand (&). Let’s see the below example.

<?php

function lowercase(&$string){
$string = strtolower($string);
}

$name = ‘STEPHEN’;
lowercase($name);
echo $name; // returns stephen
?>

 

There are so many advantages of using references, for example you don’t have to return anything from the function, nor do you have to look to define them as globally accessible.

References are very useful when you use them with arrays. Let’s say we have a function that sets the first item in any array to flower.

 

<?php
function flowerArray(&$array){
$array[0] = ‘flower’;
}
$nonflower = array(‘mahesh’, ‘nirmal’, ‘saurabh’);
flowerArray($nonflower);
print_r($nonflower); // This will now have changed ‘mahesh’ to ‘flower’
?>

 

 

Tip #14
Single Quotes vs. Double Quotes

You may or may not think about this point in your PHP use but it is kind of a big deal. Using the right or wrong quotes can not only cause errors that might be hard to find but there can be a slight performance boost and can make your code much easier to read.

<?php
echo ‘hello scriptarticle’;
?>
<?php
echo “hello scriptarticle”;
?>

These will produce the exact same end result but do you know which one is technically better? The single quote. The single quote just puts exactly what is inside of it without processing while the double quote actually evaluates and processes. Let’s take an example.

<?php

$example = ‘hello scriptarticle’;

echo ‘$example’; // outcome will be $example

echo “$example”; // outcome will be hello scriptarticle
?>

As you can see here the double quotes take the time to process what is inside so technically there will be a little more overhead.

Obviously on a small scale this means nothing but if you have a loop that iterates 1000 or more times you might start to see the benefits of single quotes in a performance sense.

 

 

Tip #15
PHP Short Tags

You know when you just want to pre populate a form or add one PHP variable into the middle of an HTML block. Which one is more readable and easy to use PHP open tags or short tags?

<?php echo $name; ?>
<?=$name ?>

Lower one will produce the exact same output as the first but much neater and with a little less code. It’s it?
NOTE: A short tag is something that can be disabled in the php.ini so it is not guaranteed to work but industry standard has short tags enabled.

 

 

Tip #16
Working with zero filled numbers in PHP

Padding Zero is very easy to do by using PHP build-in functions.

<?php echo $new_number = str_pad($num, 3, “0”, STR_PAD_LEFT); ?>

Remove padding zero
<?php echo intval($new_number); ?>

 

 

Tip #17
Know the Difference between Comparison Operators
<?php

$sentence = ‘scriptarticle is very good blog’;

if (strpos($sentence, ‘scriptarticle’)) {
echo ‘I like scriptarticle.’;
} else {
echo ‘I don\’t like scriptarticle..’;
}

?>
Because the substring “scriptarticle” occurs at the very beginning of “scriptarticle is very good blog”, strpos() correctly returns 0, indicating the first position in the string. Because the conditional statement treats this as a Boolean, it evaluates to FALSE, and the condition fails. In other words, it looks like ‘scriptarticle’ is not in the sentence but it is!

This can be corrected with a strict comparison as below.
<?php

if (strpos($sentence, ‘scriptarticle’) !== FALSE) {
echo ‘I like scriptarticle.’;
} else {
echo ‘I don\’t like scriptarticle..’;
}

?>

 

 

Tip #18
Methods in derived classes run faster than ones defined in the base class.

 

 

Tip #19
Accessing arrays
e.g. $row[‘id’] is 7 times faster than $row[id]

 

 

Tip #20
Avoid functions inside loops

Try to use functions outside loops. Otherwise the function may get called each time and obeviously it will affect performance.

<?php
/*  loop with a count() inside the control block will be
executed on EVERY loop iteration.
*/
$max = count( $array );
for( $i = 0; $i < $max; $i++ )
{
// do something here
}

// is better than
for( $i = 0; $i < count( $array ); $i++ )
{
// do something here
}
?>

It’s even faster if you eliminate the call to count() AND the explicit use of the counter by using a foreach loop in place of the for loop.

<?php
foreach ($array as $i) {
// do something
}
?>

 

 

Tip #21

When you need to output a large or even a medium sized static bit of text it is faster and simpler to put it outside the PHP.

This will make the PHP parser effectively skip over this bit of text and output it as is without any overhead. You should be careful however and not use this for many small strings in between PHP code as multiple context switches between PHP and plain text will be away at the performance gained by not having PHP print the text via one of its functions or constructs.

 

 

Tip #22
true is faster than TRUE

This is because when looking for constants PHP does a hash lookup for name as is & since names are always stored lowercased, by using them you avoid 2 hash lookups. Furthermore, by using 1 and 0 instead of TRUE and FALSE, can be considerably faster.

 

 

Tip #23
Incrementing or decrementing the value of the variable

When incrementing or decrementing the value of the variable $i++ happens to be a slower then ++$i.++$i happens to be faster in PHP because instead of 4 opcodes used for $i++ you only need 3. Post incrementation actually causes in the creation of a temporary var that is then incremented. While pre-incrementation increases the original value directly. This is one of the optimization that opcode optimized like Zends PHP optimizer.

It is a still a good idea to keep in mind since not all opcode optimizers perform this optimization and there are plenty of ISPs and servers running without an opcode optimizer.

 

Additionally,
* Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in a function.
* Incrementing a global variable is 2 times slower than a local variable.
* Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
* Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.

 

 

Tip #24
Free unnecessary memory

Unset your variables to free memory, especially large arrays.

 

 

Tip #25
Specify full paths

Use full paths in includes and requires, less time spent on resolving the OS paths.

<?php
include( ‘/var/www/html/your_app/database.php’ );
//is better than
include( ‘database.php’ );
?>

 

 

Tip #26
Use get_browser() built-in function to get browser information

Easily get your hands on the user’s browser-type.Some programmers leave this process to the browser end but can be useful to get this info server side.

 

 

Tip #27
debug_print_backtrace()

This print a debug-style list of what was called to get the point where this function is called.

 

 

Tip #28
Automatic optimization for your database

You will probably add and delete tables from time to time. Therefore, you should use a solution that works no matter how your database looks like. For this, you can use this PHP script that finds all your tables, and then perform Optimize on every single one.

<?php
dbConnect();
$tables = mysql_query(“SHOW TABLES”);

while ($table = mysql_fetch_assoc($tables))
{
foreach ($table as $db => $tablename)
{
mysql_query(“OPTIMIZE TABLE ‘”.$tablename.”‘”)
or die(mysql_error());
}
}
?>

 

Tip #29
require() vs. require_once()

Use require() instead of require_once() where possible.

 

 

Tip #30
Secure HTTP connections

You can force a secure HTTP connection using the following code,
<?php

if (!($HTTPS == “on”)) {
header (“Location.https://$SERVER_NAME$php_SELF”);
exit;
}
?>

 

 

ACID (Atomicity Consistency Isolation Durability) Model of database

acid-atomicity-consistency-isolation-durability

ACID(Atomicity Consistency Isolation Durability) is a set of properties that guarantee that database transactions are processed reliably.

In the context of databases, a single logical operation on the data is called a transaction.

 

Atomicity
Atomicity is an all-or-none proposition.
Modifications on the data in the database either fail or succeed. Each transaction is said to be “atomic.” If one part of the transaction fails, the entire transaction fails. It is critical that the database management system maintain the atomic nature of transactions in spite of any DBMS, operating system or hardware failure.

 

Consistency
Consistency guarantees that a transaction never leaves your database in a half-finished state.
Only valid data (valid according to integrity constraints) may be committed. If, for some reason, a transaction is executed that violates the database’s consistency rules, the entire transaction will be rolled back and the database will be restored to a state consistent with those rules. On the other hand, if a transaction successfully executes, it will take the database from one state that is consistent with the rules to another state that is also consistent with the rules.

 

Isolation
Isolation keeps transactions separated from each other until they’re finished.
One transaction does not interfere with another. The ‘executor’ of a transaction has the feeling that he has the entire database for himself.

 

Durability
A committed transaction will not be lost.
Durability means that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors,  i.e. the database will keep track of pending changes in such a way that the server can recover from an abnormal termination.

 

Example of printer to understand the ACID property more clearly.
Atomicity
Either the entire document gets printed or nothing at all.

Consistency
At end-of-transaction, the paper feed is positioned at top-of-page.

Isolation
No two documents get mixed up while printing.

Durability
The printer can guarantee that it was not “printing” with empty cartridges

 

ACID properties provide the basic building blocks of any database transaction model. So spend few minutes to review these characteristics and commit these in your memory 🙂

 

Can not receive emails sent from my mail server to my test accounts on gmail, hotmail and yahoo, how to resolve this issue?

can-not-receive-emails-sent-from-my-mail-server

On a normal server, there is a limit of mails, that can be sent in a day, but due to error or some issue if a large number of mails sent automatically from your server, and then they (gmail, hotmail yahoo and other) block the incoming mails from that server.

 

This means that your IP address is blocked and reported as a spam IP, to remove it from the spam list,

 

1. Go to http://www.spamhaus.org/lookup.lasso
2. Check your IP/Domain if it is blocked
3. If it is blocked select to remove it from black list

 

Wait between half and one hour and then try again to send an email to hotmail, gmail or yahoo.

 

 

Useful PHP validation functions

String Validation
Validate name, surname by the below function to restrict only letters and spaces.

function validateString($str)
{
//accept letters and space only
return preg_match('/^[A-Za-zs ]+$/', $str);
}

Validate numeric value by the below function to restrict only numbers,you can uncomment any line according to your need.

function validateNumber($value)
{
//is_double($value);
//is_float($value);
//is_int($value);
//is_integer($value);
return is_numeric($value);
}

Alphanumeric Characters Validation
Below function validates alphanumeric characters.ctype is complete function library in PHP.

function validateAlphanumeric($string)
{
return ctype_alnum ($string);
}

Validation for URL Exist or not
This function will check whether a given URL exist and not only validate it.

function urlExist($url)
{
$url = @parse_url($url);
if (!$url){
return false;
}
$url = array_map('trim', $url);
$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
$path = (isset($url['path'])) ? $url['path'] : '';

if ($path == ''){
$path = '/';
}
$path .= (isset($url['query'])) ? '?$url[query]' : '';
if (isset($url['host']) AND $url['host'] != @gethostbyname($url['host']))
{
if (PHP_VERSION >= 5){
$headers = @get_headers('$url[scheme]://$url[host]:$url[port]$path');
}else{
$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
if (!$fp){
return false;
}
fputs($fp, 'HEAD $path HTTP/1.1rnHost: $url[host]rnrn');
$headers = fread($fp, 4096);
fclose($fp);
}
$headers = (is_array($headers)) ? implode('n', $headers) : $headers;
return (bool)preg_match('#^HTTP/.*s+[(200|301|302)]+s#i', $headers);
}
return false;
}

Validation for check Image Exist
Below function will check whether a given image link exist and not.

function imageExist($url) {
if(@file_get_contents($url,0,NULL,0,1)){return 1;}else{ return 0;}
}

IP Address Validation
function will validate an IP address.

function validateIP($IP){
return preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/',$IP)
}

Validation for Proxy
This function will detect proxy visitors even those that are behind anonymous proxy 🙂

function validateProxy(){
if ($_SERVER['HTTP_X_FORWARDED_FOR']
|| $_SERVER['HTTP_X_FORWARDED']
|| $_SERVER['HTTP_FORWARDED_FOR']
|| $_SERVER['HTTP_VIA']
|| in_array($_SERVER['REMOTE_PORT'], array(8080,80,6588,8000,3128,553,554))
|| @fsockopen($_SERVER['REMOTE_ADDR'], 80, $errno, $errstr, 30))
{
exit('Proxy detected');
}
}

Strong Password Validation
Check whether a particular password filled by the user is strong enough or not.

function validatePassword($password){
//must contain 8 characters, 1 uppercase, 1 lowercase and 1 number
return preg_match('/^(?=^.{8,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$/', $password);
}

Credit Card Validation
Below function validate credit card number format.

function validateCreditCard($cc){
//eg. 746486033718121
return preg_match('/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/', $cc);
}

Search Engine Optimization & SEO rich Web Content Development

Search Engine Optimization (SEO) is the process of improving the ranking in the search engine it involves editing its content, HTML, Images.

Content is always king and it should be very relative to its specific keywords. Content portion itself of the web development process is vital to the overall success of the website and Google raking and PR.

 

Web Content is the main reason that people come to your Web pages but if your designs, architectures, and interactivity don’t provide that content they will leave.

 

Keep in mind that content is still king.

Basically, there are two types of Web Content:

=>Text
=>Multimedia

 

Text Web Content
It’s the written content that’s on the page, both inside images and in text blocks. The best textual Web Content is that text that has been written for the Web, rather than simply copy-and-pasted from a print source. Textual Web Content will also have good internal links to help readers get more information and aid in scanning the text. Finally, Web text will be written for a global audience as even local pages can be read by anyone around the world.

 

Multimedia Web Content
The other type of Web Content is multimedia. To put it simply, multimedia is any content that isn’t text, but it includes the following.

 

Images

 

Animation/Flash

 

Sound

 

Video

 

Images are the most common way to add multimedia to websites. Images on Web pages should be optimized, so that they download fast as it affect the site load speed.

 

Animation can be created using GIF images or using Flash, JavaScript, Ajax or other animation tools.

 

Sound is embedded in a Web page so that readers hear it when they enter the site or when they click a link to turn it on. Always keep in mind that sounds on Web pages can create frustration, especially if you turn it on automatically and don’t provide any way to turn it off easily.

 

Video is getting more and more popular on Web pages. But it can be challenging to add a video so that it works reliably and well across different browsers.

 

What should be there in your Web Content?

 

1)  It should be very simple, lucid and easy to read and understand.

 

2)  It should be original content (no copy-paste).

 

3)  Search Engine prefers the grammatically correct content first.

 

4)  Use optimum keywords and LSI (Latent Semantic Indexing) keywords after proper keyword analysis.

 

5)  Web Content should be written after proper SEO analysis.

 

Hope the above article will help you to write the content more SEO friendly & rich.