Connect to Mysql Database

Connecting to the mysql database is done in two steps:
  1. Connecting to a mysql server, it's the most of time installed in the same server where php is, so we uselocalhost as address of mysql server.

    mysql_connect("localhost", "username", "password") or die(mysql_error());
    echo "Connected to MySQL Server";

    Some times, when you are running a server in your own computer and not a hosting service provider's, you can connect with just indicating username "root" with no password, and some times is no need to enter an username. It's all depend on your current mysql configuration.

  2. After you are connected to a mysql server, you need then to connect to a mysql database:

    mysql_select_db("database-name") or die(mysql_error());
    echo "Connected to Mysql Database";

So now you are completely connected to your database, and you can read/send data from/to it. But if a problem occurs, the "or die(mysql_error());" help you to find the error and hundle it.

1 comments:

John Mueller said...

Hi, how do you explain that sometimes Mysql disconnects just by itself in a PHP script and I have to reconnect ??