RSS

Connecting to a MySQL database

Thu, Jan 1, 2009

Code, PHP, SQL

Below are the steps to connect to and extract data from a MySQL database.

Connecting to the database

Step 1. Create and configure some connection variables.

$mysql_server = "mysql.yourserver.com";
$mysql_user = "admin";
$mysql_pwd= "password";
$mysql_db= "mydatabase";



Step 2. Create connection.

$mysql_connection =
mysql_connect($mysql_server, $mysql_user, $mysql_pwd);



Step 3. Select your database.

mysql_select_db($mysql_db) or die("Unable to select a database.");



Step 4. Create your SQL string.

$mysql_sql = "SELECT * FROM mytable";



Step 5. Combine your connection string and your SQL to return data.

$mysql_result = mysql_query($mysql_sql, $mysql_connection);


Printing the data

Step 6. Loop through the results and write it to the page. This output’s format is not pretty since it is meant to be simple.

while($data_row = mysql_fetch_row($mysql_result)) {
    foreach($data_row as $data_field) {
        print $data_field;
    }
    print "<br />";
}



Step 7. Close the connection string.

mysql_close($mysql_connection);
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • email
  • MySpace
  • Twitter
  • Yahoo! Buzz
  • PDF
  • Reddit
  • Slashdot
  • Technorati
, ,

Leave a Reply