Use PHP to connect to MySQL Print

  • php, mysql
  • 83

Php offers multiples ways to connect to a local or remote MySQL database, each requiring a bit of coding knowledge.

PHP's MySQL functions

<?php mysql_connect('localhost','username','password'); mysql_select_db("dbname"); ?>

Where 'localhost' would be your own server (if not remote, case in which you would have to enter the domain or IP). 'username' and 'password' would be for the database that you are connecting to, that is named 'dbname'.

PHP's MySQLi

The mysqli class is an improved method of connection, that is set to be a replacement of the regular functions.

<?php $mysqli = new mysqli("localhost", "username", "password", "dbname"); ?>

PHP's MySQL PDO Classes

Another way to connect to MySQL us by using MySQL's PHP Data Objects (PDO).

<?php $myPDO = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password'); ?>


And don't forget, for remote connections the port is 3306.


Was this answer helpful?

« Back