Home > Article > PHP Framework > How to connect thinkphp to the database
First open Zend to create a project and import our ThinkPHP.
Enter http://1270.0.1/text01 in the browser address bar and run the ThinkPHP project, you can see Think’s smiling face.
Related recommendations: "ThinkPHP Tutorial"
Create a database Create a user table for the database connection of our entire project , test whether the database is connected.
Open the project refresh and view the generated directory structure. Application->Common->Conf is the public configuration file directory of the project. You can see that there is a config under Conf. .php file, "Public Configuration File Directory" can be seen that this directory is a common directory for the front and backend. If the front and backend use a database to directly configure a database connection in the public directory, it can be used by both the front and backend. It can be used under config.php Write all public configuration files.
ThinkPHP has a built-in abstract database access layer that encapsulates different database operations. We only need to use the public Db class to operate without having to write different databases for different databases. The code and underlying implementation, the Db class will automatically call the corresponding database driver to process. Current databases include Mysql, SqlServer, PgSQL, Sqlite, Oracle, Ibase, Mongo, and support for PDO.
We have taken the mysql database as an example:
'DB_TYPE' => 'mysql', // 数据库类型我们是mysql,就对于的是mysql 'DB_HOST' => '127.0.0.1', // 服务器地址,就是我们配置好的php服务器地址,也可以使用localhost, 'DB_NAME' => 'text', // 数据库名:mysq创建的要连接我们项目的数据库名称 'DB_USER' => 'root', // 用户名:mysql数据库的名称 'DB_PWD' => '', //mysql数据库的 密码 'DB_PORT' => 3306, // 端口服务端口一般选3306 'DB_PREFIX' => 'tp_', // 数据库表前缀 'DB_CHARSET'=> 'utf8', // 字符集 'DB_DEBUG' => TRUE, // 数据库调试模式 开启后可以记录SQL日志 3.2.3新增
The database has been successfully connected. Try to see if you can access the database correctly. Open the project Home->Controller ->IndexController.class.php
public function index(){ $user=M('User'); //大M方法访问数据表 $sql=$user->select(); //thinkPHP 封装的SQL查询所有数据 var_dump($sql); //打印出数据 }
Enter http://1270.0.1/text01 in the browser address bar and run the ThinkPHP project to see if the data is printed out. The test is successful. .
The above is the detailed content of How to connect thinkphp to the database. For more information, please follow other related articles on the PHP Chinese website!