thinkphp5随机抽取数据的方法

/**
 * 随机获取数据
 * @param string $num  抽取条数
 * @param string $table    表名
 * @param string $where    查询条件
 * @return array 
 */
function tt_random_data($num,$table,$where=[])
{
    $pk = Db::name($table)->getPK();//获取主键
    $countcus = Db::name($table)->where($where)->field($pk)->select();//查询数据
    $con = '';
    $qu = '';
    foreach($countcus as $v=>$val){
        $con.= $val[$pk].'|';
    }
    $array = explode("|",$con);
    $countnum = count($array)-1;
    for($i = 0;$i <= $num;$i++){
        $sunum = mt_rand(0,$countnum);
        $qu.= $array[$sunum].',';
    }
    $list = Db::name($table)->where($pk,'in',$qu)->limit(0,$num)->select();
    return $list;
}

亲测有效。


关注公众号,了解更多it技术(it问答网

Mysql按指定顺序排序的两种写法

SELECT `ID` FROM wp_posts WHERE `ID` in (1,2,3,4,5) ORDER BY FIELD(`ID`,5,4,3,1,2); // 纯数字字段不用处理引号,比较好拼接
SELECT `ID` FROM wp_posts WHERE `ID` in (1,2,3,4,5) ORDER BY FIND_IN_SET(`post_title`,'A,B,C,D,E'); // 一个引号全包住,搞定字符值字段
 
-- 注意:第一个参数不能是字符串,否则不起作用
-- 性能差异
SELECT id FROM cbd_hots WHERE id in (155,154) ORDER BY FIELD(`id`,154,155); // 纯数字字段不用处理引号,比较好拼接

亲测有效!

针对tp5中的这样的写法[orderRaw 代替order  ] 请使用orderRaw方法替代order

有业务需求如下:

select * from table where id IN (3,6,9,1,2,5,8,7) order by field(id,3,6,9,1,2,5,8,7);
但是也可以写成这样

->order("field(id,3,6,9,1,2,5,8,7)")
但是官方文档说了,当你的order排序中使用了SQL函数的时候,请使用orderRaw方法替代order 。

实践有效:

return Db::connect(config('database.sqla'))->name("hots")->where("id in (".$hots_ids.")")->orderRaw("field(id,".$hots_ids.")")->select();

 

 


关注公众号,了解更多it技术(it问答网

tp5获取session id的方式

方法一

先任一设置一个session值,然后获取session id

session(‘g’,”);//执行一次助手函数,session啥都可以,只要执行这个函数即可。
$session_id = session_id();
方法二

在文件\think\Session 中加一个函数

public static function sid(){
if (PHP_SESSION_ACTIVE != session_status()) {
session_start();
}
return session_id();
}

 


关注公众号,了解更多it技术(it问答网

tp5如何调用多个数据库连接?

database.php数据内容里面 最下面追加如下:

//推广产品站数据库设置
	'sqla'=>[
			// 数据库类型
			'type'            => 'mysql',
			// 服务器地址
			'hostname'        => '127.0.0.1',
			// 数据库名
			'database'        => 'cbd2',
			// 用户名
			'username'        => 'root',
			// 密码
			'password'        => 'root',
			// 端口
			'hostport'        => '',
			// 连接dsn
			'dsn'             => '',
			// 数据库连接参数
			'params'          => [],
			// 数据库编码默认采用utf8
			'charset'         => 'utf8',
			// 数据库表前缀
			'prefix'          => 'cbd_',
			// 数据库调试模式
			'debug'           => true,
			// 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器)
			'deploy'          => 0,
			// 数据库读写是否分离 主从式有效
			'rw_separate'     => false,
			// 读写分离后 主服务器数量
			'master_num'      => 1,
			// 指定从服务器序号
			'slave_no'        => '',
			// 是否严格检查字段是否存在
			'fields_strict'   => true,
			// 数据集返回类型
			'resultset_type'  => 'array',
			// 自动写入时间戳字段
			'auto_timestamp'  => false,
			// 时间字段取出后的默认时间格式
			'datetime_format' => 'Y-m-d H:i:s',
			// 是否需要进行SQL性能分析
			'sql_explain'     => false,
	
	]

 

调用方式【实例化链接】:

Db::connect(config(‘database.sqla’))->query();

//跨db的表实例化代替DB::name(‘pages’);
Db::connect(config(‘database.sqla’))->name(“pages”);


关注公众号,了解更多it技术(it问答网

tp5查询后保持分页条件

在这里记录一下Tp5保持分页状态的两种方法:

一:

Db::name('data') -> where($where)  -> paginate(5,false,['query' => request()->param()]);

二:

$params = $this -> request -> param();
 $users = Db::name('data')->where($where)->paginate(15);
 
// 在 render 前,使用appends方法保持分页条件
$users->appends($params);
 
$this->assign('page', $users->render());//单独提取分页出来

 


关注公众号,了解更多it技术(it问答网

thinkphp5 中 db::query 原生查询如何实现分页?

	$sql="select a.*,b.name from obj_users_admin a left join obj_users_admin_groups b on a.gid=b.id";		

		$b=$num=2;		//每页显示记录数		
		$page=input("get.page")?input("get.page"):1;	//当前页
		$count = Db::execute($sql); //总条数		
		
		$a=($page-1)*$b;
		$sql2=$sql." limit $a,$b";
		$list = Db::query($sql2); //当前页数据
		$arr=Bootstrap::make($list,$num,$page,$count,false,['path'=>Bootstrap::getCurrentPath(),'query'=>request()->param()]);
		
		print_r($arr);
		print_r($arr->render());

徐多蔚亲测无误!

tp5中LEFT分页格式:

	$a=config("database.prefix")."users_admin";
		$b=config("database.prefix")."users_admin_groups";

		$arr=$obj->db->table("$a a")
->join("$b b", "a.gid=b.id", 'LEFT')->where($tj)->field("a.*,b.name")->order("a.updatetime desc,a.id desc")->paginate(2,false, [
                'query' => Request::instance()->param(),//不丢失已存在的url参数
            ]);

 


关注公众号,了解更多it技术(it问答网

thinkPHP5 错误页面修改

1.进入手册找到错误配置文件位置和模板信息,最快速的办法是直接修改框架错误文件;

进入手册:https://www.kancloud.cn/manual/thinkphp5_1/354092

2.找到错误位置:

thinkphp/tpl/think_exception.tpl

3.进入模板,找到信息进行修改。

  <div class="copyright">
        <a title="技术支持" href="http://www.xuduowei.com" target="_blank">xuduowei[徐多蔚]</a> 
        <span>V1.0<?php //echo THINK_VERSION; ?></span> 
        <span>{ 十年磨一剑-为API开发设计的高性能框架 }</span>
    </div>

 

当tp5url有错误的时候,最终效果如下!【提示:记得关闭debug模式哦!】


关注公众号,了解更多it技术(it问答网

thinkphp5事务的处理,事务中涉及到循环的处理方案-徐多蔚【合肥php老师】原创。

function ac(){
		$obj=new \app\admin888\model\ProductsModel;
		$b=1;//标志成功的状态,一般失败,就修改其为0
				for($j=0;$j<=10;$j++){
					for($i=0;$i<=5;$i++){
						$obj->db->query("insert into cbd_products_attr_guige set uid=5");
						if($i==4){//一旦与遇错
							//Db::rollback();//可以省略,在try那里一起操作
							$b=0;//设置出错标志
							break;//终止本次循环,不可少。
						}
					}

					if(!$b){//外层循环中判断里面有错误,则外层也终止。数据库回滚。
						//Db::rollback();在try那里一起操作
						break;//终止本次循环,不可少。
					}
				}
				//echo 1;
				return $b;
	}


	function trya(){
		
		// 启动事务
			Db::startTrans();
			try{
				$b=$this->ac();
				if($b){
					Db::commit();
					return 1;
				}else{
					Db::rollback();
					return 0;
				}
				
			} catch (\Exception $e) {
				//echo 0;
				// 回滚事务			
				Db::rollback();			
				return 2;				
			}
	}

	//测试
	function cs(){
		echo $this->trya();
	}

 


关注公众号,了解更多it技术(it问答网

TP5中的No input file specified/解决PHP5.6版本“No input file specified”的问题

问题描述:使用TP框架做项目时,在启用REWRITE的伪静态功能的时候,首页可以访问,但是访问其它页面的时候,就提示:“No input file specified.”
原因在于使用的PHP5.6是fast_cgi模式,而在某些情况下,不能正确识别path_info所造成的错误
默认的.htaccess里面的规则:

IfModule mod_rewrite.c>
  Options +FollowSymlinks
  RewriteEngine On

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>

“No input file specified.”,是没有得到有效的文件路径造成的。
修改后的伪静态规则,如下:

IfModule mod_rewrite.c>
  Options +FollowSymlinks
  RewriteEngine On

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?/$1 [QSA,PT,L]
</IfModule>

仅仅就是在正则结果“/$1”前面多加了一个“?”号,问题也就随之解决了。


关注公众号,了解更多it技术(it问答网