2019独角兽企业重金招聘Python工程师标准>>>
最近做了一个基于php技术的企业网站,第一次使用php,边学边做,为了更好的完成网站,也为了让代码更易于维护,里面大量运用了单例模式,以下是数据库连接的代码,请君品鉴,如有可改进的,也希望您能提出意见,批评指正。
为了快速完成开发,没有使用配置文件,直接写在类里面了。
conn.php
<?phpclass MySqlManager{private $con; private static $instance;private $server="localhost";private $username="root";private $userpwd="111111"; private $database="enterprise"; public static function getInstance(){if(!self::$instance){self::$instance=new MySqlManager();}return self::$instance;}public function execute($sql){return mysql_query($sql);} public function close(){if($this->con){mysql_close($this->con);}}public function open(){$this->con = mysql_connect($this->server.":3306",$this->username,$this->userpwd);if(!$this->con){die("connect mysql error "+$this->con.mysql_error());}else{//echo "connect mysql success ";mysql_select_db($this->database);}}function __construct(){//构造函数//echo $this->server;$this->open();}function __destruct(){ //析构函数 }}
?>
这样的话,调用起来就很方便了
<?phprequire("./conn.php");$conobj= MySqlManager::getInstance(); $conobj->open(); $sql= "select * from table t"; $query=$conobj->execute($sql); $row=mysql_fetch_row($query);if($row){//处理业务逻辑}$conobj->close();
?>
本博客文章大多是经验积累总结,以免今后忘却,记录下来。同时感谢您的阅读,也希望能对您有所帮助。