解析yii数据库的增删查改
1. 存取数据库方法
存储第一种
存表时候用到
例子:
复制代码 代码如下:
$post=new Post;
$post->title='samplepost';
$post->content='content for thesample post';
$post->createTime=time();/$post->createTime=newCDbexpression_r('NOW()');
$post->save();
$user_field_data= new user_field_data;
$user_field_data->flag=0;
$user_field_data->user_id=$profile->id;
$user_field_data->field_id=$_POST['emailhiden'];
$user_field_data->value1=$_POST['email'];
$user_field_data->save();
注当一个表存储4次的时候,需要创建4个handle new4次
存储第二种
存储后我们需要找到这条记录的流水id 这样做 $profile = new profile;$profile->id;
存储第三种
用于更加安全的方法,来绑定变量类型 这样可以在同一个表中存储两个记录
复制代码 代码如下:
$sql="insert intouser_field_data(user_id,field_id,flag,value1)values(:user_id,:field_id,:flag,:value1);";
$command=user_field_data::model()->dbConnection->createCommand($sql);
$command->bindParam(":user_id",$profile->id,PDO::PARAM_INT);
$command->bindParam(":field_id",$_POST['firstnamehiden'],PDO::PARAM_INT);
$command->bindParam(":flag",$tmpflag,PDO::PARAM_INT);
$command->bindParam(":value1",$_POST['firstname'],PDO::PARAM_STR);
$command->execute();
$command->bindParam(":user_id",$profile->id,PDO::PARAM_INT);
$command->bindParam(":field_id",$_POST['emailhiden'],PDO::PARAM_INT);
$command->bindParam(":flag",$tmpflag,PDO::PARAM_INT);
$command->bindParam(":value1",$_POST['email'],PDO::PARAM_STR);
$rowchange =$command->execute();
if( $rowchange != 0){ 修改成功 }//用来判断
注:update delete都可以用这个方法
$sql="delete from profile whereid=:id";
$command=profile::model()->dbConnection->createCommand($sql);
$command->bindParam(":id",$userid,PDO::PARAM_INT);
$this->rowflag=$command->execute();
$sql="update profile setpass=:pass,role=:role where id=:id";
$command=profile::model()->dbConnection->createCommand($sql);
$command->bindParam(":pass",$password,PDO::PARAM_STR);
$command->bindParam(":role",$role,PDO::PARAM_INT);
$command->bindParam(":id",$userid,PDO::PARAM_INT);
$this->rowflag=$command->execute();
// 同理变更updateAll()模式
$sql="update user_field_data set flag =:flag where user_id= :user_id and field_id= :field_id ";
原始sql语句
$criteria = newCDbCriteria;
$criteria->condition ='user_id = :user_id and field_id= :field_id';
$criteria->params =array(':user_id' => $userid,':field_id'=> $fieldid);
$arrupdate = array('flag'=> $flag);
if(user_field_data::model()->updateAll($arrupdate,$criteria)!= 0)
{
更新成功后。。。
}
第四种更新和存储应用同一个handle 流程:
先查询记录是否存在,若存在就更新,不存在就新创建
注:1.第一次查询的变量,要跟save()前的变量一致。2.存储时候需要再次 new一下库对象
复制代码 代码如下:
$user_field_data =user_field_data::model()->findByAttributes(
$attributes = array('user_id'=>Yii::app()->user->user_id, 'field_id'=> $key));
if($user_field_data !== null)
{
$user_field_data->value1= $value;
$user_field_data->save();
}
else
{
$user_field_data= new user_field_data;
$user_field_data->user_id= Yii::app()->user->user_id;
$user_field_data->field_id= $key;
$user_field_data->value1= $value;
$user_field_data->save();
}
查询
注:当项目没查找到整个对象会为空需要这样判定
复制代码 代码如下:
if($rows !== null) 当对象不为空
{
returntrue;
}else{
returnfalse;
}
SELECT
读表时候用到
例子:
第一种find()
复制代码 代码如下:
// find thefirst row satisfying the specified condition
$post=Post::model()->find($condition,$params);
// find the row with postID=10
$post=Post::model()->find('postID=:postID',array(':postID'=>10));
同样的语句,用另种方式表示
$criteria=new CDbCriteria;
$criteria->select='title';// only select the 'title' column
$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);
$post=Post::model()->find($criteria);// $params is not needed
第二种find()
复制代码 代码如下:
$post=Post::model()->find(array(
'select'=>'title',
'condition'=>'postID=:postID',
'params'=>array(':postID'=>10),
));
// find the row with the specified primarykey
$post=Post::model()->findByPk($postID,$condition,$params);
// find the row with the specified attributevalues
$post=Post::model()->findByAttributes($attributes,$condition,$params);
示例:
第一种findByAttributes()
$checkuser= user_field_data::model()->findByAttributes(
array('user_id' =>Yii::app()->user->user_id, 'field_id'=> $fieldid));
第二种findByAttributes()
$checkuser =user_field_data::model()->findByAttributes(
$attributes = array('user_id'=>Yii::app()->user->user_id, 'field_id'=> $fieldid));
第三种当没有conditions时候,不用params
$user_field_data=user_field_data::model()->findAllByAttributes(
$attributes = array('user_id'=> ':user_id'),
$condition = "field_id in(:fields)",
$params = array(':user_id'=>Yii::app()->user->user_id, ':fields'=> "$rule->dep_fields"));
// find the first row using the specified SQLstatement
$post=Post::model()->findBySql($sql,$params);
例子
user_field_data::model()->findBySql("selectid from user_field_data where user_id = :user_id and field_id =:field_id ", array(':user_id' =>$userid,':field_id'=>$fieldid));
此时回传的是一个对象
第四种 添加其他条件
http://www.yiiframework.com/doc/api/CDbCriteria#limit-detail
$criteria = newCDbCriteria;
$criteria->select='newtime';//选择只显示哪几个字段要与库中名字相同,但是不能COUNT(newtime) as name这样写
$criteria->join = 'LEFT JOINPost ON Post.id=Date.id';//1.先要在relation函数中增加与Post表的关系语句2.Date::model()->with('post')->findAll($criteria)
$criteria->group ='newtime';
$criteria->limit = 2; //都是从0开始,选取几个
$criteria->offset = 2;// 从哪个偏移量开始
print_r(Date::model()->findAll($criteria));
得到行数目或者其他数目 count
// get the number of rows satisfying thespecified condition
$n=Post::model()->count($condition,$params);
// get the number of rows using the specifiedSQL statement
$n=Post::model()->countBySql($sql,$params);
// check if there is at least a row satisfyingthe specified condition
$exists=Post::model()->exists($condition,$params);
UPDATE
例子:
复制代码 代码如下:
$post=Post::model()->findByPk(10);
$post->title='new posttitle';
$post->save(); // save thechange to database
// update the rows matching the specifiedcondition
Post::model()->updateAll($attributes,$condition,$params);
例子:或者参考上面例子
复制代码 代码如下:
$c=new CDbCriteria;
$c->condition='something=1';
$c->limit=10;
$a=array('name'=>'NewName');
Post::model()->updateAll($a,$c);
// update the rows matching the specifiedcondition and primary key(s)
Post::model()->updateByPk($pk,$attributes,$condition,$params);
例子
复制代码 代码如下:
$profile =profile::model()->updateByPk(
Yii::app()->user->user_id,
$attributes = array('pass' =>md5($_POST['password']), 'role' => 1));
// update counter columns in the rowssatisfying the specified conditions
Post::model()->updateCounters($counters,$condition,$params);
DELETE
例子:
复制代码 代码如下:
$post=Post::model()->findByPk(10);// assuming there is a post whose ID is 10
$post->delete(); // delete therow from the database table
// delete the rows matching the specifiedcondition
Post::model()->deleteAll($condition,$params);
// delete the rows matching the specifiedcondition and primary key(s)
Post::model()->deleteByPk($pk,$condition,$params);
COMPARE
目前可以取出的
1.//$allquestion=field::model()->findAllBySql("selectlabel from field where step_id = :time1 ", array(':time1'=>1));
2. //$criteria=new CDbCriteria;
//$criteria->select='label,options';
//$criteria->condition='step_id=:postID';
//$criteria->params=array(':postID'=>1);
//$allquestion=field::model()->findAll($criteria);
//$allquestion=field::model()->find("",array("label"));
可以与在models文件夹中的 库连接文件relations()函数合用,这样可以联合查询
$criteria=newCDbCriteria;
$criteria->condition='field.step_id=1';
$this->_post=field::model()->with('step')->findAll($criteria);
这样出来的数组里面包含step表中的值,且这个值的条件为step.id=field.step_id
public functionrelations()
{
return array(
'step'=>array(self::BELONGS_TO,'step', 'step_id'),
);
}

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック









残念ながら、WeChat は広く使用されているソーシャル ソフトウェアであり、何らかの理由で特定の連絡先を誤って削除してしまうことがよくあります。ユーザーがこの問題を解決できるように、この記事では、削除された連絡先を簡単な方法で取得する方法を紹介します。 1. WeChat の連絡先削除メカニズムを理解します。これにより、削除された連絡先を取得できるようになります。WeChat の連絡先削除メカニズムでは、連絡先がアドレス帳から削除されますが、完全には削除されません。 2. WeChat の組み込みの「連絡先帳復元」機能を使用します。WeChat には、この機能を通じて以前に削除した連絡先をすばやく復元できる「連絡先帳復元」機能が用意されています。 3. WeChat 設定ページに入り、右下隅をクリックし、WeChat アプリケーション「Me」を開き、右上隅にある設定アイコンをクリックして設定ページに入ります。

テクノロジーの発展に伴い、モバイルゲームは人々の生活に欠かせないものになりました。かわいいドラゴンエッグの画像と面白い孵化過程で多くのプレイヤーの注目を集めており、その中でも注目を集めているゲームの一つがモバイル版ドラゴンエッグです。プレイヤーがゲーム内で自分のドラゴンをより適切に育成し成長させることができるように、この記事ではモバイル版でドラゴンの卵を孵化させる方法を紹介します。 1. 適切な種類のドラゴン エッグを選択する プレイヤーは、ゲーム内で提供されるさまざまな種類のドラゴン エッグの属性と能力に基づいて、自分に適したドラゴン エッグの種類を慎重に選択する必要があります。 2. 孵化機のレベルをアップグレードします。プレイヤーはタスクを完了し、小道具を収集することで孵化機のレベルを向上させる必要があります。孵化機のレベルは孵化速度と孵化成功率を決定します。 3. プレイヤーはゲームに参加する必要がある孵化に必要なリソースを収集します。

携帯電話が人々の日常生活において重要なツールになるにつれて、フォント サイズの設定は重要なパーソナライゼーション要件になりました。さまざまなユーザーのニーズを満たすために、この記事では、簡単な操作で携帯電話の使用体験を向上させ、携帯電話のフォントサイズを調整する方法を紹介します。携帯電話のフォント サイズを調整する必要があるのはなぜですか - フォント サイズを調整すると、テキストがより鮮明で読みやすくなります - さまざまな年齢のユーザーの読書ニーズに適しています - フォント サイズを使用すると、視力の悪いユーザーにとって便利です携帯電話システムの設定機能 - システム設定インターフェイスに入る方法 - 設定インターフェイスで「表示」オプションを見つけて入力します。 - 「フォント サイズ」オプションを見つけて、サードパーティでフォント サイズを調整します。アプリケーション - フォント サイズの調整をサポートするアプリケーションをダウンロードしてインストールします - アプリケーションを開いて、関連する設定インターフェイスに入ります - 個人に応じて

スマートフォンの普及に伴い、携帯フィルムは欠かせないアクセサリーの一つとなりました。耐用年数を延ばすには、携帯電話の画面を保護する適切な携帯電話フィルムを選択してください。この記事では、読者が自分に最適な携帯電話フィルムを選択できるように、携帯電話フィルムを購入する際のいくつかのポイントとテクニックを紹介します。携帯電話フィルムの素材と種類を理解する:PET フィルム、TPU など。 携帯電話フィルムは強化ガラスを含むさまざまな素材でできています。 PETフィルムは比較的柔らかく、強化ガラスフィルムは耐傷性に優れ、TPUは耐衝撃性能に優れています。選択する際は、個人の好みやニーズに基づいて決定できます。画面の保護の程度を考慮してください。携帯電話のフィルムの種類によって、画面の保護の程度も異なります。 PETフィルムは主に傷防止の役割を果たしますが、強化ガラスフィルムは落下耐性に優れています。より良いものを選ぶことができます

Apple の最新リリースの iOS18、iPadOS18、および macOS Sequoia システムでは、さまざまな理由で紛失または破損した写真やビデオをユーザーが簡単に回復できるように設計された重要な機能が写真アプリケーションに追加されました。この新機能では、写真アプリのツール セクションに「Recovered」というアルバムが導入され、ユーザーがデバイス上に写真ライブラリに含まれていない写真やビデオがある場合に自動的に表示されます。 「Recovered」アルバムの登場により、データベースの破損、カメラ アプリケーションが写真ライブラリに正しく保存されない、または写真ライブラリを管理するサードパーティ アプリケーションによって失われた写真やビデオに対する解決策が提供されます。ユーザーはいくつかの簡単な手順を実行するだけで済みます

2023 年 3 月 14 日に ChatGLM-6B が発売されて以来、GLM シリーズ モデルは幅広い注目と認知を得てきました。特にChatGLM3-6Bがオープンソース化されてからは、Zhipu AIが投入する第4世代モデルに対する開発者の期待が高まっている。 GLM-4-9B のリリースにより、この期待はついに完全に満たされました。 GLM-4-9B の誕生 小型モデル (10B 以下) により強力な機能を提供するために、GLM 技術チームはこの新しい第 4 世代 GLM シリーズ オープン ソース モデル、GLM-4-9B をほぼ半年の期間を経て発売しました。探検。このモデルは、精度を確保しながらモデルサイズを大幅に圧縮し、推論速度の高速化と効率化を実現しています。 GLM 技術チームの調査はまだ終わっていない

MySQLi を使用して PHP でデータベース接続を確立する方法: MySQLi 拡張機能を含める (require_once) 接続関数を作成する (functionconnect_to_db) 接続関数を呼び出す ($conn=connect_to_db()) クエリを実行する ($result=$conn->query()) 閉じる接続 ( $conn->close())

すべてを覆す大きなモデルが、ついに編集者の頭にたどり着いた。たった一文でできたエージェントでもあります。このように、彼に記事を与えると、1 秒以内に新鮮なタイトルの候補が出てきます。私と比較すると、この効率は稲妻のように速く、ナマケモノのように遅いとしか言いようがありません... さらに驚くべきことに、このエージェントの作成には実際には数分しかかからないということです。プロンプトは江おばさんのものです。そして、この破壊的な感覚も体験したい場合は、百度が立ち上げた新しいウェンシン インテリジェント エージェント プラットフォームに基づいて、誰でも無料で独自のインテリジェント アシスタントを作成できます。検索エンジン、スマート ハードウェア プラットフォーム、音声認識、地図、自動車、その他の Baidu モバイル エコロジー チャネルを使用して、より多くの人があなたの創造性を活用できるようにすることができます。ロビン・リー自身
