Thursday, March 15, 2012

Connect to a mysql database using php

In almost all web projects now a days you need to use at least one database to store information. So let's start using a database! First step is to connect to the database.
For this example let's imagine that a i have mysql running on the adress "localhost" with the username "root" and password "password". The database name is "mydatabase".

With this information we can start coding our php script to connect with the database.

I hope it has been helpful, in the next tutorial let's see how to insert data on your  mysql database using php.

//Try to connect to database
$con = mysql_connect('localhost','root','password'); 
if (!$con) //Test if connection was successfully
    echo ('Error on connect: ' . mysql_errno() . ": " 
    . mysql_error());
    //Connect to the table inside the database
    $db_check = mysql_select_db('mydatabase', $con); 
    if (!$db_check)
        echo ('Error on the database : ' . mysql_errno() 
        . ": " . mysql_error());

Next tutorial:  "Insert one or multiple rows in mysql db using php".

1 comment: