Forgot Password / Register
Site Statistics
Total Members: 510
Total Tutorials: 242
Newsest User: Hp
Todays Unique Hits: 128
0 Users 2 Guests Online

Easy way to use PHP + MySQL

This script is petty advanced if you do not know much bout PHP and MySQL, but if you follow my directions, you should be able to get it to work with no problems.

I found this code on another website and modifid it to work better.

1) Make a folder named "includes" in the root of your site.
2) Make a file called "SystemComponent.php" and put this code in it replacing HOST, USERNAME, PASSWORD, and DATABASE with the correct values for your sever.
Code
<?php
class SystemComponent {

var $settings;

function getSettings() {

$settings['dbhost'] = 'HOST';
$settings['dbusername'] = 'USERNAME';
$settings['dbpassword'] = 'PASSWORD';
$settings['dbname'] = 'DATABASE';

return $settings;

}

}
?>

3) Make another file in the includs folder called "DbConector.php" an put the following script in it.
Code
<?php
require_once 'SystemComponent.php';

class DbConnector extends SystemComponent {

var $theQuery;
var $link;

function DbConnector(){
$settings = SystemComponent::getSettings();

$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];

$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
}
function query($query) {
$this->theQuery = $query;
return mysql_query($query, $this->link);
}
function fetchArray($result) {
return mysql_fetch_array($result);
}
function close() {
mysql_close($this->link);
}
}
?>

4) Now in every page you want to connect to your database, just add the following lines.
Code
require_once("includes/DbConnector.php");
$conn = new DbConnector();

5) This script wll automatically connect to the database when you put those two lines of code into a page. Then you can use "$query = $conn->query('QUERY GOES HERE');" to run a query and "$query = $conn->fetchArray($query);" to fetch an array from the query just like with "mysql_query" and "mysql_fetch_array." You can also put "$conn->close();" at the end of the page to close the MySQL connection.

I hope this makes your MySQL integration easier!
Xerofait
Author:
Views:
1630
Rating:
Posted on Monday 24th March 2008 at 04:29 PM
Enros
Enros
Ahhh why did you do that to connect to your db ?


Why didnt you just go :

<?PHP
//Variables
$db_user = "db_user";//User name for the database
$db_pass = "password";//Password for the database
$db_host = "localhost";//Database host, mostly localhost
$db_name = "db_name";//the database name

//Connection with the Varibles
$mysql_access = mysql_connect($db_host, $db_user, $db_pass);
mysql_select_db($db_name);

?>


Then the file in which you put this in could be called connect.php


Then at the top of each of your pages all youd need to put is include('connect.php');


I think that would be wayyyy simpler...