加快获取数据MYSQL(inplanting)

时间:2015-11-02 08:14:12

标签: php mysql

我是一名学习程序员,我正在努力学习PHP。 现在重点是我在新项目中使用了很多数据库连接。这有很多不同的DB需要不同的连接。

有没有人可以创建一个让我使用我的代码的函数? Getdata($User, $beerbrand, $sales);并在我的代码中使用这些变量?我每次使用相同的方法从数据库中获取数据。但是它有很多代码,我认为应该可以让它变得更容易一些。

我现在使用的方式:

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'];
    }

如果你认为这是一个愚蠢的问题,请温柔地向我解释一下。

祝你好运

1 个答案:

答案 0 :(得分:1)

<?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);
            }
}

你可以创建一个像这样的数据库文件来指定连接 并且您可以使用此文件在其他页面中处理您的查询.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;
    }
}