-2

I've got not too much experience programing but I've done a little application with a few PHP files and I'd like to optimize it.

I want to extract all the repeated code and place it inside a folder as a PHP file, that I will call later, when I need the code.

For example this lines are repeated in all my files:

$servername = "ejemplo.es";
$username = "ramon";
$dbname = "bbdd";
$password = "loquesea";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
}
  • 1
    You could put that code in a separate file and [`include`](http://php.net/manual/en/function.include.php) it where needed. – showdev Jul 21 '16 at 23:28
  • @showdev a `require_once` would be more appropriate than an `include` especially if you have are including database connections see this: http://stackoverflow.com/questions/2418473/difference-between-require-include-and-include-once – ILikeTacos Jul 21 '16 at 23:29
  • @showdev Creating a class, or writing it as a simple function? (In the included file) – Ramón Miguel Jul 21 '16 at 23:30

1 Answers1

3

first of all, you should read a php tutorial about functions and object orientated programming.

In your case, you could have a class for your database things called Database, which would look something like this:

<?php

class Database
{
    private $_connection = null;

    public function __construct($host, $username, $password, $database)
    {
        // connect to database and store the connection for further use
    }

    public function doThisAndThat()
    {
        // do some fancy database stuff
    }

    public function __destruct()
    {
        // important for databases is to disconnect from them
    }
}

Then all you have to do is include your Database class file and call it like that:

$db = new Database($host, $username, $password, $database);
$db->doThisAndThat();
Alonso Urbano
  • 2,266
  • 1
  • 19
  • 26
Manuel Mannhardt
  • 2,191
  • 1
  • 17
  • 23