Home PHP Framework ThinkPHP How to connect data with thinkphp

How to connect data with thinkphp

May 26, 2023 am 09:04 AM

ThinkPHP is an open source Web framework written in PHP, which is easy to learn, efficient, fast, safe and stable. When developing with ThinkPHP, you need to connect to a database to store and manage data. This article will introduce how to connect to the database and perform basic operations.

1. Configure database connection information

In ThinkPHP, you need to configure the database connection information in the public configuration file config.php. In the config.php file, find the following code:

//数据库类型
'DB_TYPE'   => 'mysql',
//服务器地址
'DB_HOST'   => 'localhost',
//数据库名
'DB_NAME'   => 'thinkphp',
//用户名
'DB_USER'   => 'root',
//密码
'DB_PWD'    => 'root',
//端口
'DB_PORT'   => '3306',
//表前缀
'DB_PREFIX' => 'think_',
Copy after login

Among them, DB_TYPE is the database type, which currently supports mysql, mysqli, PDO and other types; DB_HOST is the database server address, which can be an IP address or domain name; DB_NAME is the database name, which needs to be created before connecting; DB_USER and DB_PWD are the user name and password of the database respectively, which require permission to access the database; DB_PORT is the port for database connection, the default is 3306; DB_PREFIX is the data table prefix, used for multiple Avoid table name conflicts when two applications share a database.

2. Connect to the database

After completing the configuration of the database connection information, you can connect to the database by instantiating a database object. In ThinkPHP, use the Db class to connect and operate the database. For example:

use thinkDb;

// 连接数据库
$conn = Db::connect();
Copy after login

If you need to specify the database configuration of the connection, you can pass an array parameter in the connect method, and the array contains the database connection information. For example:

$config = [
    //数据库类型
    'type'     => 'mysql',
    //服务器地址
    'hostname' => 'localhost',
    //数据库名
    'database' => 'thinkphp',
    //用户名
    'username' => 'root',
    //密码
    'password' => 'root',
    //端口
    'hostport' => '',
    //表前缀
    'prefix'   => 'think_',
];

// 连接数据库
$conn = Db::connect($config);
Copy after login

3. Database operations

After connecting to the database, you can perform database operations, including queries, inserts, updates, and deletes. The following takes the query operation as an example for explanation.

  1. Query a record

Use the query method to query a record, for example:

// 查询一条记录
$record = $conn->query('select * from think_user limit 1');
Copy after login

The query method returns a PDOStatement object, which can be used through the fetch method Get a record.

// 获取查询结果
$row = $record->fetch(PDO::FETCH_ASSOC);
Copy after login
  1. Query multiple records

Use the select method to query multiple records, for example:

// 查询多条记录
$list = $conn->table('think_user')->select();
Copy after login

The table method is used to set the data for the operation Table, select method is used to obtain multiple records.

  1. Conditional query

You can set query conditions through the where method, for example:

// 条件查询
$list = $conn->table('think_user')->where('id', '=', 1)->select();
Copy after login

Among them, the where method receives three parameters, which are field names. , comparison operators and values, multiple conditional queries can be implemented through chain operations. For example:

// 多条件查询
$list = $conn->table('think_user')
                ->where('id', '=', 1)
                ->where('status', '=', 1)
                ->select();
Copy after login
  1. Insert record

Use the insert method to insert a record, for example:

// 插入记录
$data = [
    'username' => 'admin',
    'password' => md5('123456'),
    'status'   => 1,
];
$result = $conn->table('think_user')->insert($data);
Copy after login

The insert method receives an array parameter, in the array Contains field names and corresponding values.

  1. Update records

Use the update method to update records, for example:

// 更新记录
$data = ['status' => 0];
$result = $conn->table('think_user')
                ->where('id', '=', 1)
                ->update($data);
Copy after login

The update method receives an array parameter, and the array contains the Field name and corresponding value.

  1. Delete records

Use the delete method to delete records, for example:

// 删除记录
$result = $conn->table('think_user')
                ->where('id', '=', 1)
                ->delete();
Copy after login

Among them, the delete method can delete multiple records that meet the conditions and does not pass Conditional parameters will clear the entire table.

4. Summary

Through the above steps, you can successfully connect to the database and perform basic query, insert, update and delete operations. When developing with ThinkPHP, you need to frequently deal with the database, so it is very important to be proficient in database operations. At the same time, you need to pay attention to security issues such as SQL injection when operating, and use parameter binding and other methods as much as possible to avoid risks.

The above is the detailed content of How to connect data with thinkphp. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between think book and thinkpad What is the difference between think book and thinkpad Mar 06, 2025 pm 02:16 PM

This article compares Lenovo's ThinkBook and ThinkPad laptop lines. ThinkPads prioritize durability and performance for professionals, while ThinkBooks offer a stylish, affordable option for everyday use. The key differences lie in build quality, p

How to prevent SQL injection tutorial How to prevent SQL injection tutorial Mar 06, 2025 pm 02:10 PM

This article explains how to prevent SQL injection in ThinkPHP applications. It emphasizes using parameterized queries via ThinkPHP's query builder, avoiding direct SQL concatenation, and implementing robust input validation & sanitization. Ad

How to deal with thinkphp vulnerability? How to deal with thinkphp vulnerability How to deal with thinkphp vulnerability? How to deal with thinkphp vulnerability Mar 06, 2025 pm 02:08 PM

This article addresses ThinkPHP vulnerabilities, emphasizing patching, prevention, and monitoring. It details handling specific vulnerabilities via updates, security patches, and code remediation. Proactive measures like secure configuration, input

How to install the software developed by thinkphp How to install the tutorial How to install the software developed by thinkphp How to install the tutorial Mar 06, 2025 pm 02:09 PM

This article details ThinkPHP software installation, covering steps like downloading, extraction, database configuration, and permission verification. It addresses system requirements (PHP version, web server, database, extensions), common installat

How to fix thinkphp vulnerability How to deal with thinkphp vulnerability How to fix thinkphp vulnerability How to deal with thinkphp vulnerability Mar 06, 2025 pm 02:04 PM

This tutorial addresses common ThinkPHP vulnerabilities. It emphasizes regular updates, security scanners (RIPS, SonarQube, Snyk), manual code review, and penetration testing for identification and remediation. Preventative measures include secure

How to use thinkphp tutorial How to use thinkphp tutorial Mar 06, 2025 pm 02:11 PM

This article introduces ThinkPHP, a free, open-source PHP framework. It details ThinkPHP's MVC architecture, features (routing, database interaction), advantages (rapid development, ease of use), and disadvantages (potential over-engineering, commun

Detailed steps for how to connect to the database by thinkphp Detailed steps for how to connect to the database by thinkphp Mar 06, 2025 pm 02:06 PM

This guide details database connection in ThinkPHP, focusing on configuration via database.php. It uses PDO and allows for ORM or direct SQL interaction. The guide covers troubleshooting common connection errors, managing multiple connections, en

How can I use ThinkPHP to build command-line applications? How can I use ThinkPHP to build command-line applications? Mar 12, 2025 pm 05:48 PM

This article demonstrates building command-line applications (CLIs) using ThinkPHP's CLI capabilities. It emphasizes best practices like modular design, dependency injection, and robust error handling, while highlighting common pitfalls such as insu

See all articles