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.
Step 2. Select database or schema using mysql_select_db() function
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
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.
Step 5. Printing the results. Simply printing the values from result array.
Step 6. Closing the connecting using mysql_close() function.
Please see the complete tested code, Save the page with .(dot) php extension e.g. ConnectDatabase.php. Provide correct credentials and see the output.
<html>
<head>
<title> PHP - database connectivity </title>
</head>
<body>
<?php
//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
mysql_close($con);
?>
</body>
</html>