Приглашаем посетить
Романтизм (19v-euro-lit.niv.ru)

Connecting to MySQL

Previous
Table of Contents
Next

Connecting to MySQL

@mysql_connect('localhost', 'user', 'password')


Two MySQL extensions for PHP are available. The older one, ext/mysql, was used for PHP 4 and older versions; the newer one, ext/mysqli (the i officially stands for improved, and unofficially for incompatiblebut that's cynical), comes with PHP 5 but requires MySQL 4.1 or higher. However, PHP 5 also supports the old extension. Both extensions are covered in this chapter.

Connecting to MySQL (mysql_connect.php)
<?php
  if ($db = @mysql_connect('localhost', 'user',
    'password')) {
    mysql_select_db('phrasebook', $db);
    echo 'Connected to the database.';
    mysql_close($db);
  } else {
    echo 'Connection failed.';
  }
?>

To use the extensions, you might have to enable them. Under PHP 4, ext/mysql is automatically activated. Under PHP 5, you have to use extension=php_mysql.dll and also have to copy libmysql.dll to where PHP can find it. If you compile PHP yourself, use the switch with-mysql=/path/to/mysql for older MySQL versions and ext/mysql.

Now connecting to the database is easy: Just call mysql_connect(), providing the server, username, and password. You then get a handle that can be used for mysql_select_db() or to choose a database on the server. Finally, mysql_close() closes the connection to the data source.


Previous
Table of Contents
Next