|
|
Script to access MySQL database using PHP
June 22, 2008 – 8:51 amPHP and MySQL are most popular combination in creating web application. PHP and MySQL gets integrated easily in any platforms. Scripts developed in PHP using Window platform works perfectly in when used in Linux environment. Below example shows how to connect between PHP and MySQL database.
<?php
// Connecting to database
$link = mysql_connect('mysqlHost', 'mysqlUser', 'mysqlPassword')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
// Selecting to database
mysql_select_db('myDatabase') or die('Could not select database');
// Performing SQL query
$query = 'SELECT * FROM myTable';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
echo "<table width='400'>\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
echo "\t\t<td>$line['colname1']</td><td>$line['colname1']</td>\n";
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
The above example shows to display the contents of the MySQL table. Here mysql_connect function is used to connect to the mysql using servername, username and userpassword parameters and returns the link identifier to that MySQL server. mysql_select_db function selects the database to run theĀ queries and finally mysql_query runs the query and stores the result set in the $result variable.
Now using mysql_fetch_array or other functions we can make the operations on the resultant datas.

