search
HomeBackend DevelopmentPHP TutorialHow to link to database through ThinkPHP

How to link to database through ThinkPHP

Jun 15, 2018 am 11:30 AM
thinkphp

Make the following configuration in the configuration file to connect to the database

<?php
return array(
   //&#39;配置项&#39;=>&#39;配置值&#39;
    &#39;DB_TYPE&#39;               =>  &#39;mysql&#39;,     // 数据库类型
    &#39;DB_HOST&#39;               =>  &#39;localhost&#39;, // 服务器地址
    &#39;DB_NAME&#39;               =>  &#39;shop&#39;,          // 数据库名
    &#39;DB_USER&#39;               =>  &#39;root&#39;,      // 用户名
    &#39;DB_PWD&#39;                =>  &#39;123&#39;,          // 密码
    &#39;DB_PORT&#39;               =>  &#39;3306&#39;,        // 端口
    &#39;DB_PREFIX&#39;             =>  &#39;sw_&#39;,    // 数据库表前缀
);

CreateModelModel

Cut the 'Home/Model' folder to the Application folder, and let Home and Admin are used together.

My database indicates that it is goods. First, create a model class with the same name as the database

GoodsModel.class.php# Methods for instantiating models in ##

<?php
namespace Model;
use Think\Model;
class GoodsModel extends Model{
}

controller

:

First method:

Define a controller(GoodsController)To call thisGoodsModel class

<?php
namespace Admin\Controller;
use Model\GoodsModel;
use Think\Controller;
class GoodsController extends Controller{
    public function test1(){
        $goods = new GoodsModel();
        echo &#39;<pre class="brush:php;toolbar:false">&#39;;
        var_dump($goods);
    }
}

Second type:

Use M function for instantiation:

<?php
namespace Admin\Controller;
use Model\GoodsModel;
use Think\Controller;
class GoodsController extends Controller{
    public function test1(){
        $goods = M(&#39;goods&#39;);
        echo &#39;<pre class="brush:php;toolbar:false">&#39;;
        var_dump($goods);
    }
}

Third type:

Use Dfunction

<?php
namespace Admin\Controller;
use Model\GoodsModel;
use Think\Controller;
class GoodsController extends Controller{
    public function test1(){
        $goods = D(&#39;goods&#39;);
        echo &#39;<pre class="brush:php;toolbar:false">&#39;;
        var_dump($goods);
    }
}

M

method is the same as Dmethod

M()

Similar to new Model()

D()

Similar tonew GoodsModel()

Tips: You can see the information of the goods table. There is no code written in the model. All business logic is implemented by the Model class

Operations on tables

Add: M('Table name')-> ;add($date);

Delete:M('Table name')->delete($id);

Update: M('Table name')->save($date);

Query: M('Table Name')->select();

Normal query (display all products)

Code in GoodsController

:

<?php
namespace Admin\Controller;
use Model\GoodsModel;
use Think\Controller;
class GoodsController extends Controller{
    public function showlist(){
        $list = M(&#39;goods&#39;)->select();
        $this->assign(&#39;list&#39;, $list);
        $this->display();
    }
}

Remove from the template

<volist name="list" id="vo" >
<tr id="product1">
    <td>{$i}</td>
    <td><a href="#">{$vo.goods_name}</a></td>
    <td>{$vo.goods_number}</td>
    <td>{$vo.goods_price}</td>
    <td><img  src="/static/imghwm/default1.png"  data-src="../../../Application/Admin/Public/img/20121018-174034-58977.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to link to database through ThinkPHP" ></td>
    <td><img  src="/static/imghwm/default1.png"  data-src="../../../Application/Admin/Public/img/20121018-174034-97960.jpg"  class="lazy"      style="max-width:90%"  style="max-width:90%" alt="How to link to database through ThinkPHP" ></td>
    <td>{$vo.goods_brand_id}</td>
    <td>{$vo.goods_create_time}</td>
    <td><a href="#">修改</a></td>
    <td><a href="javascript:;" onclick="delete_product(1)">删除</a></td>
</tr>
</volist>

This article explains how to connect to the database through ThinkPHP. For more related content, please pay attention to the php Chinese website.

Related recommendations:

How to connect multiple databases through thinkphp

##About ThinkPHP 5. Some basic operations of the database


Thinkphp5 rules for adding different data

The above is the detailed content of How to link to database through ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools