The thinkphp contains an abstract database access layer, which encapsulates different database operations. We only need to use
The common Db class operates without the need to write different code and underlying implementations for different databases. The Db class is automatically called
The corresponding database driver to handle.
One, global configuration definition
In the common/conf/config.php
// Database Type // Server Address // Database name // User name // Password // Port // database table prefix because the data table name established is Think_user
In the home/controller/usercontroller.calss.php
<?PHPnamespace Home\controller; UseThink\controller; Usethink\model;//loading the database moduleclassUsercontrollerextendsController { Public functionmodel () { $user=NewModel (' User ');//user Best Capitalization
Var_dump($user -Select ()); Select is the data in the selected data table
}
}
Second, thePDO special definition
In the common/conf/config.php
' Db_type ' = ' pdo ', ' db_user ' = ' root ', ' db_pwd ' and ' 123456 ', ' db_prefix ' and ' think_ ', ' db_dsn ' = ' Mysql:host=localhost;dbname=thinkphp;charset=utf8 ',
Unchanged in home/controller/usercontroller.calss.php
Third, write directly in home/controller/usercontroller.calss.php , do not need to insert any code in common/conf/config.php
<?PHPnamespace Home\controller; UseThink\controller;Use think\model; classUsercontrollerextendsController { Public functionmodel () { $user=NewModel (' User ', ' think_ ', ' mysql://root:[email protected]/thinkphp ');//u in user recommended capitalization Var_dump($user-Select ()); }}
The last point is that the $user within the Model () function = new Model (' user ') and can be replaced with $user = M (' user '); At this time, do not refer to use Think\model;
Three ways to call a database