system administration
   search engine optimization

   perl & mysql
   php & mysql
   mysql optimization

Contact us

T Scripts home

PHP & MySQL help. Here we will give some help on some common issues with regard to MySQL database access from within your PHP scripts.

Requirements: Apache, PHP (4 or 5), MySQL.

Simple script that illustrates how to connect to a MySQL database and issues a range of select, delete and update queries:

If you need database access from a number of scripts, it might be usefull to use include files for easier change of database parameters later on. This way you only need to change 1 file in case a username or database name changes.
In each script that requires database access you can put this:


  require_once '';

  $connection = mysql_pconnect(HOSTNAME,USERNAME,PASSWORD);

This connects to the database server and selects the correct database. Notice here that we use mysql_pconnect or persistent connections. This leaves a connection open for some time after the script finishes so that the webserver can re-use a database connection. This can increase performance on busy webservers.
The contents of the include file is this:


We define these as constants, to prevent us from accidentaly overwriting one of these values.
Always make sure you either put the include file outside of the web accessible directories, or deny access to it, otherwise this file could be downloaded and your database security compromised.

We will now show how to query the database with some simple queries:

  $result = mysql_query("SELECT fielda, fieldb FROM table", $connection);
  $fielddata = @ mysql_fetch_array($result);

  print "fielda is {$fielddata['fielda']} \n";
  print "fieldb is {$fielddata['fieldb']} \n";

To select a single field, use this:

  $result = mysql_query("SELECT field FROM table WHERE key=1", $connection);
  $myfield = mysql_result($result,0);


If you would like more information, feel free to contact us.