Evert Arends
Evert Arends

Reputation: 142

Speeding up getting data MYSQL (inplanting)

I'm a learning programmer and I'm trying to learn PHP. Now the point is that I use alot of db connections in my new project. This are alot of different DB's an require different connection.

Does anybody a way where I can create a function what makes me use my code like this? Getdata($User, $beerbrand, $sales); and use these variables in my code? I use the same way to get the data out of the database everytime. But it's alot of code, where I think it should be possible to make that a little easier.

The way I use now:

mysql_connect($host, $user, $password) or die ("cannot connect");
mysql_select_db("$db_name");
 $stuff = mysql_query("SELECT * FROM beers ORDER BY ID");
    while($frontstuff = mysql_fetch_array($stuff)){
        $us = $frontstuff['Beer'];
    }

If you think this is a stupid question, please be gentle and explain it to me in a easy way.

Best regards

Upvotes: 0

Views: 42

Answers (1)

Vishal
Vishal

Reputation: 553

<?php 
    class Database {

            private $connection;    //Database Connection Link
            private $userName;      //Database server User Name
            private $password;      //Database server Password
            private $database;      //Database Name
            private $hostname;      //Name of database server

            public function __construct() {
                $this->hostname=your servername
                $this->userName=yourusername
                $this->password=yourpasswrod
                $this->database=your bb name
                try {
                    $this->connectlink = mysql_connect($this->hostname,$this->userName,$this->password);
                    if(!($this->connectlink)) {
                        throw new Exception("Error Connecting to the Database".mysql_error(),"101");
                    }
                    if(!mysql_select_db($this->database, $this->connectlink)) {
                        throw new Exception("Error Connecting to the Database1".mysql_error(),"101");
                    }
                }catch(Exception $e){
                    //print_r($dbConfig);
                    echo $e->getMessage();
                }

            }

            public function __destruct() {
                @mysql_close($this->connectlink);
            }
}

you can crete a database file like this for specifying connnection and you can use this file in processing your query in another pages.Eg

<?php
include_once("database.php");

    function __construct(){
        $this->db = new Database;
    }

    public function getstuf($parameter){
        $stuff = mysql_query("SELECT * FROM beers ORDER BY ID");
    while($frontstuff = mysql_fetch_array($stuff)){
        $us = $frontstuff['Beer'];
    }
return stuff;
    }
}

Upvotes: 1

Related Questions