Skip to main content

Simple Connection to MySQL with PHP


The MySQL database is one of the most popular among PHP developers. It's my database of choice, and has held up remarkably well in multiple e-commerce situations. Therefore, you would be correct in assuming that there are numerous well-documented PHP functions you can use in conjunction with your MySQL databases.

Here is a an example:

Before you begin, you must know the name of the server on which the database resides, and have a valid username and password for that server. Then, start your PHP code by creating a connection variable: 
<?
    $connection
= mysql_connect("servername","username","password");
Test that a connection was established and if it wasn't, print an error message and exit the program: 
    if (!$connection) {
        echo "Couldn't make a connection!";
        exit;
    }

If you have made it through the connection test, the next steps are to select the database and create the SQL statement. Suppose that the COFFEE_INVENTORY table exists in a MySQL database called "myDB". First, create a database variable, such as:
    $db = mysql_select_db("myDB", $connection);
Next, test that the database was selected. If it wasn't, print an error message and exit the program: 
    if (!$db) {
        echo "Couldn't select database!";
        exit;
    }
Up to this point, you've told PHP to connect to a server and select a database. If you've made it this far, you can issue a SQL statement and hopefully see some results! Using the COFFEE_INVENTORY table, suppose you want to view your inventory, including the name of the coffee and the roast type, with the highest number of bags listed first. Create a variable that holds your SQL statement:
    $sql = "SELECT COFFEE_NAME, ROAST_TYPE, QUANTITY
           FROM COFFEE_INVENTORY
         ORDER BY QUANTITY DESC";
Next, create a variable to hold the result of the query, carried out by the mysql_query function. The mysql_query function takes two arguments: the connection and SQL statement variables you've previously created.
    $sql_result = mysql_query($sql,$connection);
To format the results currently held in $sql_result, first separate the results by row, using the mysql_fetch_array function: 
    while ($row = mysql_fetch_array($sql_result)) {
        // more code here    
    }
The while loop will create an array called $row for each record in the result set. To get the individual elements of the record (COFFEE_NAME, ROAST_TYPE, QUANTITY), create specific variables: 
    $coffee_name = $row["COFFEE_NAME"];
    $roast_type = $row["ROAST_TYPE"];
    $quantity = $row["QUANTITY"];

You'll probably want to print the results in a simple HTML table. Step back and place this statement before the while loop begins, to open the table tag and create the row headings:
    echo "<TABLE BORDER=1>";
    echo "<TR><TH>Coffee Name&lt;/TH><TH>Roast Type&lt;/TH><TH>Quantity&lt;/TH>";

After defining the variables within the while loop, print them in table format: 
    echo "<TR><TD>$coffee_name&lt;/TD><TD>$roast_type&lt;/TD><TD>$quantity&lt;/TD>&lt;/TR>";
The new while loop now looks like this: 
    while ($row = mysql_fetch_array($sql_result)) {
        $coffee_name = $row["COFFEE_NAME"];
        $roast_type = $row["ROAST_TYPE"];
        $quantity = $row["QUANTITY"];
        echo "<TR><TD>$coffee_name&lt;/TD><TD>$roast_type&lt;/TD><TD>$quantity&lt;/TD>&lt;/TR>";
    }

After the while loop, close the HTML table: 
    echo "&lt;/TABLE>";
Finally, you'll want to free up the resources used to perform the query, and close the database connection. Failing to do so could cause memory leaks and other nasty resource-hogging things to occur.  
    mysql_free_result($sql_result);
    mysql_close($connection);
?>

The full script to perform a simple connection and data selection from a MySQL database could look something like this: 
<?php

    
// create connection
    
$connection = mysql_connect("servername","username","password");

    
// test connection
    
if (!$connection) {
        echo
"Couldn't make a connection!";
        exit;
    }

    
// select database
    
$db = mysql_select_db("myDB", $connection);

    
// test selection
    
if (!$db) {
        echo
"Couldn't select database!";
        exit;
    }

    
// create SQL statement
    
$sql = "SELECT COFFEE_NAME, ROAST_TYPE, QUANTITY
           FROM COFFEE_INVENTORY
         ORDER BY QUANTITY DESC"
;

    
// execute SQL query and get result
    
$sql_result = mysql_query($sql,$connection);

    
// start results formatting
    
echo "<TABLE BORDER=1>";
    echo
"<TR><TH>Coffee Name&lt;/TH><TH>Roast Type&lt;/TH><TH>Quantity&lt;/TH>";

    
// format results by row
    
while ($row = mysql_fetch_array($sql_result)) {
        
$coffee_name = $row["COFFEE_NAME"];
        
$roast_type = $row["ROAST_TYPE"];
        
$quantity = $row["QUANTITY"];
        echo
"<TR><TD>$coffee_name&lt;/TD><TD>$roast_type&lt;/TD><TD>$quantity&lt;/TD>&lt;/TR>";
    }

    echo
"&lt;/TABLE>";

    
// free resources and close connection
    
mysql_free_result($sql_result);
    
mysql_close($connection);
?>

Comments

Popular posts from this blog

A KING WHO WAS POPULAL AMONG HIS PEOPLE (King Birendra)

King of Nepal Reign 31 January 1972 –1 June 2001 Predecessor Mahendra Successor Dipendra Consort Aishwarya Rajya Laxmi Devi Shah Father King Mahendra Bir Bikram Shah Dev Mother Indra Rajya Laxmi Born 28 December 1945 Kathmandu, Nepal Died 1 June 2001 (aged 55) Kathmandu, Nepal Religion Hinduism Birendra and Aishwaraya had three children. Prince Dipendra (27 June 1971 – 4 June 2001) Princess Shruti (15 October 1976 – 1 June 2001) Prince Nirajan (6 November 1977–1 June 2001) Known As: A soft-spoken man with glasses and a mustacheKing Birendra was 10th in his line to rule Nepal and considered by some to be an incarnation of the Hindu god Vishnu.On formal occasions, the king was known for stilted speeches full of jargon that did not generate much inspiration.He was more at ease and best liked for listening closely to the problems of common people, especially poor villagers in a country that is among the poorest in the world with ...

A KING WHO WAS FAMOUS (His Majesty King Mahendra)

King Mahendra  Born > 11 June 1920 Father > King Tribhuvan Bir Bikram Shah Married To >  Indra Rajya Laxmi, daughter of General Hari Shamsher Rana in 1940 . Three sons >  Birendra,  Gyanendra, and Dhirendra Three daughters >Shanti, Sharada and Shobha. After Queen Indra died in 1950. In 1952 Mahendra married Indra's sister Ratna Rajya Lakshmi Devi. Crowned > May 2, 1956 Mahendra was made a British Field Marshal in 1960. Mahendra implemented a land reform policy, which provided land to many landless people. The Mahendra Highway (also called East-West Highway) that runs along the entire Terai belt in southern Nepal was constructed during his reign. He played a key role in making Nepal a member of the United Nations. Mahendra died with a heart attack while hunting in Chitwan with Tiger Tops Hotel. It is believed  that his death was a conspiracy of CIA as John Coapman who was also proprietor of  Chitwan with Tiger Tops Hotel was ...

Quest Software’s Unicode (UTF-8)

Please make note of the following caveats Toad for Oracle supports any single-byte character set. Enabling UTF-8 does not automatically cause issues with Toad. The use of double-byte or multi-byte character does not automatically result in issues with Toad, provided that the Oracle database Client/Server configuration settings are in synch. For instance, Toad for Oracle is used extensively in Korea and it works well. Issues can arise with certain combinations of the Oracle client NLS settings and Windows regional settings. However, they seem to occur only when inserting or updating data (there are some scenarios in which data retrieval can cause issues). This makes it crucial for the database, client and OS to be in synch with any internationalization settings. In addition, when using UTF-8 data in the editor or a grid, a font that supports the desired characters must be selected as the default font. Mono-space fonts (also known as fixed-width or non-proportional) will not support...