PHP and MySQL Connectivity

We know that there are lots of tutorials (some official too) on the internet about PHP and MySQL connectivity. Then why am i posting it here ? i am posting because most of those articles are not simple and easy to understand and this is why we are doing it here. We assume that you have already installed XAMPP in your System and running it using XAMPP control panel.

To connect PHP to MySQL database you need to know following important things:

  1. Host name.
  2. MySQL user name.
  3. MySQL password.

If you have installed XAMPP in your system (not web server) then host name is localhost. By default MySQL user name and password is “root” and blank ( “” ) respectively. Let us create one simple project and try to connect our PHP code to MySQL.

If you are on Windows then there is “htdocs” folder in “C:/xampp/htdocs/” (if installed on default location). If you are on Linux (most probably Ubuntu) then it is located on “/opt/lampp/htdocs” (you should switch to root user before creating folder in it.).

In any case create any folder, lets say “test-db-connection” and create simple PHP file with following code.

if(!$con) {
  echo '

Connected to MySQL

} else {
   echo '

MySQL Server is not connected


Save it in the project folder and go to localhost/test-db-connection/filename.php and see what it is giving.

mysql_connect() is PHP inbuilt function to connect to MySQL database with the parameter shown above.

To perform SQL queries, you need to select database. You can do that using mysql_select_db(“database_name”,optional connection variable). Once Database is selected you can perform queries using mysql_query(“SQL query”). Here is sample code.

if(!$con) {
  echo '

Connected to MySQL

  //if connected then Select Database.
else {
  echo '

MySQL Server is not connected


I hope you have understood the concept. You can ask any doubt in comment.

49 thoughts on “PHP and MySQL Connectivity”

      1. hi Shahid,

        need help,

        i have put my application onto PCF(Pivotal cloud Foundry)
        i am unable to connect to mysql database,
        the application logic is written in PHP language

        my config file looks like below.

        define(‘mysql_db_hostname’,’’); —>ex: ip

        the socket is open and the php pages appears but unable to connect to db, please help me with what changes should i make to connect to mysql db


    1. $conn = mysql_connect(“localhost”,”primeb5_mysql”,”***”);
      $db = mysql_select_db(“primeb5_unigis”);
      $query = “SELECT * FROM lesson3”;
      $result = mysql_query($query);

      The function “mysql_query” is responsible for executing the query within the brackets on the database. But how does this function know which database to use? $conn and $db have been defined, but they are never used within the code.

  1. Bro I think you need to use mysqli not mysql because latest version not support mysql .

  2. Thanks for the write up. Can point me to an example where you put this concept into practice?

    1. Yes. Let’s say you are building Registration form where user will submit and their information will be store in Database , in that kind of scenario you need to connect to your database ( assuming MySQL here) in order to do further database operations.

  3. when i took ur code in my project. basic one of just checking whether its connected or not… it kept loading for a long time.. n didnt provide any result.

  4. Nicolai Czempin

    Your logic is reversed. If !$con that means your connection attempt failed.

    So either write
    if ($con) {
    instead of
    if (!$con) {

    or just handle the failure first, throw an exception and then continue assuming success, like it is done in the official documentation examples here:

    In this particular case, it doesn’t make any difference whatsoever whether you use mysql_connect or mysqli_connect. The former is deprecated and will be removed at some point in the future, but as of PHP 5.5 it still works.

  5. Fatal error: Call to undefined function mysql_connect() in C:\xampp2\htdocs\test\index.php on line 5

    what does it mean?

  6. I took ur code in my project and I got
    “Warning: mysql_select_db() expects parameter 1 to be mysqli, string given in C:\xampp2\htdocs\BDPortal\admindbconf.php on line 15”

    Can you help me with this?


  7. I got same response as tin above from the code given.
    Please help because I have tried several codes and none is working.

  8. $query=mysql_query(“YOUR_MYSQL_QUERY”,$db);

    Above method has error, since the second parameter has to be a connection object not db.

    Please correct.

  9. i have try your code but not connected to the database. its just showing localhost refuse to connect.

  10. I did try this procedure on my XAMPP but it not working .
    if anyone could help me please .
    i got this error in my browser.
    Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\conn.php:5 Stack trace: #0 {main} thrown in C:\xampp\htdocs\conn.php on line 5

  11. $host=”localhost”;
    if(!$con) {
    echo ‘Connected to MySQL’;
    } else {
    echo ‘MySQL Server is not connected’;

    } anable to connect

  12. I’m very new to PHP, but not programming. The following code from the example would seem to read that if it is NOT connected then echo ‘Connected to MySQL’. Maybe it’s different in PHP, but in other languages the ! sign means NOT. (I’m not shouting with capital letters just trying to be clear)

    if(!$con) {
    echo ‘Connected to MySQL’;
    } else {
    echo ‘MySQL Server is not connected’;

    Whatever the case, my code seems to echo “Connected to MySQL” even with a made up username. This is surely a reflection of my inexperience with PHP, but just curious how the ! operator works.

    1. Shahid (UnixRoot) Shaikh

      ! performs the comparison with a boolean value, if it is false then ! FALSE = true i.e good case to go in if condition.

  13. Can you please tell me how to create login form and how to check its backend in XAMPP?

  14. m getting els part msg dt sql server is not connected…..i hv checked the code bt not able to catch the problem…plz help me….:)

  15. Hi,
    I am not able to select database only
    I just wasted more than 15 hours everytime it says connection problem
    $con is my connection string
    mysql_select_db(“test”,$con) or die(“connection problem”);

    Output is connection problem

  16. how to run in xampp server
    i was created a database with name my_db and it was saved in xampp ht docs folder.
    how can i run it.

  17. what is the need of blank space in the code

    mysql_connect(“localhost”,”root”,” “);

  18. hi when i run by xampp the filename.php i have this output:
    $host=”localhost”; $user=”root”; $password=””; $con=mysql_connect($host,$user,$password); if(!$con) { echo ‘
    Connected to MySQL

    ‘; } else { echo ‘
    MySQL Server is not connected

    ‘; }

    BUT when i run the second code replacing the name of my database and query i have error:
    Object not found!

    The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

    If you think this is a server error, please contact the webmaster.

    Error 404

    Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.6.28

    How can it be solve? I’m new and i need to understnd it

  19. No people, y’all need to be using PHP’s PDO connector.
    mysql and mysqli connectors are gonna deprecate soon.

  20. Adegbite Victor

    I go this error on connecting to a database.

    Fatal error: Uncaught Error: Call to undefined function mysql_select_db() in C:\xampp\htdocs\download\upload.php:50 Stack trace: #0 {main} thrown in C:\xampp\htdocs\download\upload.php on line 50
    Below is the entire code.Please show me what is wrong:

    #wrapper {
    margin: 0 auto;
    float: none;
    .header {
    padding:10px 0;
    border-bottom:1px solid #CCC;
    .title {
    padding: 0 5px 0 0;
    .container form input {
    height: 30px;


    Upload File

    $con = mysql_connect("localhost","root","");
    if (!$con)
    echo('Could not connect: ' . mysql_error());
    if (file_exists("download/" . $_FILES["file"]["name"]))
    echo 'alert(” Sorry!! Filename Already Exists…”)’;
    “download/” . $_FILES[“file”][“name”]) ;
    mysql_select_db(“test2”, $con);
    $sql = “INSERT INTO presentation(subject,topic,file) VALUES (‘” . $_POST[“sub”] .”‘,'” . $_POST[“pre”] . “‘,'” .
    $_FILES[“file”][“name”] .”‘);”;
    if (!mysql_query($sql,$con))
    echo(‘Error : ‘ . mysql_error());
    echo ‘alert(“Thank You!! File Uploded”)’;





  21. hello sir i have my project along with its php files with me i am confused how to link them with the database.please give me an idea about this

Comments are closed.