Page 1 of 1

[Yii 1] Data Access Objects (DAO)

Posted: Fri Feb 17, 2017 9:45 am
by tthlan
Tạo kết nối riêng
với sqlite, mysql, sqlserver, ...

Code: Select all

	$dns = 'sqlite:protected/data/testdrive.db';
        $username = '';
        $password = '';

        $connection = new CDbConnection($dns, $username, $password);
        $connection->active=true;

        // ... Command codes ...
        
        // Close connection
        $connection->active=false;
Nếu dùng chung kết nối của main.php: Yii:app()

Code: Select all

$connection=Yii::app()->db;
Command truy vấn với tham số
Phải BindParam bằng biến để truyền tham chiếu chứ ko bindParam sẽ error "Fatal error: Cannot pass parameter 2 by reference"

Code: Select all

/* Build command query with parameter */
        /*$command2=$connection->createCommand("select * From tbl_user where username like :username");
        $username = '%' . 'test1' . '%';
        $command2->bindParam(":username",$username, PDO::PARAM_STR);
        $dataReader2=$command2->query();

        $i=1;
        foreach($dataReader2 as $row) {
            foreach($row as $key=>$value)
                var_dump($key,$value);

            $i++;
        }
Command thực thi truy vấn thêm mới với tham số

Code: Select all

 /* Insert query */
        //$sql="INSERT INTO tbl_user (id, username, email, password) VALUES(22,'lan','lan@g.com','12345')";

        $sql="INSERT INTO tbl_user (id, username, email, password) VALUES(:id, :username, :email, :password)";
        $command2=$connection->createCommand($sql);

        // Should to use variable to input for paramaters
        $id = 23;
        $username = 'hlanart';
        $email = 'hlanart@gmail.com';
        $password = '1223';

        $command2->bindParam(":id",$id, PDO::PARAM_INT);
        $command2->bindParam(":username",$username, PDO::PARAM_STR);
        $command2->bindParam(":email",$email,PDO::PARAM_STR);
        $command2->bindParam(":password", $password,PDO::PARAM_STR);

        $command2->execute();*/
Command truy vấn xóa dữ liệu

Code: Select all

 /* Delete query */
        $sqlDelete = 'Delete from tbl_user where id=23';
        $commandDelete=$connection->createCommand($sqlDelete);
        $commandDelete->execute();
Command truy vấn dự liệu và đọc xuất dữ liệu

Code: Select all

 /* Build command with select query */
        $sql = "select * from tbl_user";
        $command=$connection->createCommand($sql);

        $dataReader=$command->query();

        $i=0;
        foreach($dataReader as $row) {
            foreach($row as $key=>$value)
                var_dump($key,$value);

            $i++;
        }
        var_dump($i);
Enjoy !