PHP Source Database Build Table-configuration file-Error log method

Source: Internet
Author: User
Tags log log manual writing session id php class php database php database connection class sql error jquery library
This article mainly introduces the PHP database building table-configuration file-error log method, has a certain reference value, now share to everyone, the need for friends can refer to

Main:

    1. organizing Frames

    2. Build a database and build a table

    3. Configuration file Classes

    4. Error log records

--------------This post file structure:--------------------------------------blog├─app│  ├─model model Catalog │  ├─view View directory │  │  ├─admin Background Directory │  │  └─home Front table │  ├─common profile │  │  └─config.php  profile │  ├─log log directory │  │  └─log.txt  log file │  ├─controller Controller │  │  ├─admin backstage │  │ │ └─democontroller.class.php test controller │  │  └─home front desk ├─public   static public file (js,css,images) │  ├─plugins Plugin │  ├─back Backstage │  └─home Front ├─frame Public use class │   ├─basemodel.class.php database connection class │   ├─basecontroller.class.php Controller public operation (set code, information jump) │   ├─factorymodel.class.php  Model factory class │   ├─log.class.php  Journal factory category │   ├─config.class.php  configuration file read class │   ├─init.class.php  Initialize application class │   └─mysqldb.class.php Database Operations Tool Class └─index.php  Portal File-----------------------------------------------------------------------------------------------------

Using the MVC framework structure built in the previous article, we started to develop blog projects. First set up the data table, and then start to build the background, data front display, complete the main module display blog.

Download View the project source : Https://gitee.com/NewbiesYang/young_blog

organizing Frames

Clean Up test page

1) Build the framework structure, using the user Login test page and the background home page. Get rid of all this and start building the foreground and background pages from scratch. Similar to the one we downloaded for a thinkphp or laravel or other frame. Now start building our project in this mini-frame

2) The actual development, will use the front-end staff do a static page to develop. So you can also download the background template and the foreground blog static page in the "Template House" or other website. Then focus on back-end development, which can speed up. This project is used for study and research, and it is less anxious.


     It was intended to take full advantage of someone else's written front-end pages (including front-end display and background pages) and focus on the development of back-end logic. And the list of categorized pages has been done. Also submitted for delivery.     now, think about it, if you play like that, I'll use the frame better. Since do back-end development, write your own back-end page + program processing, there is no problem it ..., put the front page display, then the predecessor of the front page to write can be so    , roll up grapefruit, said dry, first to organize the framework, began to build blog ....

Frame structure:

--------------the structure of the MVC framework file after cleanup:--------------------------------------blog├─app│  ├─model model Catalog │  ├─view View Catalog │  │  ├─back backstage │  │  └─home Front │  ├─controller Controller directory │  │  ├─back backstage │  │ └─home Front desk ├─public   static public file (js,css,images) │  ├─plugins plugin │  ├─back backstage │  └─home front ├─frame Public use of the class │   ├─basemodel.class.php database Connection class │   ├─basecontroller.class.php Controller common operation (set code, information jump) │   ├─factorymodel.class.php  model factory class │   ├─init.class.php  Initialize application class │   └─mysqldb.class.php Database Operations Tool Class └─index.php  Portal File-----------------------------------------------------------------

Subsequent development only needs to replicate the directory structure file, it can be developed on this basis.

Submit Transfer Code

git add-agit commit-m "Clean up MVC structure" Git push origin Master

Plugin Preparation

1) Layui plug-in: Set up a background program, ready to use the Layui front-end framework, this framework personally think that the background interface is good. It also contains some comparisons using modules.

With Bootstrap can also, I prefer to use it to do the front page.

Download URL: http://www.layui.com/

2) jquery Library: More convenient to manipulate the DOM, especially with Ajax requests.

3) Other plugins: such as Ueditor editor and so on need to use and then download it. General plug-ins will have demo samples, follow the examples and manuals, understand web development basic can use.

The above plug-in is not familiar with the temporary, the official online manuals, what modules need, then the manual will be used, like building blocks, if you want to do better, of course, more time to spend more practice. I am in the background to the program administrator to use, do not necessarily have to be very beautiful, practical good.

Build a database and build a table

Preparing: Creating a Branch

$ git checkout master$ git checkout-b "Start-admin-module"

The idea of building a table:

According to the blog template, from the first page analysis, analysis of what needs Dynamic data, in order to establish the corresponding data table.

Users: Login, register, modify, delete

Article: Classification management, blog post management, comment management

Role management: Administrators, general users

Menu Management: Different permissions for people, the corresponding menu bar also has a difference

The Build Table tool can be selected arbitrarily. The initial manual writing table statements, familiar with the use of tools directly. Use Navicat to build databases and tables in this project

Database, table

1) CREATE DATABASE: Php_blog

Create Database Php_blog CharSet UTF8

2) User table: Y_users

create TABLE ' Y_user ' (' id ' int (ten) unsigned not NULL auto_increment COMMENT ' user primary key ', ' username ' varchar () NOT NULL COMMENT ' username ', ' password ' char (+) NOT null COMMENT ' password ', ' email ' varchar (not NU)  LL default ' COMMENT ' registered mailbox ', ' token_email ' varchar (+) not NULL default ' COMMENT ' Mailbox authentication ', ' status ' tinyint (1) unsigned Not null default ' 0 ' COMMENT ' state, 0-Normal, 1-disabled ', ' gid ' tinyint (1) unsigned NOT null default ' 0 ' COMMENT ' role id,1-Administrator, 2-normal user, 0-Invalid ', ' login_ip ' varchar (a) NOT null DEFAULT ' COMMENT ' last logged on IP address ', ' login_times ' smallint (6) unsigned NOT NULL Defau LT ' 0 ' COMMENT ' login number ', ' created_at ' int (ten) unsigned not NULL DEFAULT ' 0 ' COMMENT ' registration Time ', ' updated_at ' int (ten) unsigned Not NULL DEFAULT ' 0 ' COMMENT ' last login time ', PRIMARY key (' id '), unique key ' username ' (' username '), unique key ' email ' (' E Mail ')) Engine=myisam auto_increment=6 DEFAULT charset=utf8 comment= ' user table '; 

User Table SQL

3) Role table: Y_user_group

CREATE TABLE ' Y_user_group ' (  ' id ' int (ten) unsigned not NULL auto_increment COMMENT ' role id ',  ' name ' varchar () not Null default ' COMMENT ' role name ',  ' auths ' varchar (255) Not NULL default ' COMMENT ' role permissions ',  PRIMARY KEY (' id ')) ENGI Ne=myisam DEFAULT charset=utf8mb4 comment= ' character table ';

Role Table SQL

4) Menu Table: Y_menus

CREATE TABLE ' Y_menus ' (  ' id ' int (ten) unsigned not NULL auto_increment COMMENT ' menu id ',  ' title ' varchar (DEFAULT) ' COMMENT ' menu name ',  ' controller ' varchar (+) ' default ' ' COMMENT ' controllers name ',  ' action ' varchar (default ' COMMENT ') Operation name ',  ' status ' tinyint (1) unsigned default ' 1 ' COMMENT ' status, 1-normal, 0-disabled ',  ' is_hidden ' tinyint (1) unsigned default ' 0 ' COMMENT ' is hidden, 0-normal display, 1-hidden ',  ' sort ' int (ten) unsigned default ' 0 ' COMMENT ' sort ',  ' pid ' int (ten) unsigned default ' 0 ' COMMENT ' upper menu ',  PRIMARY KEY (' id ')) engine=myisam DEFAULT charset=utf8mb4 comment= ' Menu table ';

Menu Table SQL

5) Article Table y_article

create TABLE ' y_article ' (' id ' int () unsigned not NULL auto_increment COMMENT ' text Chapter ID ', ' title ' varchar ($) NOT null default ' COMMENT ' title ', ' description ' varchar ($) NOT null default ' COMMENT ' article introduction ', ' content ' text NOT null COMMENT ' contents ', ' cid ' int (ten) unsigned not null COMMENT ' article category ', ' pic ' varchar ($) NOT NULL DE FAULT ' COMMENT ' article cover map ', ' pic_watermark ' varchar ' not NULL DEFAULT ' COMMENT ' watermark graph ', ' pic_thumb ' varchar (N) ULL default ' COMMENT ' thumbnail ', ' uid ' int (ten) unsigned not null COMMENT ' author ', ' clicks ' Int (ten) unsigned NOT null DEFAULT ' 0 ' COMMENT ' reading (number of hits) ', ' updated_at ' int (ten) unsigned NOT null DEFAULT ' 0 ' COMMENT ' update Time ', ' created_at ' int (one) NOT NULL DEFAULT ' 0 ' COMMENT ' release time ', PRIMARY key (' ID '), key ' title ' (' title '), Key ' uid ' (' uid '), key ' clicks ' (' clicks '), KE Y ' CID ' (' CID ') USING BTREE) Engine=myisam auto_increment=4 DEFAULT charset=utf8 comment= ' Article table '; 

Article Table sql

6) Article Category table Y_category

CREATE TABLE ' y_category ' (  ' id ' int (ten) unsigned not NULL auto_increment COMMENT ' class ID ',  ' catename ' varchar (N) OT null COMMENT ' class name ',  ' description ' varchar (255) Not NULL DEFAULT ' COMMENT ' profile ',  PRIMARY KEY (' id ')) engine=myi SAM auto_increment=15 DEFAULT Charset=utf8 comment= ' article category table ';

Article Category Table SQL

7) Comment (Reply) Table y_comment

CREATE TABLE ' y_comment ' (  ' id ' int () unsigned not NULL auto_increment comment ' Comment id ',  ' uid ' int (ten) unsigned NO  T null COMMENT ' reviewer ',  ' created_at ' int (one) default NULL COMMENT ' comment time ',  ' content ' varchar (255) Not NULL default ' COMMENT ' comments ',  ' aid ' int (ten) unsigned not NULL COMMENT ' commented article ',  PRIMARY KEY (' id ')) engine=myisam DEFAULT CHA Rset=utf8 comment= ' comment (reply) table ';

Comment (reply) Table SQL

8) Session data table y_session (in fact, can not use this, the purpose is to operate "write session to the database")

CREATE TABLE ' y_session ' (  ' sess_id ' varchar () NOT null DEFAULT ' COMMENT ' session id ',  ' data ' text is not null CO Mment ' session data ',  ' created_at ' int (one) not NULL COMMENT ' session creation time ',  PRIMARY KEY (' sess_id ')) Engine=myisam DEFAULT Charset=utf8 comment= ' session data table ';

Session data Table SQL

To avoid getting too complicated, the data tables are created temporarily, and the fields can be adjusted later. If you need to add a module function, you can add the corresponding data table accordingly.

Connecting to a database

Modify the array information "frame/basemodel.class.php" of the data connection in Bademodel (if you use a configuration file class, you can omit it here)

1 class Basemodel {  2     ...  3     ...  4     ...  5     function __construct (array $config =null)  6     {  7         $conf = Array (  8             ' host ' = = ' localhost ',  9             ' user ' + ' root ', '             pwd ' = ' root ', one             ' port ' = ' 3306 ',             ' CharSet ' = ' and ' UTF8 ', ' dbname ' and '             php_blog ', ' and ',         $conf = Empty ($config)? $conf: Array_merge ($ conf, $config);         $this->db = Db::getdb ($conf);     18}

Setting up connection Database information

Configuration file Classes

Requirements Analysis:

For the framework easy database connection and easy to read configuration files. If you want to do some configuration items in app/common/config.php, ask to be able to read these configurations and apply them to the project

Ideas:

Step 1:  Create a file  app/common/config.php  and write the database connection information to the configuration file Step 2:  Create a read profile class in the frame/directory Config.class.phpstep 3: Set automatic load Read Configuration class Step 4: The underlying model class instantiates the read configuration class. The operational database must go through the underlying model class step 5:  Adjust the Database Tools class to get configuration information, both in its construction method by passing in the data configuration information object to get Step 6: Test the connection Data results, verify the Get configuration


Implementing a connected database-reading database configuration information ideas

Code implementation

1) Create configuration file config.php "app/common/config.php"

<?php/** * Config file * User:young */return [    //Database connection Configuration    ' host ' = ' localhost ',    ' User ' = ' root ',    ' Pwd ' = ' root ',    ' port ' = ' 3306 ',    ' charset ' = ' utf8 ',    ' dbname ' = ' php_blog ', ';

Configuration file-database configuration information

2) Create Read profile class "frame/config.class.php"

 1 <?php 2/** 3 * Config file read Class 4 * User:young 5 */6 7 class Config 8 {9 protected static $ins = NULL; Examples of this class are protected $cfg = Array ();     Storage Configuration Items 11 12/** 13 * Get this class instance * @access Public * @return Object class Singleton 16 */17 public static function Getins () {if (false = = = (self:: $ins instanceof Self)) {self:: $ins = new S Elf (); Return self:: $ins; 22} 23 24/** 25 * Construction Method: Read Configuration item * @access public * @return void * * Final PR otected function __construct () {require APP. ' Common '. DS. ' config.php '; Read Configuration entry $this->cfg = $cfg; 32} 33 34/** 35 * Returns the value of the configuration item, based on the specified configuration item. * @param string $K configuration item * @return Mixed|null returns the data for the configuration item         * * * All public Function __get ($k) {!isset ($this->cfg[$k]) {$ return null; 42 }->cfg[return $this $k]; 44} 45 46 47/** 48 * Returns the value of the configuration item according to the specified configuration item. * @param string $K configuration Item Name * @param string $v The value of the configuration item 51 */ __set Public Function ($k, $v) {$k $this->cfg[] = $v; 54} 55}

3) Auto Load Configuration class

The class needs to be loaded automatically, and the class is in the Frame directory, so it can be written to an array of attributes in the Init.class.php class "frame/init.class.php"

<?php/** * Initialize Application class * User:young */class init{    protected static $frame = Array (' Basecontroller ', ' Basemodel ', ' Db ', ' F Actorymodel ', ' Config '), ... Automatically load configuration classes

4) Basic model class instantiation configuration Class "frame/basemodel.class.php"

<?php/** * BaseModel.class.php base model class *     Connection Database *  @author young */class basemodel{    protected $db = null;    /**     * Construction Method: Instantiate database Class     * @access public *    /function __construct ()    {       $conf =  Config:: Getins (); Reads the configuration item instance        $this->db = Db::getdb ($conf);}    }

5) database Read configuration item information "frame/db.class.php"

<?php/** * Db.class.php Database Operations Tool class * @author young */class Db {...    /**     * Construction Method: Save database connection information, connect database     * @access Private     * @param array $conf database connection information */    Private function __construct ($conf)    {        $this->host = $conf->host;        $this->user = $conf->user;        $this->pwd = $conf->pwd;        $this->port = $conf->port;        $this->charset = $conf->charset;        $this->dbname = $conf->dbname;        $this->connect ();    } ..... The Database Tools class gets the configuration information

6) Testing in app/controller/home/democontroller.class.php for testing database connection conditions

<?php/** * Test Controller class * User:young */class Democontroller extends basecontroller{public    function test ()    {
  
    $DB = new Basemodel ();        $data = $db->db->getallrows ("SELECT * from Y_user");        Var_dump ($data);    }}
  

Test controller class Test connection database

Note: The $db attribute in BaseModel.class.php needs to be temporarily modified to public before it can be tested successfully (reason: the underlying model class instantiated in the demo controller, the database operation instance is placed in the class's attribute db, External cannot access the protected property), all tests in this section can temporarily set the db to public.

You can also use configuration such as: Upload directory, site configuration information, etc., according to the requirements of custom configuration requirements, and then read the configuration class read the configured data

Submit Code

Git add-agit commit-m "Finish reading Profile class"

Error log records

In addition to debugging errors during the development phase, project launch typically writes error information to the specified file. Better security.

Requirements Analysis:

Writes an error to the log file, where the database operation is temporarily primarily logged for errors. For example, the error is logged in App/log/logerror.txt by default. If configured in the configuration file, log information is written to the directory specified in the configuration item Log

Ideas:

Step 1: Make Log Class frame/log.class.php, which is used to write error information to the specified file.  (Set the log file location, just can use the above-written configuration items, through the read configuration to achieve) Step 2: In the base model class Basemodel, after reading the configuration item, you can write the log directory path to the constant. Use try: Catch catch exception, write error to log Step 3: Implement automatic loading of log classes. The log class is in the frame directory, so as long as the "log" Step 4: Log error is added to the attribute $frame array initialized in the application class init. Database connection may fail, SQL statement may fail Step 5: Test error logging

Implementing Error logging Process ideas

Code implementation

1) Making error log Class "frame/log.class.php"

<?php/** * Db.class.php Database Operations Tool class * @author young */class Db {...    /**     * Construction Method: Save database connection information, connect database     * @access Private     * @param array $conf database connection information */    Private function __construct ($conf)    {        $this->host = $conf->host;        $this->user = $conf->user;        $this->pwd = $conf->pwd;        $this->port = $conf->port;        $this->charset = $conf->charset;        $this->dbname = $conf->dbname;        $this->connect ();    } ..... The Database Tools class gets the configuration information

2) Read the log location and catch the error "frame/basemodel.class.php"

After the error record, this is simply using Exit (..) Exit, you can customize error error page is better

<?php/** * BaseModel.class.php base model class *     connect to database, catch record error *  @author young */class basemodel{public    $db = null;< c3/>/**     * Construction Method: Instantiate database Class     * @access public *    /function __construct ()    {        $conf =  Config:: Getins (); Reads a configuration item instance        //reads the log configuration item and writes it as a constant        $logPath = $conf->log;        $logPath =!isset ($logPath)? APP. " Log ". DS  : $logPath;        Define (' LOG ', $logPath);        Monitoring database Operation        try {            $this->db = Db::getdb ($conf);        } catch (Exception $e) {            $err = ';            $err. = ' Error code: '. $e->getcode (). "\ r \ n";            $err. = ' Error message: '. $e->getmessage (). "\ r \ n";            $err. =  ' file: '. $e->getfile (). "\ r \ n";            $err. =  ' line number: '. $e->getline (). "\r\n\r\n";            Log::write ($err);            Exit ("

3) Automatic load logging class "frame/init.class.php"

<?php/** * Initialize Application class * User:young */class init{    protected static $frame = Array (' Basecontroller ', ' Basemodel ', ' Db ', ' F Actorymodel ', ' Config ', ' Log '); Click to view "Load log class automatically"

4) Log Error "frame/db.class.php"

Error handling may occur for database connections

Class db{.....    /**     * Connect database, set encoding, select Library     * @access Private     *    /Private Function connect ()    {        $this->link = @ Mysql_connect ("{$this->host}:{$this->port}", "$this->user", "$this->pwd");        if (! $this-Link) {            $error = new Exception ("Database connection not on", 10000);            throw $error;        }        $this->setcharset ($this->charset);        $this->usedb ($this->dbname);    } ... Click to view "Database connection error Thrown"

SQL statement Error handling

Class Db {.....    /**     * Execute SQL statement     * @param  string $sql SQL statement     * @return Mixed     *    /Private Function query ($sql) c7/>{        $result = mysql_query ($sql, $this->link),//        if (false = = = $result) {//            echo ' <p>sql execution failed! <br> ";//            echo" <br> failure statement: ". $sql;//            echo" <br> error code ". Mysql_errno ();//            echo" <br > Error Tip: ". Mysql_error ()." </p> ";//            exit ();/        }        if (false = = = $result) {            $err =" SQL execution failed!\r\n failure statement: ". $sql." \ r \ n error code: ". Mysql_errno ()." \ r \ n error hint: ". Mysql_error ()." \r\n\r\n ";            Log::write ($err);            Exit ("

Test

You can configure the log file directory in "app/common/config.php". If not configured, the default record is in the app/log/directory

<?php/** * Config file * User:young */return [    //Database connection Configuration    ... 、 。。。    .....    //log file location configuration    ' log ' = + APP,]; Click to view "log file Configuration"

The following tests can be used to turn on configuration log in configuration items and to test separately after shutting down. Note: If you do not configure log, you must first create a log directory in the app directory

1. Intentionally write wrong database connection information in the configuration file, such as password write error

2. Execute SQL Error

The final explanation: the configuration directory, log directory is not want the browser directly access, so you need to put the. htaccess file in the directory (because the app directory already exists, it can also be omitted)

Submit Transfer Code

git add-agit commit-m "complete log class" Git checkout mastergit merge Start-admin-modulegit push Origin master

Summary: This article mainly realizes the framework clean-up, the Blog database table constructs, creates the configuration reads the class, the log record class.

In fact, this is still just a bit more complete frame structure, adding 2 functions. As mentioned in the previous article, there are many improvements that can be made. This will not continue to add functionality for the time being.

Ask questions:

1. How to use the self-made framework to build a project ==> user operation +MVC Implementation

2. How to get started using Ajax for background login ==> AJAX Applications

3. How to get started to implement the classification module function, what is the operation ==> adding and deleting

Next: Background template view production, background login, the article classification module function.

The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.