50+ PHP tips and tricks

  1. echo is faster than print.
  2. 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.
  3. Use sprintf instead of variables contained in double quotes, it’s about 10x faster.
  4. Use echo’s multiple parameters (or stacked) instead of string concatenation.
  5. Use pre-calculations, set the maximum value for your for-loops before and not in the loop. ie: for ($x=0; $x < count($array); $x), this calls the count() function each time, use $max=count($array) instead before the for-loop starts.
  6. Unset or null your variables to free memory, especially large arrays.
  7. Avoid magic like __get, __set, __autoload.
  8. Use require() instead of require_once() where possible.
  9. Use full paths in includes and requires, less time spent on resolving the OS paths.
  10. require() and include() are identical in every way except require halts if the file is missing. Performance wise there is very little difference.
  11. Since PHP5, the time of when the script started executing can be found in $_SERVER[’REQUEST_TIME’], use this instead of time() or microtime().
  12. PCRE regex is quicker than EREG, but always see if you can use quicker native functions such as strncasecmp, strpbrk and stripos instead.
  13. When parsing with XML in PHP try xml2array, which makes use of the PHP XML functions, for HTML you can try PHP’s DOM document or DOM XML in PHP4.
  14. str_replace is faster than preg_replace, str_replace is best overall, however strtr is sometimes quicker with larger strings. Using array() inside str_replace is usually quicker than multiple str_replace.
  15. “else if” statements are faster than select statements aka case/switch.
  16. Error suppression with @ is very slow.
  17. To reduce bandwidth usage turn on mod_deflate in Apache v2 or for Apache v1 try mod_gzip.
  18. Close your database connections when you’re done with them.
  19. $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.
  20. Use <?php … ?> tags when declaring PHP as all other styles are depreciated, including short tags.
  21. Use strict code, avoid suppressing errors, notices and warnings thus resulting in cleaner code and less overheads. Consider having error_reporting(E_ALL) always on.
  22. PHP scripts are be served at 2-10 times slower by Apache httpd than a static page. Try to use static pages instead of server side scripts.
  23. PHP scripts (unless cached) are compiled on the fly every time you call them. Install a PHP caching product (such as memcached or eAccelerator or Turck MMCache) to typically increase performance by 25-100% by removing compile times. You can even setup eAccelerator on cPanel using EasyApache3.
  24. An alternative caching technique when you have pages that don’t change too frequently is to cache the HTML output of your PHP pages. Try Smarty or Cache Lite.
  25. Use isset where possible in replace of strlen. (ie: if (strlen($foo) < 5) { echo “Foo is too short”; } vs. if (!isset($foo{5})) { echo “Foo is too short”; } ).
  26. ++$i is faster than $ i++, so use pre-increment where possible.
  27. Make use of the countless predefined functions of PHP, don’t attempt to build your own as the native ones will be far quicker; if you have very time and resource consuming functions, consider writing them as C extensions or modules.
  28. 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.
  29. Document your code.
  30. Learn the difference between good and bad code.
  31. Stick to coding standards, it will make it easier for you to understand other people’s code and other people will be able to understand yours.
  32. Separate code, content and presentation: keep your PHP code separate from your HTML.
  33. Don’t bother using complex template systems such as Smarty, use the one that’s included in PHP already, see ob_get_contents and extract, and simply pull the data from your database.
  34. Never trust variables coming from user land (such as from $_POST) use mysql_real_escape_string when using mysql, and htmlspecialchars when outputting as HTML.
  35. For security reasons never have anything that could expose information about paths, extensions and configuration, such as display_errors or phpinfo() in your webroot.
  36. Turn off register_globals (it’s disabled by default for a reason!). No script at production level should need this enabled as it is a security risk. Fix any scripts that require it on, and fix any scripts that require it off using unregister_globals(). Do this now, as it’s set to be removed in PHP6.
  37. Avoid using plain text when storing and evaluating passwords to avoid exposure, instead use a hash, such as an md5 hash.
  38. Use ip2long() and long2ip() to store IP addresses as integers instead of strings.
  39. You can avoid reinventing the wheel by using the PEAR project, giving you existing code of a high standard.
  40. When using header(’Location: ‘.$url); remember to follow it with a die(); as the script continues to run even though the location has changed or avoid using it all together where possible.
  41. In OOP, if a method can be a static method, declare it static. Speed improvement is by a factor of 4..
  42. Incrementing a local variable in an OOP method is the fastest. Nearly the same as calling a local variable in a function and incrementing a global variable is 2 times slow than a local variable.
  43. Incrementing an object property (eg. $this->prop++) is 3 times slower than a local variable.
  44. Incrementing an undefined local variable is 9-10 times slower than a pre-initialized one.
  45. Just declaring a global variable without using it in a function slows things down (by about the same amount as incrementing a local var). PHP probably does a check to see if the global exists.
  46. Method invocation appears to be independent of the number of methods defined in the class because I added 10 more methods to the test class (before and after the test method) with no change in performance.
  47. Methods in derived classes run faster than ones defined in the base class.
  48. A function call with one parameter and an empty function body takes about the same time as doing 7-8 $localvar++ operations. A similar method call is of course about 15 $localvar++ operations.
  49. Not everything has to be OOP, often it is just overhead, each method and object call consumes a lot of memory.
  50. Never trust user data, escape your strings that you use in SQL queries using mysql_real_escape_string, instead of mysql_escape_string or addslashes. Also note that if magic_quotes_gpc is enabled you should use stripslashes first.
  51. Avoid the PHP mail() function header injection issue.
  52. Unset your database variables (the password at a minimum), you shouldn’t need it after you make the database connection.
  53. RTFM! PHP offers a fantastic manual, possibly one of the best out there, which makes it a very hands on language, providing working examples and talking in plain English. Please USE IT!

Companies Using PHP

Often the question is asked by those who wish to convince a CEO or or some company heavy weight when the question is asked “What large sites are using PHP”. Well here is a list of large comapnies and sites known to using PHP.

Like many enterprises, PHP is not always the sole language in use, and is most often combined for tasks to which is it best suited.

How to Blogging?

Exactly what is a “Blog”? A Blog, shortened from “weblog”, is basically an online journal where you can digitally put down your ideas, thoughts, opinions and practically anything that you want people to read. Blogging is very popular all over the world and basically there are no rules when it comes to blogging. Bloggers have the freedom to express themselves however way they want, and the best thing about blogging, is that most blogging sites are free.

More Experience than all the me-too hosting providers out there. And with over ten years of hosting experience–we’d know!

Blogs can come in all different styles, formats and settings, depending on the users preferences. Many blogging sites, offer built in features such as hyperlinks, pictures, mp3’s, videos, etc. Some bloggers choose to make their blogs more audio friendly, by using spoken word entries. This is called audio blogging. There are also video logs.

Blogging is really for everyone. Overall, it can be lots of fun, very simple and easy to do. Basically, a blog will contain these features at a minimum:


Millions of Books, Journals & Articles

  • archive- list of older articles
  • title- where you label your post
  • body- the content of your post
  • blogroll- other sites can be linked back to your blog
  • comments- this allow readers to post comments on your blog

Unlike other websites that are made up of numerous individual pages, blogs are usually made up of only a few templates making it easier for blog users to create new pages. This can be very helpful for beginners, since they can start blogging right away once they’ve set up their account. One of the appeals of blogging is that it creates a community of people sharing similar ideas, thoughts, and comments with each other.

More Experience than all the me-too hosting providers out there. And with over ten years of hosting experience–we’d know!

The most popular blog type by far is the personal journal. This is the type that is normally used by first time bloggers. Individuals who want to document the daily struggle of their everyday lives, rants, poems, writings, ideas, and opinions find that blogging offers them a medium in which to express themselves.

Blogging is not just limited to personal usage. There are a lot of blogs that follow a theme such as: philosophy, mobile technology, sports, politics, social commentary, web design, pets, etc. These blogs focus on their specific themes. In this way blogging becomes a medium where people can share their knowledge and opinions about a variety of themes and topics.

There are a lot of other things you can do with a blog. Some bloggers use their blogs as a means to advertise and earn money. Some authors advertise their books or products on their blogs while other bloggers use their blogs to shed light on currents issues, news, family issues, personal thoughts and discoveries, events or catastrophes.

More Experience than all the me-too hosting providers out there. And with over ten years of hosting experience–we’d know!

A lot of entrepreneurs benefit from blogging by promoting their products and businesses on their own blogs. With millions and millions of people logging onto the net each and everyday, blogging has become a lucrative move. Some bloggers who run online businesses promote their merchandise online. Others profit through advertisements placed on their blogs.


Free shipping on printing supplies

Blogs can also play an important part in education. Professors can use blogging to document the lessons that they have previously discussed and taught. This is one way students who missed class can easily catch up with their assignments.

Want to learn more about blogging in general or a topic in particular? Blogs varying in topics, themes, and set-ups, and can be found in blog directories. First time users who want to get an idea of what the blogging world is all about can browse through a number of blogs using these kinds of directories. In this way people can get an idea of what these blogging communities, and blogging in general, are all about.

How to connect different database in ASP.Net

ADO Database Connection

Create a DSN-less Database Connection

The easiest way to connect to a database is to use a DSN-less connection. A DSN-less connection can be used against any Microsoft Access database on your web site. If you have a database called “northwind.mdb” located in a web directory like “c:/inetpub/wwwroot”, you can connect to the database with the following ASP code:

<%set conn=Server.CreateObject("ADODB.Connection")conn.Provider="Microsoft.Jet.OLEDB.4.0"conn.Open "c:/inetpub/wwwroot/northwind.mdb"%>

Note, from the example above, that you have to specify the Microsoft Access database driver (Provider) and the physical path to the database on your computer.

Create an ODBC Database Connection

If you have an ODBC database called “northwind” you can connect to the database with the following ASP code:

<%set conn=Server.CreateObject("ADODB.Connection")conn.Open "northwind"%>

With an ODBC connection, you can connect to any database, on any computer in your network, as long as an ODBC connection is available.

An ODBC Connection to an MS Access Database

Here is how to create a connection to a MS Access Database:

  1. Open the ODBC icon in your Control Panel.
  2. Choose the System DSN tab.
  3. Click on Add in the System DSN tab.
  4. Select the Microsoft Access Driver. Click Finish.
  5. In the next screen, click Select to locate the database.
  6. Give the database a Data Source Name (DSN).
  7. Click OK.

Note that this configuration has to be done on the computer where your web site is located. If you are running Personal Web Server (PWS) or Internet Information Server (IIS) on your own computer, the instructions above will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to do this for you.

The ADO Connection Object

The ADO Connection object is used to create an open connection to a data source. Through this connection, you can access and manipulate a database.

ACE OLEDB 12.0 (Access 2007)

Standard security Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:inetpubwwwrootmyAccess2007file.accdb;Persist Security Info=False; With database password This is the connection string to use when you have an Access 2007 database protected with a password using the “Set Database Password” function in Access. Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:inetpubwwwrootmyAccess2007file.accdb; Jet OLEDB:Database Password=MyDbPassword;

DataDirectory functionality
Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=|DataDirectory|myAccess2007file.accdb;
Persist Security Info=False;

ODBC(SQL Server 2000, 7.0)

Standard SecurityDriver={SQL Server};Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;

Trusted connection

Driver={SQL Server};Server=myServerAddress;Database=myDataBase;Trusted_Connection=Yes;

Prompt for username and password

This one is a bit tricky. First you need to set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

oConn.Properties(”Prompt”) = adPromptAlways

Driver={SQL Server};Server=myServerAddress;Database=myDataBase;

OLE DB, OleDbConnection (.NET)

Standard Security
Provider=sqloledb;Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Trusted connection

Provider=sqloledb;Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;

Use serverNameinstanceName as Data Source to use a specific SQL Server instance. Please note that the multiple SQL Server instances feature is available only from SQL Server version 2000 and not in any previous versions.

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Provider=sqloledb;Data Source=myServerNametheInstanceName;Initial Catalog=myDataBase;Integrated Security=SSPI;

Prompt for username and password

This one is a bit tricky. First set the connection object’s Provider property to “sqloledb”. Thereafter set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

oConn.Provider = “sqloledb”
oConn.Properties(”Prompt”) = adPromptAlways

Data Source=myServerAddress;Initial Catalog=myDataBase;

Connect via an IP address

Provider=sqloledb;Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;.

DBMSSOCN=TCP/IP. This is how to use TCP/IP instead of Named Pipes. At the end of the Data Source is the port to use. 1433 is the default port for SQL Server.

Disable connection pooling

This one is usefull when receving errors “sp_setapprole was not invoked correctly.” (7.0) or “General network error. Check your network documentation” (2000) when connecting using an application role enabled connection. Application pooling (or OLE DB resource pooling) is on by default. Disabling it can help on this error.

Provider=sqloledb;Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;OLE DB Services=-2;

<br /> <ilayer src=”http://www.s2d6.com/x/?x=i&z=i&v=2041692&r=[RANDOM]&k=[NETWORKID]” mce_src=”http://www.s2d6.com/x/?x=i&amp;z=i&amp;v=2041692&amp;r=[RANDOM]&amp;k=[NETWORKID]” z-index=”0″ width=”300″ height=”300″><br /> <a href=”http://www.s2d6.com/x/?x=c&z=s&v=2041692&r=[RANDOM]&k=[NETWORKID]” mce_href=”http://www.s2d6.com/x/?x=c&amp;z=s&amp;v=2041692&amp;r=[RANDOM]&amp;k=[NETWORKID]” target=”_blank”><br /> <img src=”http://www.s2d6.com/x/?x=i&z=s&v=2041692&r=[RANDOM]&k=[NETWORKID]” mce_src=”http://www.s2d6.com/x/?x=i&amp;z=s&amp;v=2041692&amp;r=[RANDOM]&amp;k=[NETWORKID]” border=”0″ alt=”click here” /><br /> </a><br /> </ilayer><br />

SqlConnection (.NET)

Standard Security
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Standard Security alternative syntax This connection string produces the same result as the previous one. The reason to include it is to point out that some connection string keywords have many equivalents.

Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;

Trusted Connection

Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;

Trusted Connection alternative syntax

This connection string produce the same result as the previous one. The reason to include it is to point out that some connection string keywords have many equivalents.

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

Use serverNameinstanceName as Data Source to use a specific SQL Server instance. Please note that the multiple SQL Server instances feature is available only from SQL Server version 2000 and not in any previous versions.
<br /> <ilayer src=”http://www.s2d6.com/x/?x=i&z=i&v=2041692&r=[RANDOM]&k=[NETWORKID]” mce_src=”http://www.s2d6.com/x/?x=i&amp;z=i&amp;v=2041692&amp;r=[RANDOM]&amp;k=[NETWORKID]” z-index=”0″ width=”300″ height=”300″><br /> <a href=”http://www.s2d6.com/x/?x=c&z=s&v=2041692&r=[RANDOM]&k=[NETWORKID]” mce_href=”http://www.s2d6.com/x/?x=c&amp;z=s&amp;v=2041692&amp;r=[RANDOM]&amp;k=[NETWORKID]” target=”_blank”><br /> <img src=”http://www.s2d6.com/x/?x=i&z=s&v=2041692&r=[RANDOM]&k=[NETWORKID]” mce_src=”http://www.s2d6.com/x/?x=i&amp;z=s&amp;v=2041692&amp;r=[RANDOM]&amp;k=[NETWORKID]” border=”0″ alt=”click here” /><br /> </a><br /> </ilayer><br />
Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Server=myServerNametheInstanceName;Database=myDataBase;Trusted_Connection=True;

Trusted Connection from a CE device

Often a Windows CE device is not authenticated and logged in to a domain. To use SSPI or trusted connection / authentication from a CE device, use this connection string.

Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomainmyUsername;Password=myPassword;

Connect via an IP address

Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;

DBMSSOCN=TCP/IP. This is how to use TCP/IP instead of Named Pipes. At the end of the Data Source is the port to use. 1433 is the default port for SQL Server.

Specifying packet size

Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;Packet Size=4096;

By default, the Microsoft .NET Framework Data Provider for SQL Server sets the network packet size to 8192 bytes. This might however not be optimal, try to set this value to 4096 instead.

SQLXMLOLEDB.

Using SQL Server Ole Db

The SQLXML version 3.0 restricts the data provider to SQLOLEDB only.

Provider=SQLXMLOLEDB.3.0;Data Provider=SQLOLEDB;Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Data Shape

MS Data Shape

Provider=MSDataShape;Data Provider=SQLOLEDB;Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;

How to connect different database in ASP

SQL Server 2005

This is a compiled connection strings reference list on how to connect to SQL Server 2005.

SQL Native Client ODBC Driver

Standard security

Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase; Uid=myUsername;Pwd=myPassword;

Are you using SQL Server 2005 Express? Don’t miss the server name syntax ServernameSQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2005 Express installation resides.

Trusted Connection

Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase; Trusted_Connection=yes;

Equivalent key-value pair: “Integrated Security=SSPI” equals “Trusted_Connection=yes”

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Driver={SQL Native Client};Server=myServerNametheInstanceName;Database=myDataBase; Trusted_Connection=yes;

Prompt for username and password

This one is a bit tricky. First you need to set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

oConn.Properties(”Prompt”) = adPromptAlways
Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;

Enabling MARS (multiple active result sets)

Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase; Trusted_Connection=yes;MARS_Connection=yes;

Equivalent key-value pair: “MultipleActiveResultSets=true” equals “MARS_Connection=yes”

Use ADO.NET 2.0 for MARS functionality. MARS is not supported in ADO.NET 1.0 nor ADO.NET 1.1.

Encrypt data sent over network

Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase; Trusted_Connection=yes;Encrypt=yes;

Attach a database file on connect to a local SQL Server Express instance

Driver={SQL Native Client};Server=.SQLExpress;AttachDbFilename=c:mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Driver={SQL Native Client};Server=.SQLExpress; AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.




Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

SQL Native Client OLE DB Provider

Standard security

Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Uid=myUsername; Pwd=myPassword;

Are you using SQL Server 2005 Express? Don’t miss the server name syntax ServernameSQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2005 Express installation resides.

Trusted connection

Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes;

Equivalent key-value pair: “Integrated Security=SSPI” equals “Trusted_Connection=yes”

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Provider=SQLNCLI;Server=myServerNametheInstanceName;Database=myDataBase; Trusted_Connection=yes;

Prompt for username and password

This one is a bit tricky. First you need to set the connection object’s Prompt property to adPromptAlways. Then use the connection string to connect to the database.

oConn.Properties(”Prompt”) = adPromptAlways

oConn.Open “Provider=SQLNCLI;Server=myServerAddress;DataBase=myDataBase;

Enabling MARS (multiple active result sets)

Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase; Trusted_Connection=yes;MarsConn=yes;

Equivalent key-value pair: “MultipleActiveResultSets=true” equals “MARS_Connection=yes”

Use ADO.NET 2.0 for MARS functionality. MARS is not supported in ADO.NET 1.0 nor ADO.NET 1.1.

Encrypt data sent over network

Provider=SQLNCLI;Server=myServerAddress;Database=myDataBase; Trusted_Connection=yes;Encrypt=yes;

Attach a database file on connect to a local SQL Server Express instance

Provider=SQLNCLI;Server=.SQLExpress;AttachDbFilename=c:mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Provider=SQLNCLI;Server=.SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.




Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

SqlConnection (.NET)

Standard Security

Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

Use serverNameinstanceName as Data Source to connect to a specific SQL Server instance.

Are you using SQL Server 2005 Express? Don’t miss the server name syntax ServernameSQLEXPRESS where you substitute Servername with the name of the computer where the SQL Server 2005 Express installation resides.

Standard Security alternative syntax

This connection string produce the same result as the previous one. The reason to include it is to point out that some connection string keywords have many equivalents.

Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;

Trusted Connection

Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;

Trusted Connection alternative syntax

This connection string produce the same result as the previous one. The reason to include it is to point out that some connection string keywords have many equivalents.

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;

Connecting to an SQL Server instance

The syntax of specifying the server instance in the value of the server key is the same for all connection strings for SQL Server.

Server=myServerNametheInstanceName;Database=myDataBase;Trusted_Connection=True;

Trusted Connection from a CE device

Often a Windows CE device is not authenticated and logged in to a domain. To use SSPI or trusted connection / authentication from a CE device, use this connection string.

Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;User ID=myDomainmyUsername;Password=myPassword;

Connect via an IP address

Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;

DBMSSOCN=TCP/IP. This is how to use TCP/IP instead of Named Pipes. At the end of the Data Source is the port to use. 1433 is the default port for SQL Server.

Enabling MARS (multiple active result sets)

Server=myServerAddress;Database=myDataBase;Trusted_Connection=True; MultipleActiveResultSets=true;

Use ADO.NET 2.0 for MARS functionality. MARS is not supported in ADO.NET 1.0 nor ADO.NET 1.1.




Attach a database file on connect to a local SQL Server Express instance

Server=.SQLExpress;AttachDbFilename=c:mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Attach a database file, located in the data directory, on connect to a local SQL Server Express instance

Server=.SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf; Database=dbname;Trusted_Connection=Yes;

Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.

Using an User Instance on a local SQL Server Express instance

The User Instance functionality creates a new SQL Server instance on the fly during connect. This works only on a local SQL Server 2005 instance and only when connecting using windows authentication over local named pipes. The purpose is to be able to create a full rights SQL Server instance to a user with limited administrative rights on the computer.

Data Source=.SQLExpress;Integrated Security=true; AttachDbFilename=|DataDirectory|mydb.mdf;User Instance=true;

To use the User Instance functionality you need to enable it on the SQL Server. This is done by executing the following command: sp_configure ‘user instances enabled’, ‘1′. To disable the functionality execute sp_configure ‘user instances enabled’, ‘0′.

Database mirroring

If you connect with ADO.NET or the SQL Native Client to a database that is being mirrored, your application can take advantage of the drivers ability to automatically redirect connections when a database mirroring failover occurs. You must specify the initial principal server and database in the connection string and the failover partner server.

Data Source=myServerAddress;Failover Partner=myMirrorServer;Initial Catalog=myDataBase;Integrated Security=True;

There is ofcourse many other ways to write the connection string using database mirroring, this is just one example pointing out the failover functionality. You can combine this with the other connection strings options available.

Asynchronous processing

A connection to SQL Server 2005 that allows for the issuing of async requests through ADO.NET objects.

Server=myServerAddress;Database=myDataBase;Integrated Security=True;Asynchronous Processing=True;

SQLXMLOLEDB

Using SQL Server Native Client provider

Provider=SQLXMLOLEDB.4.0;Data Provider=SQLNCLI;Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;

SQL Server 2005 specials

Context Connection

Connecting to “self” from within your CLR stored prodedure/function. The context connection lets you execute Transact-SQL statements in the same context (connection) that your code was invoked in the first place.

C#
using(SqlConnection connection = new SqlConnection(”context connection=true”))
{
connection.Open();
// Use the connection
}

VB.Net
Using connection as new SqlConnection(”context connection=true”)
connection.Open()
‘ Use the connection
End Using

Dfference between web 1.0 and web 2.0

Dfference between web 1.0 and web 2.0

“Web” is a fancy catch-all phrase for the Hypertext Transfer Protocol (HTTP, the protocol used for transferring information between a Web server and Web browser) and the Hypertext Markup Language (HTML, the markup language that tells your browser how to display whatever text, graphics, etc is coming through the HTTP). Over at the World Wide Web Consortium (W3C), there actually are versions of these protocols. HTTP for example is still on version 1.1 and has been since 1999. The most recent of HTML (version 4.01) is just as old. There is something over at the W3C in draft mode called XHTML which is now at version 2.0 and has relevance to the future Web. But a one-to-one mapping of it directly to Web 2.0, especially when you consider how many things have been dropped into the Web 2.0 bucket that don’t use XHTML, doesn’t work either.




If you looked at all the Web applications and sites that have been dropped into that Web 2.0 bucket, one of the more common ingredients would probably be use of the AJAX (Asynchronous Javascript and XML) programming technique — a technique that generally speaking adds an element of real-time interactivity to Web pages that might otherwise be very static. Google’s Gmail e-mail service, for example, uses AJAX to keep your view of the inbox updated as new mail arrives with out having to refresh the entire Web page. I’m fairly certain that AJAX is also the enabler of Gmail’s autosave feature (that automatically saves drafts to Gmail’s servers for you as you are writing your emails). But three problems that are common to many if not all AJAX-based pages is how they often interfere with the functionality of a Web browser’s back button (in most cases, it either doesn’t work, or it takes you back to a page that you don’t want to be taken back to). Another is that the forward button (when advancing to a page with AJAX code on it) yields unpredictable results as well. And finally, the same goes for bookmarking AJAX-driven pages.

So, when people ask me what Web 2.0 is, a lot of times, I say “It’s when the back button doesn’t work! (something that usually works with Web 1.0… but not always). The other thing I say is that I don’t think there’s a trade or servicemark on “Web 1.0.” That’s a big difference too.

How to get IP address in different programming language?

Get IP address
By ASP <%= Request.ServerVariables(”REMOTE_ADDR”) %>
By PHP <?php echo $ip=$_SERVER['REMOTE_ADDR']; ?>

By JAVA
import java.net.*;
import java.io.*;
import java.applet.*;

public class GetClientIP extends Applet {
public void init() {
try {
InetAddress thisIp =
InetAddress.getLocalHost();
System.out.println(”IP:”+thisIp.getHostAddress());
}
catch(Exception e) {
e.printStackTrace();
}
}
}

//HTML Page
<HTML><HEAD></HEAD><BODY>
<APPLET CODE=”GetClientIP.class”
HEIGHT=10 WIDTH=10>
</APPLET>
Check JAVA console for output
</BODY></HTML>

BY Coldfusion

<cfoutput>#CGI.REMOTE_ADDR#</cfoutput>

BY CGI
import cgi
import os

print “Content-type: text/html”
print “”

print cgi.escape(os.environ["REMOTE_ADDR"])

What is PageRank?

What is PageRank?

PageRank is the algorithm used by the Google search engine, originally formulated by Sergey Brin and Larry Page in their paper The Anatomy of a Large-Scale Hypertextual Web Search Engine.

It is based on the premise, prevalent in the world of academia, that the importance of a research paper can be judged by the number of citations the paper has from other research papers. Brin and Page have simply transferred this premise to its web equivalent: the importance of a web page can be judged by the number of hyperlinks pointing to it from other web pages

So what is the algorithm?

It may look daunting to non-mathematicians, but the PageRank algorithm is in fact elegantly simple and is calculated as follows:

  • PR(A) = (1-d) + d (PR(T1)/C(T1) + … + PR(Tn)/C(Tn))

where PR(A) is the PageRank of a page A

PR(T1) is the PageRank of a page T1

C(T1) is the number of outgoing links from the page T1

d is a damping factor in the range 0 < d < 1, usually set to 0.85

The PageRank of a web page is therefore calculated as a sum of the PageRanks of all pages linking to it (its incoming links), divided by the number of links on each of those pages (its outgoing links).

And what does this mean?

From a search engine marketer’s point of view, this means there are two ways in which PageRank can affect the position of your page on Google:

  • The number of incoming links. Obviously the more of these the better. But there is another thing the algorithm tells us: no incoming link can have a negative effect on the PageRank of the page it points at. At worst it can simply have no effect at all.
  • The number of outgoing links on the page which points at your page. The fewer of these the better. This is interesting: it means given two pages of equal PageRank linking to you, one with 5 outgoing links and the other with 10, you will get twice the increase in PageRank from the page with only 5 outgoing links.

At this point we take a step back and ask ourselves just how important PageRank is to the position of your page in the Google search results.




The next thing we can observe about the PageRank algorithm is that it has nothing whatsoever to do with relevance to the search terms queried. It is simply one single (admittedly important) part of the entire Google relevance ranking algorithm.

Perhaps a good way to look at PageRank is as a multiplying factor, applied to the Google search results after all its other computations have been completed. The Google algorithm first calculates the relevance of pages in its index to the search terms, and then multiplies this relevance by the PageRank to produce a final list. The higher your PageRank therefore the higher up the results you will be, but there are still many other factors related to the positioning of words on the page which must be considered first

So what’s the use of the PageRank Calculator - if no incoming link has a negative effect, surely We should just get as many as possible, regardless of the number of outgoing links on its page?

Well, not entirely. The PageRank algorithm is very cleverly balanced. Just like the conservation of energy in physics with every reaction, PageRank is also conserved with every calculation. For instance, if a page with a starting PageRank of 4 has two outgoing links on it, we know that the amount of PageRank it passes on is divided equally between all of its outgoing links. In this case 4 / 2 = 2 units of PageRank is passed on to each of 2 separate pages, and 2 + 2 = 4 - so the total PageRank is preserved!

Note: There are scenarios where you may find that total PageRank is not conserved after a calculation. PageRank itself is supposed to represent a probability distribution, with the individual PageRank of a page representing the likelihood of a ‘random surfer’ chancing upon it.

On a much larger scale, supposing Google’s index contains a billion pages, each with a PageRank of 1, the total PageRank across all pages is equal to a billion. Moreover, each time we recalculate PageRank, no matter what changes in PageRank may occur between individual pages, the total PageRank across all one billion pages will still add up to a billion.

Firstly, this means that although we may not be able to change the total PageRank across all pages, by strategic linking of pages within our site, we can affect the distribution of PageRank between pages. For instance, we may want most of our visitors to come into the site through our home page. We would therefore want our home page to have a higher PageRank relative to other pages within the site. We should also recall that all of the PageRank of a page is passed on and divided equally between each of the outgoing links on a page. We would therefore want to keep as much combined PageRank as possible within our own site without passing it on to external sites and losing its benefit. This means we would want any page with lots of external links (ie. links to other people’s web sites) to have a lower PageRank relative to other pages within the site to minimise the amount of PageRank which is ‘leaked’ to external sites. Bear in mind also our earlier statement, that PageRank is simply a multiplying factor applied once Google’s other calculations regarding relevance have already been calculated. We would therefore want our more keyword-rich pages to also have a higher relative PageRank.




Secondly, if we assume that every new page in Google’s index begins its life with a PageRank of 1, there is a way we can increase the combined PageRank of pages within our site - by increasing the number of pages! A site with 10 pages will start life with a combined PageRank of 10 which is then redistributed through its hyperlinks. A site with 12 pages will therefore start with a combined PageRank of 12. We can thus improve the PageRank of our site as a whole by creating new content (ie. more pages) and then control the distribution of that combined PageRank through strategic interlinking between the pages.

And this is the purpose of the PageRank Calculator - to create a model of the site on a small scale including the links between pages, and see what effect the model has on the distribution of PageRank.

How does the PageRank Calculator work?

It’s very simple really. Start by typing in the number of interlinking pages you wish to analyse and hit ‘Submit’. I have confined this number to just twenty pages to ease server resources. Even so, this should give a reasonable indication of how strategic linking can affect the PageRank distribution.

Next, for ease of reference once the calculation has been performed, provide a label for each page (eg. ‘Home Page’, ‘Links Page’, ‘Contact Us Page’, etc) and again hit ‘Submit’.

Finally, use the list boxes to select which pages each page links to. You can use CTRL and SHIFT to highlight multiple selections.

You can also use this screen to change the initial PageRanks of each page. For instance, if one of your pages is supposed to represent Yahoo, you may wish to raise its initial PageRank to, say, 3. However, in actual fact, starting PageRank is irrelevant to its final computed value. In other words, even if one page were to start with a PageRank of 100, after many iterations of the equation (see below), the final computed PageRank will converge to the same value as it would had it started with a PageRank of only 1!

Finally you can play around with the damping factor d, which defaults to 0.85 as this is the value quoted in Brin and Page’s research paper.

Why are there 20 lines of results?

Ever heard of the Google ‘Dance’? You can see this demonstrated by looking at the differing results sets produced on www.google.com, www2.google.com and www3.google.com. If you study these results closely you will see that they change very slightly from day to day, and in particular during the period once a month when Google updates its index.

One of the reasons for this apparent dancing of results is because Google does not simply calculate the PageRank once for each page. After it has calculated the PageRank for the first time it will then put the resulting PageRanks back into the PageRank algorithm and calculate again. Google will go through this process of iteration many times before the results settle down to their ‘true’ values. When it has been completed, the results will then appear on the ‘official’ www.google.com domain.

The PageRank Calculator defaults to 20 iterations, although you can increase this number should you choose. For a model of around 20 pages, 20 iterations is sufficient to see the PageRanks honing in on a single ‘true’ value. Google almost certainly performs many more.