Showing posts with label Database. Show all posts
Showing posts with label Database. Show all posts

Tuesday, 13 November 2012

country state city ajax dropdown

PHP MySQL country state city ajax drop down with database.

When you are creating triple or more than 2 dependent dropdown then you might need to take care of parents and child dropdowns. Means if you make changes to parent then your child nodes should get affected too.

Here in this country state city dropdown as you change country then it is required to change states. and when states get changed required to change cities too.

Below code works well in all modern browsers like Chrome, mozilla, IE9/8/7 and works well so copy and enjoy it

Database design/structure for country, state and city tables

CREATE TABLE IF NOT EXISTS `country` (
  `Country_Id` varchar(3) NOT NULL,
  `name` varchar(60) NOT NULL,
  `continent_code` varchar(30) NOT NULL,
  `tel_code` varchar(5) NOT NULL,
  PRIMARY KEY (`Country_Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

`continent_code` and `tel_code` is not necessary yet you can avoid that fields.

CREATE TABLE IF NOT EXISTS `state` (
  `state_id` varchar(6) NOT NULL,
  `country_id` varchar(3) NOT NULL,
  `name` varchar(30) NOT NULL,
  PRIMARY KEY (`state_id`),
  KEY `Country_Id` (`country_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `city` (
  `city_id` varchar(10) NOT NULL,
  `state_id` varchar(6) NOT NULL,
  `city_name` varchar(50) NOT NULL,
  PRIMARY KEY (`city_id`),
  KEY `state_id` (`state_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- foreign key constrains for table state and city (If you dont know simply avoid this)

ALTER TABLE `city`
  ADD CONSTRAINT `city_ibfk_1` FOREIGN KEY (`state_id`) REFERENCES `state` (`state_id`) ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE `state`
  ADD CONSTRAINT `state_ibfk_1` FOREIGN KEY (`country_id`) REFERENCES `country` (`Country_Id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- End of database structure.

Javascript Code

<script>
var xmlhttp;
function ajaxFunction(url,myReadyStateFunc)
{
   if (window.XMLHttpRequest)
   {
      // For IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
   }
   else
   {
      // For IE5, IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   xmlhttp.onreadystatechange= myReadyStateFunc;        // myReadyStateFunc = function
   xmlhttp.open("GET",url,true);
   xmlhttp.send();
}

function getState(x)
{
    // in second argument of ajaxFunction we are passing whole function (onreadystatechange function).
    // Goto getState.php code
    ajaxFunction("getState.php?cid="+x, function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
var s = xmlhttp.responseText;    //   s = "1,2,3,|state1,state2,state3,"
s=s.split("|");                              //   s = ["1,2,3,", "state1,state2,state3,"]
sid = s[0].split(",");                    //  sid = [1,2,3,]
sval = s[1].split(",");                   //  sval = [state1, state2, state3,]
st = document.getElementById('state')
st.length=0
for(i=0;i<sid.length-1;i++)
{
st[i] = new Option(sval[i],sid[i])
}
getCity(-1) // emptying the city.
        }
    });
}
function getCity(x)
{
    // in second argument of ajaxFunction we are passing whole function.
   // Goto getCity.php code
   ajaxFunction("getCity.php?sid="+x, function()
   {
       if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
var c = xmlhttp.responseText;
c=c.split("|");
cid = c[0].split(",");
cval = c[1].split(",");
ct = document.getElementById('city')
ct.length=0
for(i=0;i<cid.length-1;i++)
{
ct[i] = new Option(cval[i],cid[i])
}
        }
    });
}
</script>
<style>
select{width:270px;size:10}
</style>

HTML Code

<table>
<tr>
<td>Country </td>
<td>:&nbsp;<select name="country" id="country" onchange="getState(this.value)">
<option value="-1">Select Country</option>
<?php
$cntry = mysql_query("SELECT `Country_Id`, `name` FROM country ORDER BY `name` ASC");
while($row = mysql_fetch_assoc($cntry))
{
echo '<option value="'.$row['Country_Id'].'">'.$row['name'].'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>State </td>
<td>:&nbsp;<select name="state" id="state" onchange="getCity(this.value)">
<option value="-1">Select State</option>
</select>
</td>
</tr>
<tr>
<td>City </td>
<td>:&nbsp;<select name="city" id="city" >
<option value="-1">Select City</option>            
</select>
</td>
</tr>
</table>

PHP Code for getState.php

$link = mysql_connect("localhost","root","");
$dbSelected = mysql_select_db('pra_countrystate');
$id="-1,";
$sname="Select State,";
$cid = $_GET['cid'];
if($cid=="-1")
{
$response = $id."|".$sname;
echo $response;
}
else
{
$result = mysql_query("SELECT `state_id`, `name` FROM `state` WHERE `country_id` = ".$cid." ORDER BY `name` ASC");
while($row = mysql_fetch_assoc($result))
{
$id .=$row['state_id'].","; 
$sname .=$row['name'].","; 
}
$response = $id."|".$sname;
echo $response;
}
?>

PHP Code for getCity.php

<?php
$link = mysql_connect("localhost","root","");
$dbSelected = mysql_select_db('pra_countrystate');
$id="-1,";
$cname="Select City,";
$sid = $_GET['sid'];
if($sid=="-1")
{
$response = $id."|".$cname;
echo $response;
}
else
{
$result = mysql_query("SELECT `city_id`, `city_name` FROM `city` WHERE `state_id` = ".$sid." ORDER BY `city_name` ASC");

while($row = mysql_fetch_assoc($result))
{
$id .=$row['city_id'].",";
$cname .=$row['city_name'].",";
}
$response = $id."|".$cname;
echo $response;
}
?>

Tuesday, 23 October 2012

import-insert data from csv file to mysql using php

Import/Inserting data into mysql with load data query. Using load data infile query we can easily insert data into table.
We already have seen the tutorial on how to export data into csv - click here to see export csv tutorial

It is quiet often required to insert bulk of data into database table doing with script its bit lengthy. Instead we can easily import data using mysql load data query.

Sysntax for LOAD DATA INFILE

LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name' 
          [REPLACE | IGNORE] INTO TABLE tbl_name 
          [CHARACTER SET charset_name] 
          [FIELDS [TERMINATED BY 'string'] [OPTIONALLY] ENCLOSED BY 'char'] [ESCAPED BY 'char'] ] 
          [LINES [STARTING BY 'string'] [TERMINATED BY 'string']] 
          [IGNORE number LINES] 
          [(col_name_or_user_var,...)] 
Ex. 
LOAD DATA INFILE 'PATH_TO_CSV' INTO TABLE tblTableName FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (tblCol1,tblCol2,tblCol3)
[LOW_PRIORITY | CONCURRENT]
LOW_PRIORITY : If you use LOW_PRIORITY execution of the LOAD DATA statement is delayed until no other clients are reading from the table. This affects to only those storage engines that uses only table-level locking (such as MyISAM, MEMORY, and MERGE).
CONCURRENT : If you specify CONCURRENT with a MyISAM table that satisfies the condition for concurrent inserts, other threads can easily retrieve data from the table while LOAD DATA is executing on other hand.
[LOCAL]
If it is specified, is treated as client end connection. Means when you specified it is read on client side and sent to server where a temporary copy generated for execution
 [REPLACE | IGNORE]
This two are Control handling Keywords on input rows that duplicate existing rows on unique key values:
REPLACE : Input rows replaces existing rows that have same value for primary key, unique key index.
 IGNORE : Means Duplicate rows are skipped.
If you don't specify either option behavior depends on LOCAL keywords. If you don't specify LOCAL Keyword then error generated when duplicate entry found. With LOCAL Keyword default behavior is IGNORE.
[FIELDS [TERMINATED BY 'string'] [OPTIONALLY] ENCLOSED BY 'char'] [ESCAPED BY 'char'] ] 
This are the arguments that how you wants to treat all fields.  TERMINATED BY  to define field  end with specified string. ENCLOSED BY  specified character.
 If you don't specify any of the above argument it will treat as below default behavior 
FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\'
[LINES [STARTING BY 'string'] [TERMINATED BY 'string']] 
This line is to determine line behavior.  STARTING BY  is used to define starting symbols of given files matches the lines which starting with specified string value.  TERMINATED BY  is to used to specify end of LINE.
 If you don't specify anything then default behavior for LINE is as below
LINES TERMINATED BY '\n' STARTING BY ''
[IGNORE number LINES]
This is to specify starting of line number means to ignore the rows from top. If you specfy IGNORE 1 LINES then first line will be skipped, execution will start from the second row/record.
[(col_name_or_user_var,...)] 
Specify the respective columns for your insertion operation.

Monday, 20 August 2012

Create-Export csv file from mysql using php

Often you or your client has requirement to generate/create/export table records of database in excel sheet. 
Now it is possible to generate excel sheet of mysql database table using php. 

We will see that how easy to generate reports using php and mysql of table.

Code: 
<?php
    //Connection to database
    mysql_connect("localhost","root","");
    mysql_select_db("yourDatabase");

    $result = mysql_query("SELECT * FROM `table`");
    if (!$result) die('Couldn\'t fetch records');
    $num_fields = mysql_num_fields($result);

    $headers = array();

  // Creating headers for output files
    for ($i = 0; $i < $num_fields; $i++)
    {
        $headers[] = mysql_field_name($result , $i);
    }

    $fp = fopen('php://output', 'w');
    if ($fp && $result)
    {
    // name of file with date
        $filename = "jobPostingReport-".date('Y-m-d').".csv";
         
            // Setting header types for csv file.
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename='.$filename);
            header('Pragma: no-cache');
            header('Expires: 0');
            fputcsv($fp, $headers);

            while ($row = mysql_fetch_row($result))
            {
                 fputcsv($fp, array_values($row));
            }
            die;
     }
?>

Explanation Of Code:

First two lines to create connection to the database. Then create your desired query with field which are required to generate csv files.
if(!$result) to check whether your query is correct or not, if not then it will execute next lines means here "die".
Next set the headers/titles for CSV files from query resource. mysql_field_name() has two arguments first one is resource and the second one is offset, offset starts with 0.
 Now open the file writing wrapper with writable mode using fopen('php://output', 'w'). php://output is a write-only stream that allows you to write to the output buffer mechanism in the same way as print and echo.
for more info about wrappers - http://www.php.net/manual/en/wrappers.php

Now, use the above headers to export/download csv files from MySQL database and php.

fputcsv() command will help you to place data into csv sheet. At first write the headers/titles of csv files means field name to the csv file with help of file pointer which we have created earlier.

Now, Finally using fetch_array() fetch all rows and write them all into csv file using file pointer.

Saturday, 18 August 2012

database engine and database table types in mysql-mysqli

Engines or Engine types are storage handlers for database tables. MySQL / MySQLi supports different engines like MyIASM, InnoDB, HEAP (Memory), CSV, ARCHIVE, BLACKHOLE, MERGE (MRG_MyISAM) etc.

Engine selection is depends upon what kind of requirement you have. Generally, people do avoid it as they don't have much knowledge about it. But engine is performing very important role in your transaction and table data safety. Most people uses MyIASM and InnoDB. InnoDB is having higher advantage and very safe engine compare to MyIASM. We will see its comparison below.

MyIASM
MyIASM is default engine in MySQL/MySQLi. It used very oftenly and oldest engine database. It is suitable for simple and small application where there is no importance of security and relational database. MyIASM is unable to setup relational key(Foreign keys). 
It provides high-speed storage and retrieval, as well as fulltext searching capabilities. MyISAM is supported in all MySQL configurations, and is the default storage engine unless you have configured MySQL to use a different one by default. It has very average rating for table design. 
MyIASM is extension of IASM which is not available at all. 
Each MyIASM table stored on disk with three files. The files name are same as table name and have three different file types. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex) extension.
InnoDB
InnoDB is one of the good and safe engine for transaction. It is transaction safe engine and follows ACID property(Atomicity, Consistency, Isolation, Durability). It has commit, rollback, and crash-recovery capabilities to protect user data.  
InnoDB row-level locking and Oracle-style consistent nonlocking reads increase multi-user concurrency and performance. InnoDBstores user data in clustered indexes to reduce I/O for common queries based on primary keys.  
To maintain data integrity, InnoDB also supports FOREIGN KEY referential-integrity constraints. You can freely mix InnoDB tables with tables from other MySQL storage engines, even within the same statement. Simply we can say that  nnoDB is very reliable due to transactional nature of data operations, and makes it very good choice for systems where backup operation are essential and often needed. InnoDB tables are reliable and has many safety measures implemented to make sure that data remains safe. 
InnoDB is used in production at numerous large database sites requiring high performance. The famous Internet news site Slashdot.org runs on InnoDB. Mytrix, Inc. stores more than 1TB of data in InnoDB, and another site handles an average load of 800 inserts/updates per second in InnoDB.  
It has only one file type .frm, which means reduce in other extra files compare to MyIASM. Possibly prefer InnoDB over MyIASM. 
MEMORY (HEAP)
The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred term. 
As indicated by the engine name, MEMORY tables are stored in memory. They use hash indexes by default, which makes them very fast, and makes it very useful for creating temporary tables.  
As its being volatile, when the server shut down all the data are lost only table definition remains(becomes empty table), means needs to store the data before shutting down the server.  
As table definition remains in database, it creates one file of type .frm extension.
MERGE (MRG_MyISAM)
The MERGE storage engine is also known as MRG_MyISAM. It is collection of identical MyIASM tables, which cab be used as one. 
“Identical” means that all tables have identical column and index information. You cannot merge MyISAM tables in which the columns are listed in a different order, do not have exactly the same columns, or have the indexes in different order. 
When you create a MERGE table, MySQL creates two files on disk. The files have names that begin with the table name and have an extension to indicate the file type. An .frm file stores the table format, and an .MRG file contains the names of the underlying MyISAM tables that should be used as one. The tables do not have to be in the same database as the MERGE table. 
To create a MERGE table, you must specify a UNION=(list-of-tables) option that indicates which MyISAMtables to use.
CSV
The CSV storage engine stores data in text files using comma-separated values format. It can be used on windows only in newer version which is higher than MySQL 5.1. 
When you create a CSV table, the server creates a table format file in the database directory. The file begins with the table name and has an .frm extension. The storage engine also creates a data file. Its name is same as table name and has a .CSV extension. The data file is plain text file. When you store data into the table, the storage engine saves it into the data file in comma-separated values format (CSV).
ARCHIEVE
The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. 
Archive storage engine does compresses your data and should be good for log storage or storing something which needs no updates and no indexes, however compression ratio is not perfect, configuration and stats could be improved.  
The ARCHIVE engine supports INSERT and SELECT, but not DELETE, REPLACE, or UPDATE. It does support ORDER BY operations, BLOB columns, and basically all but spatial data types. The ARCHIVE engine uses row-level locking.  
When you create an ARCHIVE table, the server creates a table format file in the database directory. The file begins with the table name and has an .frm extension. The storage engine creates other files, all having names beginning with the table name. The data and metadata files have extensions of .ARZ and .ARM, respectively. An.ARN file may appear during optimization operations.
BLACKHOLE
The BLACKHOLE storage engine act as a "black hole", it accepts data and throws it away and does not store anything. Retrieves only empty result. 
When you create a BLACKHOLE table, only the .frm file is created, because it does not reuire to store data so no .MYD and .MYI file needed.  
If you run in a high volume production system where you may have one or more master databases for writes/updates/deletes and a whole bunch of slaves reading the log from that master which in short increase the network traffic, disk I/O, CPU power and others, this affect the performance of a Master Server.
What you then have is the Master only replicating to one database, increasing the Master’s capacity to process transactions. The slaves consume the log file from the Blackhole server. It acts as a proxy at this point, with the benefit of freeing up resources on the Master’s server. 
The master writes to its binary log. The “Blackhole” server acts as a proxy slave server, it does not actually store any data, so there is little processing overhead incurred and other SLAVE server will read a binary log from this server. 
Other possible uses for the BLACKHOLE storage engine include:
- Verification of dump file syntax.
- Measurement of the overhead from binary logging, by comparing performance using  BLACKHOLE with and without binary logging enabled.

Sunday, 12 August 2012

Stored Procedure in php with example

Stored Procedure : These are set of SQL Commands / Statements that are stored in database in compiled form so that can be shared by a number of programs.

stored procedure is a subroutine stored in the database catalog.

Advantages of Stored Procedure
  • Developed once, All applications can use same Command / Statements.
  • Task becomes easier and less complicated.
  • Network traffic reduced to greater extent as not sent repeatedly to server / reduces CPU load.
  • Centralization of Command / Statements, which helps in repeated call
  • Runs on any environment.


Basic Structure

CALL Procedure(....) - The CALL SQL statement is used to execute a stored procedure.

Parameters - IN/INOUT/OUT

ParameterDescription
IN An IN parameter passes a value into a procedure with CALL. The procedure might modify the value, but the modification is not visible to the caller when the procedure returns.
INOUT An INOUT parameter is initialized by the caller, can be modified by the procedure, and any change made by the procedure is visible to the caller when the procedure returns.
OUT An OUT parameter passes a value from the procedure back to the caller. Its initial value is NULL within the procedure, and its value is visible to the caller when the procedure returns.
Specifying a parameter as IN, OUT, or INOUT is valid only for a PROCEDURE. For a FUNCTION, parameters are always regarded as IN parameters.

Understand Procedure in PHP By Example

First we need to create database:
CREATE DATABASE `userdata`
Then create Table:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`contact` varchar(10) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5  
 Dumping Data into table:
INSERT INTO `users` (`id`, `name`, `contact`) VALUES
(1, 'Mukund Topiwala', '9422222222'),
(2, 'Ram ', '6666666635'),
(3, 'Veer', '5689782532'),
(4, 'BCW', '6584225141');
Afte Creating database and tables now look at the procedure.

Remember: 
"If you are using phpMyAdmin for MySQL or MySQLi You may have to create and compile Your Procedure into sql command box."
DELIMITER //
DROP PROCEDURE IF EXISTS `userdata`.`getUsers` //
CREATE PROCEDURE `userdata`.`getUsers`
(
IN uId INT,
OUT fullName VARCHAR(100),
OUT contactNo VARCHAR(10)
)
BEGIN
SELECT name, contact
INTO fullName, contactNo
FROM users
WHERE id = uId;
END //
DELIMITER ;
Explanations:
Here Client DELIMITER command used to change default delimiter ; to // while procedure is being defined. After setting DELIMITER DROP is used to drop the old procedure similar to drop table. First you check for the stored procedure if exist drop it before you recreate it. 
CREATE is used to create new stored procedure. Here in above example getUsers has three parameters uId, fullName, and contactNo. uId is passed to the Procedure that is why set to IN while fullName and contactNo is being returned from the procedure to caller, set to OUT. For more details see parameters table. 
Body of Procedure is written inside the BEGIN and END block. SELECT query that is used to select name and contact from the users table where the id = uId which is passed from the caller in CALL statement. OUT variable retrieves the value from the SELECT statement. fullName is set into  name and simillarly contactNo is set into contact.
Remember:

"Your Procedure is stored inside `ROUTINES` Table of `information_schema`

Once You compiled and successfully created your Procedure you can view it by following query

select routine_definition
from information_schema.routines
where routine_schema = 'userdata'
and routine_name = 'getUsers';   "
As you have created and compiled your procedure in MySQL now time to create a PHP file.

With MySQL AND PHP
<?php
       $mysql = mysql_connect('localhost', 'root', '');
       mysql_select_db('userdata', $mysql) ; 
       print '<h3>MySQL: simple select</h3>';
       $rs = mysql_query( 'SELECT * FROM users;' );
       while($row = mysql_fetch_assoc($rs))
      {
      echo $row["name"]."||".$row["contact"]."<br>";
      } 
      print '<h3>MySQL: calling Procedure with out variables</h3>';
      $rs = mysql_query( 'CALL getUsers(1, @name, @contact)' );
      $rs = mysql_query( 'SELECT @name, @contact' );
      while($row = mysql_fetch_assoc($rs))
      {
      echo $row["@name"]."||".$row["@contact"];
      }
?>
With MySQLi AND PHP
$mysqli = new mysqli('localhost', 'root', '', 'userdata');
print '<h3>MYSQLI: simple select</h3>';
$rs = $mysqli->query( 'SELECT * FROM users;' );
while($row = $rs->fetch_object())
{
print_r($row);
print("<br>");
}
print '<h3>MYSQLI: calling Procedures with out variables</h3>';
$rs = $mysqli->query( 'CALL getUsers(1, @name, @contact)' );
$rs = $mysqli->query( 'SELECT @name, @contact' ); 
while($row = $rs->fetch_object())
{
print_r($row);
print("<br>");
} 
Output :

To retrieve all field as array you can use print_r($row) function too.
replace echo line with print_r


MySQLi output :


Now to retrieve all the recordset with no repeated same value. (visit - retrieve recordset using stored procedure)

DELIMITER //
DROP PROCEDURE IF EXISTS `test`.`get_users`$$
CREATE PROCEDURE  `test`.`get_users`()
BEGIN
SELECT *
FROM users;
END //
DELIMITER ; 
print '<h3>MySQL: calling Procedure returning a recordset – Won't work here with MySQL</h3>';
$rs = mysql_query( 'CALL get_users()' );
while($row = mysql_fetch_assoc($rs))
{
print_r($row);
print("<br>");
} 
Output: Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in ***.php on line xx 
print '<h3>MySQLi: calling Procedure returning a recordset</h3>';
$rs = $mysqli->query( 'CALL get_users()' );
while($row = mysql_fetch_assoc($rs))
{
print_r($row);
print("<br>");
} 
Output: as above in simple mysqli select

As you can see from the results above, mysql could not get the recordset returned by the stored procedure while mysqli and PDO could. After some more research, some people mentioned (Bob’s World, php.net) that by adding ‘false,65536′ to the end of the mysql_connect line, mysql could then get recordsets from stored procedures. I tried this and in fact it does work. So by changing
$mysql = mysql_connect(‘localhost’, ‘example’, ‘example’);
to:
$mysql = mysql_connect(‘localhost’, ‘example’, ‘example’,false,65536);

Wednesday, 27 June 2012

php code optimization tips

Wrap your string in single quotes (’) instead of double quotes (”) is faster because PHP searches for variables inside “…” and not in ‘…’, use this when you’re not using variables you need evaluating in your string.

If method is static, declare that method for once and reuse that method and achieve improvement in speed.


Echo is faster than print
echo and print are virtually (not technically) the same thing. The (pretty much only) difference between the two is that print will return the integer 1, whereas echo returns nothing. Keep in mind that neither is actually a function, but rather language constructs. echo allows you to pass multiple strings when using it as if it were a function (e.g., echo($var1, $var2, $var3)) 
echo can also be shorthanded by using the syntax <?= $var1; ?> (in place of <?php echo $var1; ?>).
Use loop limit calculation outside and same extra calculation
for($i=0; $i<$cnt*10; $++) replace with$count1 = $cnt*10;for($i=0; $i<$count1; $i++)
Unset the value of variable and get more freed space for faster performance
Use the unset($var); to unset the variable.
Avoid expensive require_once() and include_once() to for faster execution
_once() method do require to store log and has to check log every time for file requie/include.
Use fullpath because it takes less time in path resolving.

Possibly avoid regex by the use of strncasecmp, strpbrk or stripos.

str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4

If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.

It is better to use select statements than multi if, else if, statements.
if...else statement - use this statement if you want to execute a set of code when a condition is true and another if the condition is not true
elseif statement - is used with the if...else statement to execute a set of code if one of several condition are true
switch statement - is used if you want to select one of many blocks of code to be executed, use the Switch statement. The switch statement is used to avoid long blocks of if..elseif..else code.
Error suppression with @ is very slow.
@ is called error suppression symbol in php and used to tell php that it shouldn’t generate a warning (or a notice) as u know It’s perfectly correct to ignore that warning message. And overuse of that @ symbol can decrease your speed performance 

Turn on apache's mod_deflate
It is good to compress files on apache to reduce bandwidth usage and speed. This can be done by mod_deflate in apache 
In order to compress files using mod_deflate on Apache 2.x you first need to load the module, so you'll need to edit the Apache configuration. The exact location of the configuration file varies between each Linux/BSD distro, but it's often found at /etc/httpd/httpd.conf or /etc/apache2/httpd.conf, or /etc/httpd/conf/httpd.conf or /etc/apache2/conf/httpd.conf. If you are unsure of its location locate httpd.conf will usually send you in the right direction. 
So now that you've found the Apache config file, open it up in your favourite text editor as root or using sudo, and add this line: 
LoadModule deflate_module modules/mod_deflate.so this section:
<Location />          AddOutputFilterByType DEFLATE text/html text/plain text/xml text/x-js text/css</Location> 
Always remember to close database connection after the use of that connection

If you are using prepared statement then remember to close stmt objects, and in select statement when you 
use store_result use free_result to free the memory
Use $stmt->free_result(); and 
$stmt->close()
$row['id'] is 7 times faster than $row[id], because if you don’t supply quotes it has to guess which index you meant, assuming you didn’t mean a constant.

Error messages are expensive try to reduce error message and warning messages

Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x++) The count() function gets called each time.
$cnt = count($array);
For($x=0; $x < $cnt; $x++)
{
      ………..
}
Incrementing a local variable in a method is the fastest. Nearly the same as calling a local variable in function.

Incrementing a global variable is 2 times slow than a local var.

Try to exchange calculation with cheaper instruction. Ex. Replace multiplication by cheaper instruction addition.
$z = $x*2;
$z = $x+$x;
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.

Try to use local variable rather than global variable. 
Little time is waste behind checking the global variable
Surrounding your string by ' instead of “ will make things interpret a little faster since php looks for variables inside ”..." but not inside '...' . Of course you can only do this when you don't need to have variables in the string.

A PHP script will be served at least 2-10 times slower than a static HTML page by Apache. Try to use more static HTML pages and fewer scripts.
Means use html tags outside the php script code by breaking php scriptAvoid <?php echo “<br />” ?> and use simply <br />
Your PHP scripts are recompiled every time unless the scripts are cached. Install a PHP caching product to typically increase performance by 25-100% by removing compile times.

Cache as much as possible. Use memcached - memcached is a high-performance memory object caching system intended to speed up dynamic web applications by alleviating database load. OP code caches are useful so that your script does not have to be compiled on every request

When working with strings and you need to check that the string is either of a certain length you'd understandably would want to use the strlen() function. This function is pretty quick since it's operation does not perform any calculation but merely return the already known length of a string available in the zval structure (internal C struct used to store variables in PHP). However because strlen() is a function it is still somewhat slow because the function call requires several operations such as lowercase & hashtable lookup followed by the execution of said function. In some instance you can improve the speed of your code by using an isset() trick.
Example:
if (strlen($foo) < 5) { echo "Foo is too short";}
vs.
if (!isset($foo{5})) { echo "Foo is too short"; }
Calling isset() happens to be faster then strlen() because unlike strlen(), isset() is a language construct and not a function meaning that it's execution does not require function lookups and lowercase. This means you have virtually no overhead on top of the actual code that determines the string's length.

When incrementing or decrementing the value of the variable $i++ happens to be a tad slower then ++$i. This is something PHP specific and does not apply to other languages, so don't go modifying your C or Java code thinking it'll suddenly become faster, it won't. ++$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 Zend's 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.

Not everything has to be OOP, often it is too much overhead, each method and object call consumes a lot of memory.

Do not implement every data structure as a class, arrays are useful, too

Don't split methods too much, think, which code you will really re-use

You can always split the code of a method later, when needed

Make use of the countless predefined functions

If you have very time consuming functions in your code, consider writing them as C extensions

Profile your code. A profiler shows you, which parts of your code consumes how many time. The Xdebug debugger already contains a profiler. Profiling shows you the bottlenecks in overview

mod_gzip which is available as an Apache module compresses your data on the fly and can reduce the data to transfer up to 80%