织梦自定义模型与附加表字段调用方法

想要实现织梦DedeCMS任意位置调用自定义字段,就得先了解DEDECMS自定义字段其实就是添加了个附加的表,要调用附加表的内容有list和arclist两种方法。譬如增加一个自定义字段商品的价格price ①.list调用附加表字段
{dede:list pagesize='5'}
<li><a href="[field:arcurl/]"><img src="[field:litpic/]" /></a><span>[field:price/]</span></li>
{/dede:list}
用list调取自定义字段的时候,一定要注意在后台建立字段的时候,前台参数那里的“使字段可以在列表的底层模板中获得” ②.arclist调用附加表字段
{dede:arclist row='5' addfields='price' channelid='3'}
<li></a href="[field:arcurl/]"><img src="[field:litpic/]" /></a><span>[field:price/]</span></li>
{/dede:arclist}
要获取附加表内容,必须符合两个条件 1、指定 channelid 属性(内容模型的id值) 2、指定要获得的字段 addfields='字段1,字段' 在文章内容页面,可以直接使用{dede:field.price/}来获得价格的值。 ☞ 拓展:织梦dedecms更新列表页提示Fatal error: Call to a member function GetInnerText() on a non-object in... 这个错误提示会在更新自定义模型栏目列表的时候出现,解决办法如下所示: 打开 /inculde/taglib/channel/img.lib.php文件 找到第51行代码
将$innerTmp = $arcTag->GetInnerText();替换为
  $innerTmp = ($arcTag=="") ? trim($arcTag) : trim($arcTag->GetInnerText());

解决DEDE图集上传图片时跳出302错误

今天在本地上传图集的时候突然提示网页出错,还跳出302错误。以前从来没遇到过,想了半天也没想出是哪里出了错误,郁闷~ 所以就去论坛搜了一下,遇到此类问题的童鞋还真多呢。往下拉了几楼,还是找到了答案。如下: 解决办法是 [php] 在include/userlogin.class.php文件中的session_start();前加上 if (isset($_POST["PHPSESSID"])) { session_id($_POST["PHPSESSID"]); } else if (isset($_GET["PHPSESSID"])) { session_id($_GET["PHPSESSID"]); } [/php] 如此保存后就OK了

织梦dedecms中的{dede:php}标签使用方法

 
{dede:sql}标签的用法 sql标签可以称得上是个万能标签了,查询数据库将其输出,这里介绍一些关于这个标签的用法: 1.用来输出统计内容,这个是不错的,举个例子,我们来统计下总共发了多少的文章,思路就是输出dede_addonarticle这个文章附加表内容总数就可以了。 {dede:sql sql="SELECT COUNT(*) AS nums FROM dede_addonarticle"} [field:name = "nums"/] {/dede:sql} 2.使用~field~来进行特殊的查询,比如之前论坛上面很多会员需要做一个输出当前发布文章会员的相关内容,之前用sql或者arclist标签是没办法实现的,因为每篇内容是不同的,这里我们来用5.5的sql语句来做个示范。 我们首先在文章模板中相应的位置加上下面的标签 {dede:sql sql="SELECT * FROM dede_archives WHERE writer=~writer~"} [field:id/], DEDE模板  {/dede:sql} 这个放到article_article.htm页面,将会检索出当前会员发布的相关文章,这里的~ writer~会根据当前内容的环境变量进行替换后再执行查询。 这里出现在SQL语句中条件查询的~ writer~,也就是$refObj->Fields[$value]这个里面的相关内容 模板中使用PHP 许多人希望织梦的模板标签能够更加灵活,加入可以运行PHP的功能,这里在DedeCMS V5.5中就加入了一个可以执行php的特殊标签{dede:php}{/dede:php},这个标签可以执行PHP语句了。 我这里举几个常用的例子: 1.最简单的输出内容: {dede:php} $numA = 1; $numB = 2; echo $numA + $numB; {/dede:php} 在 {dede:php}里想要输出信息 可以直接使用print , echo 之类的打印出来   赋值给@me 无效 这个输出的内容是计算结果: 3 2.结合SQL查询输出单条内容 {dede:php} $row = $dsql->GetOne('select id,typename from dede_arctype where id=2'); print_r($row); {/dede:php} 这个输出的内容是 Array ( [id] => 2 [typename] => 问答 ) 3.获取当前页面的变量 比如我们这里进入系统后台的[模板]-[全局标记测试],我们在代码中填入下面的内容: {dede:php} print_r($refObj->Fields); {/dede:php} 织梦模板团 在PHP中想要获取dede某个字段值 可以使用 $refObj->Fields 对象来获取 列入获取 title => $refObj->Fields['title'] 如果环境变量保持默认,即“不使用环境ID”,我们会看到以下的结果: Array ( [typeid] => 0 [phpurl] => /plus [indexurl] => / [templeturl] => /templets [memberurl] => /member [specurl] => /special [indexname] => 主页 [templetdef] => /templets/default ) 那我们再换个环境变量测试看看,这里以我本地的栏目为测试了: Array ( [id] => 3 [reid] => 0 [topid] => 0 [sortrank] => 1 [typename] => 产品 [typedir] => {cmspath}/product … … [indexname] => 主页 [templetdef] => /templets/default [position] => 主页 > 产品 > [title] => 产品 ) 这样一来就检索出当前页面的局部变量了,接下来我们可以来结合前面的SQL语句来实现根据不同环境ID调用内容不同栏目内容。 例如: {dede:php} $thisid = $refObj->Fields['id']; $row = $dsql->GetOne('select id,typename from dede_arctype where id='.$thisid); print_r($row); {/dede:php} 这样是来调用当前栏目的标题,这个标签功能类似于{dede:field.typename/} 接下来我们通过执行查询对sql及输出变量进行处理: $dsql->Execute('me',$sql); while($rs = $dsql->GetArray('me')) { //根据属性处理查询变量 $rs['title'] = cn_substr($rs['title'], $titlelen); //获取底层模板 $ctp->LoadSource($innertext); foreach($ctp->CTags as $tagid=>$ctag) { if(!empty($rs[strtolower($ctag->GetName())])) { $ctp->Assign($tagid,$rs[$ctag->GetName()]); DEDE模板  } } //根据底层模板及查询变量得到处理结果 $revalue .= $ctp->GetResult(); } 这样我们 就将查询出来的结果同底层模板中出现的相关变量进行替换,然后生成输出字符串,将所有的字符串信息存储到$revalue中。
最后返回这个值 return $revalue; 整个文件内容如下: if(!defined('DEDEINC')) { exit("Request Error!"); } function lib_writerarc(&$ctag,&$refObj) { global $dsql,$envs; //属性处理 $attlist="row|12,titlelen|24"; FillAttsDefault($ctag->CAttribute->Items,$attlist); extract($ctag->CAttribute->Items, EXTR_SKIP); $revalue = ''; $innertext = $ctag->GetInnerText(); $ctp = new DedeTagParse(); $ctp->SetNameSpace('field', '[', ']'); $sql = "SELECT * FROM dede_archives WHERE writer='{$refObj->Fields['writer']}' limit 0, $row"; $dsql->Execute('me',$sql); while($rs = $dsql->GetArray('me')) { //根据属性处理查询变量 $rs['title'] = cn_substr($rs['title'], $titlelen); //获取底层模板 $ctp->LoadSource($innertext); foreach($ctp->CTags as $tagid=>$ctag) {  if(!empty($rs[strtolower($ctag->GetName())])) { $ctp->Assign($tagid,$rs[$ctag->GetName()]); } } //根 据底层模板及查询变量得到处理结果 $revalue .= $ctp->GetResult(); } return $revalue; } ?> 接下来我们来测试我们这个标签,我们修改 article_article.htm模板,在里面加入以下的标签代码: {dede:writerarc row='10' titlelen='6'} [field:title/]  {/dede:writerarc}

DEDE 二级菜单

 

DEDE 二级菜单

{dede:channelartlist typeid='son'} <a href="{dede:field name='typeurl'/}">{dede:field name='typename'/}</a><br /> {dede:channel type='son' noself='yes'} <div><a href='[field:typelink/]'>[field:typename/]</a></div> {/dede:channel} {/dede:channelartlist}
三级菜单 - DEDECMS 产品目录是顶级栏目,核仪器和辐射防护产品是二级栏目,其他的二级栏目下面的三级栏目。 实现代码: 其实也就是一个标签嵌套,只不过一般人想不到这点。 {dede:channelartlist typeid=6 row=4} <div> <span><a href="{dede:field name='typeurl'/}">{dede:field name='typename'/}</a></span> <ul> {dede:sql sql='Select * from dede_arctype where reid=~id~ ORDER BY id limit 0,7'} <li><a href='[field:typedir/]' target='_blank'>[field:typename/]</a></li> {/dede:sql} </ul> </div> {/dede:channelartlist} typeid='' 指定顶级栏目就可以啦, limit0,7 这个7是控制三级栏目的显示个数的,显示样式自己调整CSS

dede文章发布系统 获取文章链接url 和 分类链接url的方法

 
通过文章id获取文章链接url:
require_once(dirname(__FILE__).”/../include/common.inc.php”); require_once(DEDEINC.”/arc.archives.class.php”); $ac = new Archives($aid);//通过文章id $aurl = $ac->GetTrueUrl(0); var_dump($aurl);//文章url 静态链接或者动态链接 根据你的后台设置 $ac->ParAddTable();//解析文档 得出分页数 var_dump($ac->TotalPage); //var_dump($ac);exit; //分页url for($i=1;$i<=$ac->TotalPage;$i++) { if($i>1) { //$trueurl = str_replace(“.”.$ac->ShortName,”_”.$i.”.”.$ac->ShortName,$aurl);//$aurl.”_”.$i.”.”.$ac->ShortName; $trueurl = substr($aurl,0,strlen($aurl)-strlen(“.”.$ac->ShortName)).”_”.$i.”.”.$ac->ShortName; } else { $trueurl = $aurl; } 通过分类typeid获取分类链接url: 
require_once(dirname(__FILE__).”/../include/common.inc.php”); require_once(DEDEINC.’/typelink.class.php’); $typelink = new TypeLink($typeid); $typeurl = $typelink->GetOneTypeUrl($typelink->TypeInfos); var_dump($typeurl);//分类url 静态链接或者动态链接

dede5.7 给栏目添加上缩略图OK

如我们一个栏目列表都用缩略图来表示,而不仅仅只是文字,如果没有这项功能会非常麻烦,网上有很多这方面的资料,但是都试过了有很多问题,自己研究一下,测试基本通过。新加字段 typeimg 后台执行SQL: alter table `cn_arctype` add `typeimg` char(100) NOT NULL default ''; 涉及到文件:
        dede/catalog_add.php dede/catalog_edit.php dede/templets/catalog_add.htm dede/templets/catalog_edit.htm
打开dede/catalog_add.php 查找$queryTemplate = "insert into `cn_arctype` 将 (reid,topid,sortrank,typename,typedir, 替换为 (reid,topid,sortrank,typename,typedir,typeimg, 将 ('~reid~','~topid~','~rank~','~typename~','~typedir~', 替换为 ('~reid~','~topid~','~rank~','~typename~','~typedir~','~typeimg~', 打开dede/catalog_edit.php 查找 $upquery = "Update `cn_arctype` set 在其下面新加一行 `typeimg`='$typeimg', 打开dede/templets/catalog_add.htm 查找 <tr> <td height="26">列表命名规则:</td> <td> <input name="namerule2" type="text" id="namerule2" value="{typedir}/list_{tid}_{page}.html"  class="pubinputs"  style="width:250px" /> <img src="img/help.gif" alt="帮助" width="16" height="16" border="0" style="cursor:pointer" onClick="ShowHide('helpvar3')"/></td> </tr> 在其下面增加以下内容 <tr> <td height="65" style="padding-left:10px;">栏目图片:</td> <td> <input name="typeimg" type="text" style="width:250px" id="typeimg" value="" /> <input type="button" name="set9" value="浏览... "class="coolbg np" style="width:60px" onClick="SelectImage('form1.typeimg','');" /> </td> </tr> 并在文件的head增加以下内容 <script language='javascript' src="js/main.js"></script> 打开dede/templets/catalog_edit.htm 在刚前面的位置加入: <tr> <td height="65" style="padding-left:10px;">栏目图片:</td> <td> <input name="typeimg" type="text" style="width:250px" id="typeimg" class="alltxt" value="<?php echo $myrow['typeimg']?>" /> <input type="button" name="set9" value="浏览... "class="coolbg np" style="width:60px" onClick="SelectImage('form1.typeimg','');" /> </td> </tr> 说明:下面这句会调用出已添加的路片路径。 <?php echo $myrow['typeimg']?> 并在文件的head增加以下内容 <script language='javascript' src="js/main.js"></script> 我试了一下在模版里用:{dede:field.typeimg /} 是调不出数据的,所以我改成了SQL调用。 原来是这样的: {dede:channel type='top' row='13'} <li><a href='[field:typeurl/]' [field:rel/]>[field:typeimg/]</a></li> {/dede:channel} 在这里面加上[field:typeimg]  是调不出来的,我个人认为栏目缩略图就是通过循环出来的,而循环不出来则意义不大,所以改成了如下: {dede:sql sql="SELECT typename,typedir,typeimg FROM dede_arctype"} <li><a href="[field:typedir/]">[field:typeimg/]</a></li> {/dede:sql} 这样就顺利的调出来了,当然如果你要调用子ID的话,只要加上相应的条件ID调用就可以了。
                 {dede:channelartlist  typeid='13,14' row ='10'}
<dt ><img src="{dede:field name='litpic'/}" alt="" width="80" /><span><a href='{dede:field name='typeurl'/}'>{dede:field name='typename'/}</a></span></dt>
<dd>
<ul>
                         {dede:channel type='son' noself='yes' }
<li><a href='[field:typelink/]'>[field:typename/]</a></li>
                             {/dede:channel}
</ul>
</dd>
                                {/dede:channelartlist}

织梦dede:sql实现分页

 
思路是把dede:list标签进行改造, 列表页专用标签的工作原理大致是先通过栏目变量id获取到对应的数据源再呈现到页面上来,那么就可以让它不仅 仅通过栏目变量id还可以通过指定的sql语句来获取数据源 可以另外嵌入一个类似 {dede:listsql sql='select * from wp_posts' pagesize='10'}的标签来使用。
打开include/arc.listview.class.php这个文件
找到:
 if ( ! is_object ( $ctag ) ) { $ctag = $this -> dtp -> GetTag ( "list" ) ; }
这一段,在其后添加如下代码: if(!is_object($ctag)) { $ctag = $this->dtp->GetTag("listsql"); if (is_object($ctag)) { $cquery = $ctag->GetAtt("sql"); $cquery = preg_replace("/SELECT(.*?)FROM/is", " SELECT count(*) as dd FROM ", $cquery); $cquery = preg_replace("/ORDER(.*?)SC/is", "", $cquery); $row = $this->dsql->GetOne($cquery); if(is_array($row)) { $this->TotalResult = $row['dd']; } else { $this->TotalResult = 0; } } } 然后找到: if($ctag->GetName()=="list") { $limitstart = ($this->PageNo-1) * $this->PageSize; $row = $this->PageSize; if(trim($ctag->GetInnerText())=="") { $InnerText = GetSysTemplets("list_fulllist.htm"); } else { $InnerText = trim($ctag->GetInnerText()); } $this->dtp->Assign($tagid, $this->GetArcList( $limitstart, $row, $ctag->GetAtt("col"), $ctag->GetAtt("titlelen"), $ctag->GetAtt("infolen"), $ctag->GetAtt("imgwidth"), $ctag->GetAtt("imgheight"), $ctag->GetAtt("listtype"), $ctag->GetAtt("orderby"), $InnerText, $ctag->GetAtt("tablewidth"), $ismake, $ctag->GetAtt("orderway") ) ); } 这一段,在其后添加如下代码: else if($ctag->GetName()=="listsql") { $limitstart = ($this->PageNo-1) * $this->PageSize; $row = $this->PageSize; if(trim($ctag->GetInnerText())=="") { $InnerText = GetSysTemplets("list_fulllist.htm"); } else { $InnerText = trim($ctag->GetInnerText()); } $this->dtp->Assign($tagid, $this->GetSqlList( $limitstart, $row, $ctag->GetAtt("sql"), $InnerText ) ); } 最后找到function GetArcList这个方法,在其后添加一个可以通过传入sql参数获取指定数据源的方法,代码如下:
function GetSqlList($limitstart = 0, $row = 10, $sql = '', $innertext){ global $cfg_list_son; $innertext = trim($innertext); if ($innertext == '') { $innertext = GetSysTemplets('list_fulllist.htm'); } //处理SQL语句 $limitStr = " LIMIT {$limitstart},{$row}"; $this->dsql->SetQuery($sql . $limitStr); $this->dsql->Execute('al'); $t2 = ExecTime(); //echo $t2-$t1; $sqllist = ''; $this->dtp2->LoadSource($innertext); $GLOBALS['autoindex'] = 0; //获取字段 while($row = $this->dsql->GetArray("al")) { $GLOBALS['autoindex']++; if(is_array($this->dtp2->CTags)) { foreach($this->dtp2->CTags as $k=>$ctag) { if($ctag->GetName()=='array') { //传递整个数组,在runphp模式中有特殊作用 $this->dtp2->Assign($k,$row); } else { if(isset($row[$ctag->GetName()])) { $this->dtp2->Assign($k,$row[$ctag->GetName()]); } else { $this->dtp2->Assign($k,''); } } } } $sqllist .= $this->dtp2->GetResult(); }//while $t3 = ExecTime(); //echo ($t3-$t2); $this->dsql->FreeResult('al'); return $sqllist; } 总共就添加三段代码,调用范例: {dede:listsql sql='select ID,post_title from wp_posts' pagesize='10'} <li><a href="http://gump.me/[field:ID /].html">[field:post_title /]</a></li> {/dede:listsql} <!--分页--> {dede:pagelist listsize='2' listitem='index pre pageno next end '/}
{dede:sql} 和{dede:listsql}的文章链接地址<a href="[field:id runphp='yes'] $id=@me; @me='';$url=GetOneArchive($id);@me=$url['arcurl'];[/field:id]">

dede自定义图片字段 用法

 
遇到几个朋友在问:为什么在用自定义列表出来的图片字段不是正确的图片地址,而是类似于: {dede:img text='' width='270' height='129'} /uploads/101017/1-10101H21F54P.gif {/dede:img} 这样的格式! 非常明显,这样是不能正确显示的,这是自定义图片字段的处理方式造成的。要解决这个问题,我们必须得创建一个自定义函数,其实现方式为: 【实现】 1.创建自定义函数 打开 /include/extend.func. 文件(注:这个文件就是系统预留的自定义函数接口文件,主要用于二次开发用的。如果你是老版本,默认没有这个文件,自己创建一个PHP文件即可),在最下面的?>上一行加入以下函数代码: [php] /**************** function GetOneImgUrl @@ 功能:读取自定义字段图片地址 @@ 作者:华强℡(QQ:3421209) @@ 网址:织梦网(xuewl.com) @@ 时间:2010-10-17 22:48 *****************/ function GetOneImgUrl($img,$ftype=1){ if($img <> ''){ $dtp = new DedeTagParse(); $dtp->LoadSource($img); if(is_array($dtp->CTags)){ foreach($dtp->CTags as $ctag){ if($ctag->GetName()=='img'){ $width = $ctag->GetAtt('width'); $height = $ctag->GetAtt('height'); $imgurl = trim($ctag->GetInnerText()); $img = ''; if($imgurl != ''){ if($ftype==1){ $img .= $imgurl; } else{ $img .= '<img src="'.$imgurl.'" width="'.$width.'" height="'.$height.'" />'; } } } } } $dtp->Clear(); return $img; } } [/php] 保存后关闭即可。 2.函数调用方法 问:我们创建好函数以后,那么这个函数要如何来调用呢? 答:本函数的调用方法为: [field:自定义图片字段名 function="GetOneImgUrl(@me,显示类型)"/] 比如:我们的自定义图片字段名为 imgurl ,那么调用方式有以下两种: [field:imgurl function='GetOneImgUrl(@me,0)'/] <!--调用图片的信息,自动调用宽度和高度(已包含Html代码的<img />)--> [field:imgurl function='GetOneImgUrl(@me,1)'/] <!--只调用图片地址,一般可用于背景图嵌套-->

DEDE 前台使用select的自定义字段

由于项目要在前台生成分类让用户选择,自己又不想写死。所以想直接调用后台的自定义select的字段 网上查了好久都没有相关信息 所以自己写了个  大致思路是 获取channeltype表的fieldset 字段  然后通过正则 过滤需要的数据 代码如下 [php] /** * @param     string  $str      fieldset字段内容 * @param     string  $field    字段名 * @return    string */ function getSelectOption($str , $field) { preg_match( "/\<field:".$field." (.*?)\>/", $str, $str1 ); array_shift($str1); preg_match_all( "/default=\"(.*?)\"/", $str1[0], $str2 ); array_shift($str2); $arr = explode(',', $str2[0][0]); $html = NULL; foreach($arr as $a) { $html .= "<option value=\"{$a}\">{$a}</option>\r\n"; } return $html; } [/php] 前台调用 [php] <select  name="ask_title"  id="ask_title"> {dede:sql sql="select fieldset from #@__channeltype where id=7"} [field:fieldset function="getSelectOption('@me','tezhen')"/] {/dede:sql} </select> [/php] 把id 换成对应的模型即可  

WordPress 数据接口

数据库接口介绍 WordPress包含一个操作数据库的类——wpdb,该类基于ezSQL(由Justin Vincent维护的数据库操作项目)编写,包含了其基本的功能。 使用说明 请不要直接调用wpdb类中的方法。WordPress定义了$wpdb的全局变量,所以请直接调用该全局变量$wpdb的实例来操作数据库。(调用之前不要忘了声明引用全局变量$wpdb。参考globalize) $wpdb对象可以用来操作WordPress数据库中的每一个表,不仅仅是WordPress自动创建的基本表。例如,你有一个自定义的表叫做mytable,那么可以使用如下语句来查询: [php] $myrows = $wpdb->get_results( "SELECT id, name FROM mytable" ); [/php] $wpdb对象可以读取多个表,但是其只针对WordPress的数据库。如果你需要连接其他数据库,那么你应该使用你自己的数据库连接信息,并调用wpdb类来创建一个你自己的数据库操作实例。如果你有多个数据库需要连接,那么你可以考虑使用hyperdb来替代$wpdb。 在数据库上运行任务查询 这个查询函数允许你在wordpress的数据库里运行任何SQL查询。当然了,最好能利用如下的特定函数, [php] <!--?php $wpdb--->query('query'); ?> [/php] query (string) The SQL query you wish to execute. The function returns an integer corresponding to the number of rows affected/selected. If there is a MySQL error, the function will return FALSE. (Note: since both 0 and FALSE can be returned, make sure you use the correct comparison operator: equality == vs. identicality ===). Note: As with all functions in this class that execute SQL queries, you must SQL escape all inputs (e.g., wpdb->escape($user_entered_data_string)). See the section entitled Protect Queries Against SQL Injection Attacks below. Examples Delete the 'gargle' meta key and value from Post 13. [php] $wpdb->query(" DELETE FROM $wpdb->postmeta WHERE post_id = '13' AND meta_key = 'gargle'"); [/php] Performed in WordPress by delete_post_meta(). Set the parent of Page 15 to Page 7. [php]$wpdb->query(" UPDATE $wpdb->posts SET post_parent = 7 WHERE ID = 15 AND post_status = 'static'");[/php] SELECT a Variable The get_var function returns a single variable from the database. Though only one variable is returned, the entire result of the query is cached for later use. Returns NULL if no result is found. query (string) The query you wish to run. Setting this parameter to null will return the specified variable from the cached results of the previous query. column_offset (integer) The desired column (0 being the first). Defaults to 0. row_offset (integer) The desired row (0 being the first). Defaults to 0. Examples Retrieve and display the number of users. [php] <!--?php $user_count = $wpdb--->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->users;")); echo ' User count is ' . $user_count . ' '; ?> [php] Retrieve and display the sum of a Custom Field value. [php] <!--?php $meta_key = 'miles';//set this to appropriate custom field meta key $allmiles=$wpdb--->get_var($wpdb->prepare("SELECT sum(meta_value) FROM $wpdb->postmeta WHERE meta_key = %s", $meta_key)); echo ' Total miles is '.$allmiles . ' '; ?> [php] SELECT a Row To retrieve an entire row from a query, use get_row. The function can return the row as an object, an associative array, or as a numerically indexed array. If more than one row is returned by the query, only the specified row is returned by the function, but all rows are cached for later use. Returns NULL if no result is found. query (string) The query you wish to run. output_type One of three pre-defined constants. Defaults to OBJECT. OBJECT - result will be output as an object. ARRAY_A - result will be output as an associative array. ARRAY_N - result will be output as a numerically indexed array. row_offset (integer) The desired row (0 being the first). Defaults to 0. Examples Get all the information about Link 10. [php] $mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10"); [/php] The properties of the $mylink object are the column names of the result from the SQL query (in this all of the columns from the $wpdb->links table). [php] echo $mylink->link_id; // prints "10" [/php] In contrast, using [php] $mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_A); would result in an associative array: echo $mylink['link_id']; // prints "10" and $mylink = $wpdb->get_row("SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_N); would result in a numerically indexed array: echo $mylink[1]; // prints "10" [/php] SELECT a Column To SELECT a column, use get_col. This function outputs a dimensional array. If more than one column is returned by the query, only the specified column will be returned by the function, but the entire result is cached for later use. Returns an empty array if no result is found. query (string) the query you wish to execute. Setting this parameter to null will return the specified column from the cached results of the previous query. column_offset (integer) The desired column (0 being the first). Defaults to 0. Examples For this example, assume the blog is devoted to information about automobiles. Each post describes a particular car (e.g. 1969 Ford Mustang), and three Custom Fields, manufacturer, model, and year, are assigned to each post. This example will display the post titles, filtered by a particular manufacturer (Ford), and sorted by model and year. The get_col form of the wpdb Class is used to return an array of all the post ids meeting the criteria and sorted in the correct order. Then a foreach construct is used to iterate through that array of post ids, displaying the title of each post. Note that the SQL for this example was created by Andomar. [php] <!--?php $meta_key1 = 'model'; $meta_key2 = 'year'; $meta_key3 = 'manufacturer'; $meta_key3_value = 'Ford'; $postids=$wpdb--->get_col($wpdb->prepare(" SELECT key3.post_id FROM $wpdb->postmeta key3 INNER JOIN $wpdb->postmeta key1 on key1.post_id = key3.post_id and key1.meta_key = %s INNER JOIN $wpdb->postmeta key2 on key2.post_id = key3.post_id and key2.meta_key = %s WHERE key3.meta_key = %s and key3.meta_value = %s ORDER BY key1.meta_value, key2.meta_value",$meta_key1, $meta_key2, $meta_key3, $meta_key3_value)); if ($postids) { echo 'List of ' . $meta_key3_value . '(s), sorted by ' . $meta_key1 . ', ' . $meta_key2; foreach ($postids as $id) { $post=get_post(intval($id)); setup_postdata($post);?> [/php] This example lists all posts that contain a particular custom field, but sorted by the value of a second custom field. [php] <!--?php //List all posts with custom field Color, sorted by the value of custom field Display_Order //does not exclude any 'post_type' //assumes each post has just one custom field for Color, and one for Display_Order $meta_key1 = 'Color'; $meta_key2 = 'Display_Order'; $postids=$wpdb--->get_col($wpdb->prepare(" SELECT key1.post_id FROM $wpdb->postmeta key1 INNER JOIN $wpdb->postmeta key2 on key2.post_id = key1.post_id and key2.meta_key = %s WHERE key1.meta_key = %s ORDER BY key2.meta_value+(0) ASC", $meta_key2,$meta_key1)); if ($postids) { echo 'List of '. $meta_key1 . ' posts, sorted by ' . $meta_key2 ; foreach ($postids as $id) { $post=get_post(intval($id)); setup_postdata($post);?> [/php] SELECT Generic Results Generic, mulitple row results can be pulled from the database with get_results. The function returns the entire query result as an array. Each element of this array corresponds to one row of the query result and, like get_row, can be an object, an associative array, or a numbered array. query (string) The query you wish to run. Setting this parameter to null will return the data from the cached results of the previous query. output_type One of four pre-defined constants. Defaults to OBJECT. See SELECT a Row and its examples for more information. OBJECT - result will be output as a numerically indexed array of row objects. OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded). ARRAY_A - result will be output as an numerically indexed array of associative arrays, using column names as keys. ARRAY_N - result will be output as a numerically indexed array of numerically indexed arrays. Since this function uses the '$wpdb->query()' function all the class variables are properly set. The results count for a 'SELECT' query will be stored in $wpdb->num_rows. Examples Get the IDs and Titles of all the Drafts by User 5 and echo the Titles. [php] $fivesdrafts = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = 5"); foreach ($fivesdrafts as $fivesdraft) { echo $fivesdraft->post_title; } [/php] Get all information on the Drafts by User 5. [php] <!--?php $fivesdrafts = $wpdb--->get_results("SELECT * FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = 5"); if ($fivesdrafts) : foreach ($fivesdrafts as $post) : setup_postdata($post); ?> [/php]

title="Permanent Link to ">

Not Found

INSERT rows Insert a row into a table. table (string) The name of the table to insert data into. data (array) Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). format (array|string) (optional) An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. Possible format values: %s as string; %d as decimal number; and %f as float. After insert, the ID generated for the AUTO_INCREMENT column can be accessed with: $wpdb->insert_id This function returns false if the row could not be inserted. Examples Insert two columns in a row, the first value being a string and the second a number: [php]$wpdb->insert( 'table', array( 'column1' => 'value1', 'column2' => 123 ), array( '%s', '%d' ) )[/php] UPDATE rows 更新记录 更新数据库的记录。 table (string) 要更新的表名称。 data (array) 需要更新的数据(使用格式:column => value)。Both $data columns and $data values should be "raw" (neither should be SQL escaped). where (array) A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw". format (array|string) (optional) An array of formats to be mapped to each of the values in $data. If string, that format will be used for all of the values in $data. where_format (array|string) (optional) An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where. Possible format values: %s as string; %d as decimal number and %f as float. If omitted, all values in $where will be treated as strings. 范例 Update a row, where the ID is 1, the value in the first column is a string and the value in the second column is a number: $wpdb->update( 'table', array( 'column1' => 'value1', 'column2' => 'value2' ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) ) Protect Queries Against SQL Injection Attacks For a more complete overview of SQL escaping in WordPress, see database Data Validation. That Data Validation article is a must-read for all WordPress code contributors and plugin authors. Briefly, though, all data in SQL queries must be SQL-escaped before the SQL query is executed to prevent against SQL injection attacks. This can be conveniently done with the prepare method, which supports both a sprintf()-like and vsprintf()-like syntax. query (string) The SQL query you wish to execute, with %s and %d placeholders. Any other % characters may cause parsing errors unless they are escaped. All % characters inside SQL string literals, including LIKE wildcards, must be double-% escaped as %%. value_parameter (int|string|array) The value to substitute into the placeholder. Many values may be passed by simply passing more arguments in a sprintf()-like fashion. Alternatively the second argument can be an array containing the values as in PHP's vsprintf() function. Care must be taken not to allow direct user input to this parameter, which would enable array manipulation of any query with multiple placeholders. Values must not already be SQL-escaped. Examples Add Meta key => value pair "Harriet's Adages" => "WordPress' database interface is like Sunday Morning: Easy." to Post 10. $metakey = "Harriet's Adages"; $metavalue = "WordPress' database interface is like Sunday Morning: Easy."; [php]$wpdb->query( $wpdb->prepare( " INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value ) VALUES ( %d, %s, %s )", 10, $metakey, $metavalue ) );[/php] Performed in WordPress by add_meta(). The same query using vsprintf()-like syntax. $metakey = "Harriet's Adages"; $metavalue = "WordPress' database interface is like Sunday Morning: Easy."; [php]$wpdb->query( $wpdb->prepare( " INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value ) VALUES ( %d, %s, %s )", array(10, $metakey, $metavalue) ) );[/php] Note that in this example we pack the values together in an array. This can be useful when we don't know the number of arguments we need to pass until runtime. Notice that you do not have to worry about quoting strings. Instead of passing the variables directly into the SQL query, use a %s placeholder for strings and a %d placedolder for integers. You can pass as many values as you like, each as a new parameter in the prepare() method. Show and Hide SQL Errors You can turn error echoing on and off with the show_errors and hide_errors, respectively. [php] <!--?php $wpdb--->show_errors(); ?> <!--?php $wpdb--->hide_errors(); ?>[/php] You can also print the error (if any) generated by the most recent query with print_error. print_error(); ?> Getting Column Information You can retrieve information about the columns of the most recent query result with get_col_info. This can be useful when a function has returned an OBJECT whose properties you don't know. The function will output the desired information from the specified column, or an array with information on all columns from the query result if no column is specified. type (string) What information you wish to retrieve. May take on any of the following values (list taken from the ezSQL docs). Defaults to name. name - column name. Default. table - name of the table the column belongs to max_length - maximum length of the column not_null - 1 if the column cannot be NULL primary_key - 1 if the column is a primary key unique_key - 1 if the column is a unique key multiple_key - 1 if the column is a non-unique key numeric - 1 if the column is numeric blob - 1 if the column is a BLOB type - the type of the column unsigned - 1 if the column is unsigned zerofill - 1 if the column is zero-filled offset (integer) Specify the column from which to retrieve information (with 0 being the first column). Defaults to -1. -1 - Retrieve information from all columns. Output as array. Default. Non-negative integer - Retrieve information from specified column (0 being the first). Clearing the Cache You can clear the SQL result cache with flush. This clears $wpdb->last_result, $wpdb->last_query, and $wpdb->col_info. Class Variables $show_errors Whether or not Error echoing is turned on. Defaults to TRUE. $num_queries The number of queries that have been executed. $last_query The most recent query to have been executed. $queries You may save all of the queries run on the database and their stop times by setting the SAVEQUERIES constant to TRUE (this constant defaults to FALSE). If SAVEQUERIES is TRUE, your queries will be stored in this variable as an array. $last_result The most recent query results. $col_info The column information for the most recent query results. See Getting Column Information. $insert_id ID generated for an AUTO_INCREMENT column by the most recent INSERT query. $num_rows The number of rows returned by the last query. $prefix The assigned WordPress table prefix for the site. Multi-Site Variables If you are using Multi-Site, you also have access to the following: $blogid The id of the current site (blog). Tables The WordPress database tables are easily referenced in the wpdb class. $posts The table of Posts. $postmeta The Meta Content (a.k.a. Custom Fields) table. $comments The Comments table. $commentmeta The table contains additional comment information. $terms The terms table contains the 'description' of Categories, Link Categories, Tags. $term_taxonomy The term_taxonomy table describes the various taxonomies (classes of terms). Categories, Link Categories, and Tags are taxonomies. $term_relationships The term relationships table contains link between the term and the object that uses that term, meaning this file point to each Category used for each Post. $users The table of Users. $usermeta The usermeta table contains additional user information, such as nicknames, descriptions and permissions. $links The table of Links. $options The Options table. 来自手册 :wordpress中文手册