Yii2-05 How to manipulate a database

Source: Internet
Author: User
Tags yii
Preparing the database
DROP TABLE IF EXISTS ' pre_user ';
CREATE TABLE ' pre_user ' (
    ' id ' int () auto_increment PRIMARY KEY,
    ' username ' varchar (255) Not  NULL,
    '  Password ' varchar NOT null default ',
    ' password_hash ' varchar (255) NOT null default ',
    ' email ' varchar (255) Not null default ',
    ' status ' smallint (6) is not null default,
    ' Created_at ' smallint (6) is not NULL default 0,
    ' Updated_at ' smallint (6) not NULL default 0
) engine=innodb default charset=utf8mb4;
Configuring Connections

config\db.php

<?php return

[
    ' class ' => ' yii\db\connection ',
    ' DSN ' => ' Mysql:host=localhost;dbname=yii2 ',
    ' username ' => ' root ', '
    password ' => ' root ',
    ' charset '
    => ' utf8mb4 ', ' Tableprefix ' => ' Pre_ '
];

To see if the database connection was successful
In the controller print:

Var_dump (\yii:: $app->db);

How to execute the SQL statement.

Delete and change

Receive the data for the form
 $username = ' Jack ';

 $sql = "INSERT into {{%user}}} (Username,status) VALUES (: Username,:status)";

 Returns the number of affected rows
 $row = \yii:: $app->db->createcommand ($sql, [' username ' => $username, ' status ' =>8])-> Execute ();

 Get the self-increasing ID
 echo \yii:: $app->db->getlastinsertid ();

Inquire

$sql = "Select * FROM {%user}} WHERE id>:id";

The query result is a two-dimensional array
$USERARR = \yii:: $app->db->createcommand ($sql, [' ID ' =>1])->queryall ();


If you are querying a
$user = \yii:: $app->db->createcommand ($sql, [' ID ' =>1])->queryone ();

If you want to return a single value
//For example, select COUNT (*) statement
$count = \yii:: $app->db->createcommand ($sql, [' ID ' =>1])-> Queryscalar ();

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.