Databases

From Lankyland

Jump to: navigation, search

There are multiple types of Databases and ways to connect to them. Here are a few examples. I mostly use PHP as that is my favourite web based language to use.

If I come across some code snippets in any other languages I'll include them here.

Contents

Connecting to Databases

MySQL

Using PHP to connect to a MySQL Server

 <?
 $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
 if (!$link) {
     die('Could not connect: ' . mysql_error()); 
 }
 echo 'Connected successfully';
 mysql_close($link);
 ?>

Once you have connected to the MySQL server you then need to specify the database to use

 <?
 
 $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
 if (!$link) {
     die('Not connected : ' . mysql_error());
 }
 
 // make foo the current db
 $db_selected = mysql_select_db('foo', $link);
 if (!$db_selected) {
     die ('Can\'t use foo : ' . mysql_error());
 }
 ?>

MS SQL

Using PHP to connect to an MS SQL Server.

 <?
 // Server in the this format: <computer>\<instance name> or 
 // <server>,<port> when using a non default port number
 $server = 'KALLESPC\SQLEXPRESS';
 
 $link = mssql_connect($server, 'sa', 'phpfi');
 
 if(!$link)
 {
     die('Something went wrong while connecting to MSSQL');
 }
 ?>

Once you have connected to the MS SQL Server you will need to select a Database to use.

 <?
 // Create a link to MSSQL
 $link = mssql_connect('KALLESPC\SQLEXPRESS', 'sa', 'phpfi');
 
 // Select the database 'php'
 mssql_select_db('php', $link);
 ?>

Working with Databases

Both MySQL, MS SQL and other *SQL servers all run on a basic language that is similar across all the platforms. The SQL stands for Structured Query Language.

  • The MySQL page has examples of the most commonly used MySQL statements from the code that I have developed.
  • The MSSQL page has examples of the most commonly used MSSQL statements from work, etc.
Personal tools
Donate
Donate towards my web hosting bill!