Saturday, August 11, 2012

PHP - Database connectivity

Below are the 6 steps used for PHP database connectivity.

Step 1. Create a connection to the database using mysql_connect() function, which returns a connection object.

Syntax : $con = mysql_connect("localhost","root","password");

Step 2. Select database or schema using mysql_select_db() function

Syntax : mysql_select_db("database_name", $con);

Step 3. Execute the query using mysql_query() function. This function is used to send a query or command to a MySQL connection. It returns result object

Syntax : $result = mysql_query($sql);

Step 4. Looping through results. mysql_fetch_array() function is used to fetch a result row as an associative array, a numeric array, or both.

Syntax : $row = mysql_fetch_array($result)

Step 5. Printing the results. Simply printing the values from result array.

Syntax : echo $row['column1']." ".$row['column2'];

Step 6. Closing the connecting using mysql_close() function.

Syntax : mysql_close($con);

Please see the complete tested code, Save the page with .(dot) php extension e.g. ConnectDatabase.php. Provide correct credentials and see the output.

  <title> PHP - database connectivity </title>

//Connect to database
$con = mysql_connect("localhost","root","password");
if (!$con)
die('Could not connect: '.mysql_error());

//Provide schema
mysql_select_db("BookStore", $con);

//SQL Query
$sql = "select * from employee";

//Fetch result
$result = mysql_query($sql);

//Looping through results, (if any)
while($row = mysql_fetch_array($result))
echo $row['emp_id']." ".$row['emp_name'];
echo "<br/>";

//Close the connection