doudang2537 2016-07-02 15:44
浏览 30
已采纳

PHP SQL代码优化[关闭]

I am learning the object oriented PHP. Now I have the mission to get a connection. I'd like to show my code and ask you for some optimization support. Maybe there are several absolutely wrong understood things. I don't hope so. I want to improve my design. In real the Constants of course have the rights values. BIG THANKS! :)

// index.php

<?php
require( dirname( __FILE__ ) . '/config.php' );
new db(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
?>

// config.php

<?php
define('DB_HOST', 'host');
define('DB_USER', 'user');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');

if (!defined('ABSPATH') )
    define('ABSPATH', dirname(__FILE__) . '/');

require_once(ABSPATH . '/includes/classes/db.class.php');
?>

// db.class.php

<?php
class db
{
    protected $db_host;
    protected $db_user;
    protected $db_password;
    protected $db_name;

    function __construct($dbHost, $dbUser, $dbPassword, $dbName)
    {
        global $mysqli;

        $this -> db_host       = $dbHost;
        $this -> db_user       = $dbUser;
        $this -> db_password   = $dbPassword;
        $this -> db_name       = $dbName;

        $this -> mysqli = new mysqli($this -> db_host, $this -> db_user, $this -> db_password, $this -> db_name);
        $mysqli = $this -> mysqli;
    }
}
?>
  • 写回答

2条回答 默认 最新

  • drcrc28428 2016-07-02 15:49
    关注

    Here are some tips I found some time back, On the DB layer

    Define connection as a static variable, to avoid connecting more than once

    static $connection;
    

    Try and connect to the database, if a connection has not been established yet, Create connection only once

    if(!isset($connection)) {
         // Load configuration as an array. Use the actual location of your configuration file
        $config = parse_ini_file('../config.ini'); 
        $connection = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
    }
    

    If connection was not successful, handle the error

    if($connection === false) {
        // Handle error - notify administrator, log to a file, show an error screen, etc.
        return mysqli_connect_error(); 
    }
    

    Finally return connection

    return $connection;
    

    More info: https://www.binpress.com/tutorial/using-php-with-mysql-the-right-way/17

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?