PHP & MySQL

products:
   TGS
   TTS
   TSE
   TES
   TPS
   TCS
   TSELA
   Nitro

services:
   programming
   system administration
   security
   search engine optimization

tutorials:
   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:

<?php

  require_once 'database.inc';

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

?>
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 database.inc include file is this:
<?php

  define('HOSTNAME','localhost');
  define('DATABASE','myDatabase');
  define('USERNAME','myUser');
  define('PASSWORD','myPassword');

?>
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:
<?php

  $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:
<?php

  $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.