RSS

How To Connect To a MySQL Database

Sat, Nov 1, 2008

PHP

Connecting to a MySQL database in PHP is very simple. People seem to be under the impression its very complicated.

To connect to a database firstly we need to connect to MySQL using this function: mysql_connect ( )

Here is the syntax for this:

mysql_connect('localhost', 'mysql_user', 'mysql_password')

A slightly more advanced way of doing this is using this. It makes connecting to the database a bit more smooth and should put less strain on the server.


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

Now we have established a connection to MySQL we need to select a database to connect to. We do this using the mysql_select_db ( ) function.

Here is the syntax for selecting the database ($link is the MySQL connection data):

mysql_select_db('database', $link);

So its as simple as that. Here is the full code for connecting to the database:

<?php

$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());
}
?>

Rating: 10.0/10 (5 votes cast)
Share and Enjoy:
  • Digg
  • Google
  • Technorati
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Furl
  • Live
  • Reddit
  • Spurl

  • Subscribe
    • XML
    • Google Reader or Homepage
    • Add to My Yahoo!
    • Subscribe with Bloglines
    • Subscribe in NewsGator Online
    • BittyBrowser
    • Add to My AOL
    • Convert RSS to PDF
    • Subscribe in Rojo
    • Subscribe in FeedLounge
    • Subscribe with Pluck RSS reader
    • Solosub
    • MultiRSS
    • R|Mail
    • Rss fwd
    • Blogarithm
    • Eskobo
    • gritwire
    • BotABlog
    • Simpify!
    • Add to Technorati Favorites!
    • Add to netvibes
    • Add this site to your Protopage
    • Subscribe in NewsAlloy
    • Subscribe in myEarthlink
    • Add to your phone
    • Get RSS Buttons

, , , , , , ,



This post was written by:

admin - who has written 41 posts on Unreal Media.


Contact the author

Leave a Reply