Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    php
  » Connect to MySQL
      by sde
 Page 1 of 1 
   

(Login to remove green text ads)
MySQL Connect Script
One of the fundimentals of PHP is connecting to a MySQL server. Before you begin to use functions such as mysql_query(), you need to do 2 things.

1. Connect to the MySQL Server.
2. Select the Database.

It is very common to have your connection code in it's own file so you can just include it at the top of every page that needs to connect to the database. The reason you would want to do this is so when you need to modify the databae connection information, you only have to change it in 1 place.

See the code below:
PHP Code:
<?
/*--------- DATABASE CONNECTION INFO---------*/
$hostname="localhost";
$mysql_login="myusername";
$mysql_password="mypassword";
$database="mydatabase";

// connect to the database server
if (!($db mysql_pconnect($hostname$mysql_login $mysql_password))){
  die(
"Can't connect to database server.");    
}else{
  
// select a database
    
if (!(mysql_select_db("$database",$db))){
      die(
"Can't connect to database.");
    }
}
?>
You could place this code at the top of a script that you need to connect to a database, but I recommend saving this file as connect.php and put it in a directory with other files you might include. Then, when you want to use the code, just include it like in the example below.
PHP Code:
<?
include("includes/connect.php");
// now you are connected and can query the database
$request mysql_query("select field1,field2 from table");

// loop through the results with mysql_fetch_array()
while($row mysql_fetch_array($result)){
  echo 
$row[0]." / ".$row[1]."<br>\n";
}

// don't forget to close the mysql connection
mysql_close();
?>





 
 Page 1 of 1 
   

Rate This Article
1 2 3 4 5 6 7 8 9 10





Copyright © 2000-2006, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting
Open Circle