Make connections from one place in PHP

In JSP, if I want to connect to a database, I would create a Java class called DBManager with the following code:

public class DBManager {
    private final static String DB_URL = "jdbc:mysql://localhost:3306/mydb";
    private final static String DB_USERNAME = "root";
    private final static String DB_PASSWORD = "root";
    public static Connection conn = null;
    private static Statement stmt = null;

    /**
     * Tests connection with the database by getting connection using the
     * database url and username and password. And creates a dumb statement and
     * closes it to make sure everything is working fine.
     */
     static {
         try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager
                .getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
            stmt = conn.createStatement();
            stmt.close();
         } catch (Exception e) {
            e.printStackTrace();
         }
     }
}

      

Now I can easily do something like:

PreparedStatement pstmt = DBManager.conn.prepareStatement("SELECT * FROM USER");

      

I'm learning PHP on my own, and "most" online tutorials don't really teach you how to do things right.

They all do it the traditional way on every page they need a link to:

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

      

What's wrong because you want to change your password? Then you have to change it on every page where you used this password.

My question is, how can I do something equivalent / similar to this Java class in PHP?

EDIT:

<?php 
class DBManager {
   public static $conn = null;
   private static $hostname = "localhost";
   private static $username = "root";
   private static $password = "root";
   private static $dbname = "tutorme";

   protected function __construct() {
       try {
           DBManager::$conn = new PDO("mysql:host=localhost;dbname=tutorme", DBManager::$username, DBManager::$password);
           DBManager::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo "Error: " . $e->getMessage();
        }
    }

    public static function getInstance() {
        if (null === DBManager::$conn) {
            DBManager::$conn = new DBManager();
        }
       return DBManager::$conn;
   }
}
?>

      

I searched a bit and came up with the above code. However, now when I call

$stmt = DBManager::getInstance()->prepare("INSERT INTO SUBJECT (SubjectTitle, SubjectName) VALUES (:subject,:subj)");

      

I am getting an error that there is DBManager

no functionprepare()

which means my DBManager::getInstance

returns DBManager object

instead ofPDO conn object

+3


source to share


3 answers


You have one obvious mistake:

DBManager::$conn = new DBManager();

You don't want this!



Just call new DBManager()

and $conn

var will be initialized!

And also some minor changes,

<?php 
class DBManager {
    public static $conn = null;
    private static $hostname = "localhost";
    private static $username = "root";
    private static $password = "root";
    private static $dbname = "tutorme";

    private function __construct() {
        try { // why not using $hostname and $dbname?!
           DBManager::$conn = new PDO("mysql:host=" . DBManager::$hostname . ";dbname=" .DBManager::$dbname, DBManager::$username, DBManager::$password);
           DBManager::$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
           echo "Error: " . $e->getMessage();
        }
    }

    // getConnection() is a better naming of the function
    public static function getConnection() {
        if (is_null(DBManager::$conn)) {
            new DBManager();
       }
       // now $conn is initialized
       return DBManager::$conn;
    }
 }
 ?>

      

0


source


create a class like in java and call it database.php

in file u want to do something

include 'database.php';
.... your code ..... 

      



tip: search for "startup"

- Is this what you want?

0


source


you can start with this

class Database{
    function __construct(){
        $this->host = HOST;
        $this->user = DB_USER;
        $this->pass = DB_PASS;
        $this->db = DATABASE;
        $this->con = $this->connect();
    }

    function connect(){
        $q = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
        if($q) return $q; die("Couldn't Connect to Database");
    }
}

      

another file like for example

include 'Database.php';
$db = new Database();
mysqli_query($db->con, "QUERY_HERE");

      

0


source







All Articles