>

类似jq的即点即改,操作数据库的三种方式

- 编辑:正版管家婆马报彩图 -

类似jq的即点即改,操作数据库的三种方式

Getting data from a database
Most applications today use databases. Be it a small website or a social network, at least some parts are powered by databases. Yii introduces three ways which allow you to work with databases:
Active Record
Query builder
SQL via DAO

<?php

 代码如下

namespace appcontrollers;

<?php
class DbController extends Controller
{
    protected function afterAction($action)
    {
        $time = sprintf('%0.5f', Yii::getLogger()->getExecutionTime());
        $memory = round(memory_get_peak_usage()/(1024*1024),2)."MB";
        echo "Time: $time, memory: $memory";
        parent::afterAction($action);
    }
 
    public function actionAr()
    {
        $actors = Actor::model()->findAll(array('with' => 'films',
                'order' => 't.first_name, t.last_name, films.title'));
        echo '<ol>';
        foreach($actors as $actor)
        {
            echo '<li>';
            echo $actor->first_name.' '.$actor->last_name;
            echo '<ol>';
            foreach($actor->films as $film)
            {
                echo '<li>';
                echo $film->title;
                echo '</li>';
            }
            echo '</ol>';
            echo '</li>';
        }
        echo '</ol>';
    }
 
    public function actionQueryBuilder()
    {
        $rows = Yii::app()->db->createCommand()
                ->from('actor')
                ->join('film_actor', 'actor.actor_id=film_actor.actor_id')
                ->leftJoin('film', 'film.film_id=film_actor.film_id')
                ->order('actor.first_name, actor.last_name, film.title')
                ->queryAll();
        $this->renderRows($rows);
    }
 
    public function actionSql()
    {
        $sql = "SELECT * FROM actor a
             JOIN film_actor fa ON fa.actor_id = a.actor_id
             JOIN film f ON fa.film_id = f.film_id
             ORDER BY a.first_name, a.last_name, f.title";
        $rows = Yii::app()->db->createCommand($sql)->queryAll();
        $this->renderRows($rows);
    }
 
    public function renderRows($rows)
    {
        $lastActorName = null;
        echo '<ol>';
        foreach($rows as $row)
        {
            $actorName = $row['first_name'].' '.$row['last_name'];
            if($actorName!=$lastActorName){
                if($lastActorName!==null){
                    echo '</ol>';
                    echo '</li>';
                }
                $lastActorName = $actorName;
                echo '<li>';
                echo $actorName;
                echo '<ol>';
            }
            echo '<li>';
            echo $row['title'];
            echo '</li>';
        }
        echo '</ol>';
    }
}

use Yii;
use yiifiltersAccessControl;
use yiiwebController;
use yiifiltersVerbFilter;
use yiidataPagination;
use appmodelsUsers;
use appmodelsYuyue;

//留言
class MessController extends Controller
{
public function actionIndex()
{ //开启session
$session = Yii::$app->session;
$session->open();

//查询全体留言
$sql = “select * from message”;
$mess = yii::$app->db->createCommand($sql)->queryAll();

//剖断是不是登陆
$user = $session->get(“user”);
$u_id = $session->get(“u_id”);
if(!isset($user)){
$status = 0;
}else{
$status = 1;

//查询遮蔽的留言
$sql = “select * from dis_mess where u_id=”.$u_id;
$display = yii::$app->db->createCommand($sql)->queryAll();

//将m_id遍历为一维数组
foreach($display as $key =>$val){
$display[$key] = $display[$key][‘m_id’];
}
//抽出隐敝留言的id,有就 删除该变量
foreach($mess as $k=>$v){
if(in_array($mess[$k][‘id’],$display)){
unset($mess[$k]);
}
}

}
// var_dump($mess);die();

return $this->render(“index”,[‘status’=>$status,’user’=>$user,’mess’=>$mess]);
}
//登录
public function actionLogin()
{
return $this->render(“login”);

}

//ajax 隐蔽 反感表
public function actionNot()
{
//开启session
$session = Yii::$app->session;
$session->open();
$u_id = $session->get(“u_id”);

$m_id = Yii::$app->request->get(‘m_id’); //抵触的留言id
// var_dump($u_id);die();
$sql = “insert into dis_mess(u_id,m_id) VALUES (‘$u_id’,’$m_id’)”;
$res = yii::$app->db->createCommand($sql)->query();

if($res){
return 1;
}else{
return 0;
}
}
//加载越来越多
public function actionDuo()
{
//开启session
$session = Yii::$app->session;
$session->open();
$u_id = $session->get(“u_id”);
//全数留言
$sql = “select * from message”;
$arr = yii::$app->db->createCommand($sql)->queryAll();

//查询隐敝的留言
$sql = “select * from dis_mess where u_id=”.$u_id;
$display = yii::$app->db->createCommand($sql)->queryAll();

//将m_id遍历为一维数组
foreach($display as $key =>$val){
$display[$key] = $display[$key][‘m_id’];
}
//抽出遮蔽留言的id,有就 删除该变量
foreach($arr as $k=>$v){
if(in_array($arr[$k][‘id’],$display)){
unset($arr[$k]);
}
}
// var_dump($arr);die();
return json_encode($arr);
}
//验证登陆
//登录
public function actionLogin_check()
{
//接值
$username = Yii::$app->request->post(‘username’);
$pwd = Yii::$app->request->post(‘pwd’);
$sql = “select username,u_id from mess_user where username='”.$username.”‘ and pwd='”.$pwd.”‘”;
$arr = yii::$app->db->createCommand($sql)->queryOne();
// var_dump($arr);die();

if(!$arr){
die(“密码错误”);
}else{
//登入成功
//开启session 存u_id ,user
$session = Yii::$app->session;
$session->open();
$session->set(“user”,$arr[‘username’]);
$session->set(“u_id”,$arr[‘u_id’]);
$this->redirect([‘mess/index’]);
}
}
//增多留言 1:成功
public function actionAdd()
{
//接值
$user = Yii::$app->request->get(‘user’);
$content = Yii::$app->request->get(‘content’);
$time = Yii::$app->request->get(‘time’);
//增多留言
$sql = “insert into message(time,content,username) value(‘$time’,’$content’,’$user’)”;
$res = yii::$app->db->createCommand($sql)->query();

if($res){
return 1;
}else{
return 0;
}
}

}

以上是调节器层

==============================================================

<!doctype html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>留言</title>
</head>
<body>
<center>
<a href=”<?= yiihelpersUrl::to([‘mess/login’]) ?>”><input type=”button” value=”登录”/></a>
<input type=”text” id=”content”/><input type=”button” value=”留言” id=”btn” /><br>
留言内容:<br>

<table border=”1″ id=”table”>
<tbody id=”blog”>
<?php $num=0;?>
<?php foreach($mess as $k=>$v) { ?>
<?php if($num==5){break;} ?>

<tr>
<td><?= $v[‘username’] ?></td>
<td><?= $v[‘content’] ?></td>
</tr>
<tr m_id=”<?= $v[‘id’]?>” class=”tr”>

<td>日期:<?= $v[‘time’] ?></td>
<td><input type=”button” value=”隐藏” class=”yin”/></td>
</tr>
<?php $num++;?>
<?php } ?>
</table>
</tbody>

<input type=”button” value=”更多” id=”btn2″/>
<script src=”./js/jquery.min.js”></script>
<script>
$(function(){
//更多
$(“#btn2″).click(function(){
$.ajax({
url:”<?= yiihelpersUrl::to([‘mess/duo’]) ?>”,
type: “GET”,
success: function(xml){
// alert(xml)
//拼接字符串
obj= $.parseJSON(xml);
var str = new String();
$.each(obj,function(i,n){
//拼接字符串
str+=”<tr>”;
str+=”<td>”+n.username+”</td>”;
str+=”<td>”+n.content+”</td>”;
str+=”</tr>”;
str+=”<tr m_id='”+n.id+”‘ >”;
str+=”<td>日期:”+n.time+”</td>”;
str+=”<td><input type=’button’ value=’隐藏’ class=’yin’/></td>”;
str+=”</tr>”;
})
$(“#table”).append(str);
$(“#btn2”).css(“display”,”none”);//隐藏越多开关
}
})
})
//隐蔽 难点:追加的tr触发不了点击事件
//bind live on delegate
$(“#blog”).delegate(“.yin”,”click”,function(){
// alert(“隐藏”);
var m_id = $(this).parent().parent().attr(“m_id”); //获取到id
var obj = $(this).parent().parent();

$.ajax({
url : “<?= yiihelpersUrl::to([‘mess/not’]) ?>”,
type: “GET”,
data: “m_id=”+m_id,
success: function (msg) {
// alert(msg)
if(msg==1){
//遮蔽成功 注意移除的次第,当先杀当前变量时,当前的小伙子节点就能够找不到
obj.prev().remove();
obj.remove();
}
}
})

})

//点击留言
$(“#btn”).click(function(){
//检查实验是还是不是登陆
var status =”<?= $status ?>”;

//未登入时
if(status==0){
alert(“请登录”);
$(“#btn”).attr(“disabled”,”true”)
}
//留言
time =”<?= date(‘Y/m/d’,time()) ?>”;
content =$(“#content”).val();
user = “<?php echo $user ?>”;
$.ajax({
url:”<?= yiihelpersUrl::to([‘mess/add’]) ?>”,
type: “GET”,
data: “time=”+time+”&content=”+content+”&user=”+user,
success: function(msg){
//留言成功时
if(msg==1){
//拼接字符串
var str = new String();
str+=”<tr>”;
str+=”<td>”+user+”</td>”;
str+=”<td>”+content+”</td>”;
str+=”</tr>”;
str+=”<tr>”;
str+=”<td>日期:”+time+”</td>”;
str+=”<td><input type=’button’ value=’隐藏’ class=’yin’/></td>”;
str+=”</tr>”;

$(“#table”).append(str);
}
}
})
})

})
</script>

</center>

</body>
</html>

本文由关于计算机发布,转载请注明来源:类似jq的即点即改,操作数据库的三种方式