PHP MySql Connect to a database

PHP MySQL Connect to database  tutorial will explain you How to create a connection with MySQL? with Examples.

Creating Connection to a mysql database

When you can get content out of your MySQL database, you should know how to create an connection with MySQL from inside a PHP script. To perform basic queries from within MySQL. The first thing to do is connect to the database. The function to connect to MySQL is called MySQL_connect.

Syntax for PHP MySql Connect:

$link = mysql_connect ($hostname, $username, $password, $newlink);

A call to MySQL_connect returns a link identifier on success or FALSE on failure.

  • $hostname = The domain name of the mysql server. If both the web server and mysql are located on the same machine/computer, you can simply use “localhost”. Default value is “localhost:3306”.
  • $username = Login ID/username of the mysql server
  • $password = Password for the mysql server

Example of mysql_connect:

All going well, you should see “Connected to MySQL” when you run this script. If you can’t connect to the server, make sure your password, username and database are correct.

Closing database Connection

Closing a connection to a database is quite easy. The connection will be closed automatically when the script ends.

If you’ve used a file handle, as above, you just do this:
mysql_close ($db_handle);

Code for closing the connection:

Previous articlePHP MySql Introduction
Next articlePHP MySql Create database and tables
I am a young Information Systems Security Engineer(CEH). I had started with penetration testing when i am 17 years old. It all started with Kali linux and Metasploit.In free time i will play with Security holes/Bug bounty/Pentesting and Hacking !!!
  • wasib

    hi i’m working with my php project on the topic online classifieds .
    i created some pages and created mysql database using xampp .
    and its connecting and working too. but
    i don’t know how to create a secure page for the user after signing in .
    i’m stuck here . so will you plz reply or mail me :
    i need some php codes of secure page to display the ads for the user.