Connecting to a MySQL database using PHP
Posted on June 4th, 2008 by roger
If you ever wanted a simple way to connect to a MySQL database using PHP, use the following files to connect quick and simple.
To Download: Database files
Steps:
- The “Config.inc.php” creates an instance of the “Database.php” class. All you need to do is open up “Config.inc.php” and edit the “require_once(’Database.php’);” to point to where the “Database.php” class is in your directory. And then edit the server, username, password and database name variables.
- In the page where you want to connect to the database - let’s call it test.php, connect like so:
<php require_once("Config.inc.php"); $cg = new Config(); // Now you can make sql queries like so $results = $cg->query("SELECT * FROM mytablename"); while($result = mysql_fetch_assoc($results)){ // do something with the data echo $result["columnname"]; } ?> - If you do not want to use “Config.inc.php”, you can connect simply by using the following line of code:
<php require_once("Database.php"); $db = new Database("server", "databasename", "username", "password"); // Now you can make sql queries like so $results = $db->query("SELECT * FROM mytablename"); while($result = mysql_fetch_assoc($results)){ // do something with the data echo $result["columnname"]; } ?>
Filed under: PHP