close

User Level: Beginner to Intermediate

  1.  
  2. < ?php
  3. class MySQLHandler {
  4. var $mysql_host;
  5. var $mysql_username;
  6. var $mysql_password;
  7. var $mysql_marking_database;
  8. var $link;
  9. var $select_db;
  10.  
  11. function MySQLHandler($database_name) {
  12. $this->mysql_host = "INSERT_HOST_HERE";
  13. $this->mysql_username = "INSERT_USERNAME_HERE";
  14. $this->mysql_password = "INSERT_PASSWORD_HERE";
  15. $this->mysql_marking_database = $database_name;
  16. }
  17.  
  18. function open_mysql_link() {
  19. $this->link = mysql_connect($this->mysql_host,
  20. $this->mysql_username, $this->mysql_password);
  21. $this->select_db = mysql_select_db(
  22. $this->mysql_marking_database, $this->link);
  23. return $this->link;
  24. }
  25.  
  26. function close_mysql_link() {
  27. mysql_close($this->link);
  28. }
  29. }
  30. ?>
  31.  

The above PHP script (mysql_handler.php) can be used to connect to your MySQL database with PHP.

  1.  
  2. < ?php
  3. include('classes/mysql_handler.php');
  4. $mysql = new MySQLHandler("database_name");
  5. ?>
  6.  

The include line will allow you to make references to the class, the 2nd line will allow you to initiate the class with a database name.

  1.  
  2. $mysql_link = $mysql->open_mysql_link();
  3.  

Then when you need a link for your MySQL functions, all you need to do is specify the above script and you're connected.

You may want to further secure this file by placing your host, username, and password details elsewhere.