How do I connect to a MySQL database using PHP? Print
Submit Cancel
Email this article

Close

You are here: Home > Website Support > MySQL

The PHP scripting language is a popular method of accessing your MySQL database via the web. Below is a sample program using PHP to interact with a MySQL database, which has been commented to explain each function:

// Connect To Database
// * mysql_connect takes the servername, user,
// * and password as arguments. mysql_select_db
// * takes the database name. Together, they
// * open a connection to your database.

mysql_connect($SERVER,$USER,$PASSWORD);

mysql_select_db($DATABASE);

// Execute Query
// * mysql_query takes as its argument the query
// * you are executing on the database. It should
// * be assigned to a variable -- the variable is
// * used by other functions to retrieve the results.

$QUERY mysql_query("SELECT * from test");

// How many rows in results?
// * mysql_num_rows takes the variable the query
// * Was assigned to (referred to hereafter as the
// * query identifier) and returns the number of rows
// * the query resulted in.

$RESULT mysql_query($QUERY);
$NUMROWS mysql_num_rows($QUERY);

// Display Results

if ($NUMROWS{ $I 0; while ($I<$NUMROWS{

// Get Results
// * mysql_result returns the value of a specific field
// * in a specific row. It takes three arguments: the
// * first is the query identifier, the second is the row
// * number, and the third is the field name. In this
// * example, a while loop is used to process all
// * rows.

$FIELD1 mysql_result($RESULT,$I,"field1");

$FIELD2 mysql_result($RESULT,$I,"field2");

$FIELD3 mysql_result($RESULT,$I,"field3");

echo 
"field1 = $FIELD1, field2 = $FIELD2, field3 = $FIELD3 \n";
$I++;

}

}

?> 

Was this information helpful?

Yes No

Thank you for your feedback
We are delighted to find that our article resolved your query.

Thank you for your feedback
We will resolve your query as soon as possible.

Please take a few moments to comment on your unresolved query. Simply tell us what your problem is. We guarantee that we'll get back to you within two hours (during office hours) in response to your query.


  Partially resolved    Unresolved
Enter your query here:
Your name:
Your email address:
Contact number:
Customer number or domain name:
 
Preferred contact method: Email     Call me
Please enter the text in the picture below into the text box:
CAPTCHA Image:
ID Number:
 
  • Hosting for Beginners

    Step-by-step guide to hosting with Hetzner.

    VIEW NOW
  • Application Tutorials

    Use our installation guides to get up and running.

    VIEW NOW
  • Login Now

    Our award winning proprietary control panel empowers customers to manage their hosting environment.

    Take the Tour
  • Contact Us

    support@hetzner.co.za

    Phone: 0861-0861-08
    Fax: 0861 0861-09
    Contact Us