我用php做了改写,可能有不完善的地方。
附件中有代码,
主要的类为class.qqhttp.php
php代码
<?php
/**
* @file class.qqhttp.php
* qq邮箱登陆获取类
* @author wc<cao8222@gmail.com>
* @date 2009-04-27
*/
class qqhttp {
var $cookie = '';
function __cunstrut() {
}
function makeform() {
$form = array(
'url' => "http://mail.qq.com/cgi-bin/loginpage",
);
$data = $this->curlfunc($form);
preg_match('/name="ts"\svalue="(\d+)"/',$data['html'], $tspre);
$ts = $tspre[1];
preg_match('/action="http:\/\/(m\d+)\.mail\.qq\.com/',$data['html'], $server);
$server_no = $server[1];
/* login.html 载入 */
$html = file_get_contents(dirname(__file__).'/login.htm');
$html = str_replace('{_ts_}',$ts, $html);
$html = str_replace('{_server_no_}',$server_no, $html);
return $html;
}
function curlfunc($array)
{
$ch = curl_init();
curl_setopt($ch, curlopt_url, $array['url']);
curl_setopt($ch, curlopt_returntransfer, true);
if( isset($array['header']) && $array['header'] ) {
curl_setopt($ch, curlopt_header, 1);
}
if(isset($array['httpheader'])) {
curl_setopt($ch, curlopt_httpheader, $array['httpheader']);
}
if(isset($array['referer'])) {
curl_setopt($ch, curlopt_referer, $array['referer']);
}
if( isset($array['post']) ) {
curl_setopt($ch, curlopt_post, 1 );
curl_setopt($ch, curlopt_postfields, $array['post']);
}
if( isset($array['cookie']) ){
curl_setopt($ch, curlopt_cookie, $array['cookie']);
}
$r['erro'] = curl_error($ch);
$r['errno'] = curl_errno($ch);
$r['html'] = curl_exec($ch);
$r['http_code'] = curl_getinfo($ch, curlinfo_http_code);
curl_close($ch);
return $r;
}
/**
* 获取验证码图片和cookie
* @param null
*
* @return array('img'=>string, 'cookie'=>string)
*/
function getvfcode ()
{
$vfcode = array(
'header' => true,
'cookie' => false,
'url'=>'http://ptlogin2.qq.com/getimage?aid='.$_get['aid'].'&'.@$_get['t'],
);
$r = $this->curlfunc($vfcode);
if ($r['http_code'] != 200 ) return false;
$data = split("\n", $r['html']);
preg_match('/verifysession=([^;]+);/',$data[5], $temp);
$cookie = trim($temp[1]);
$img = $data[9];
return array('img'=>$img,'cookie'=>$cookie);
}
/**
* 登陆qq邮箱
*
* @param $cookie getvfcode中生成的cookie
*
* @return array(
* sid=>string , //用户认证的唯一标示
* login => boolean, //true 登陆成功 ,false 登陆失败
* server_no => string // 服务器编号
* active => boolean //true 已开通 ,false 未开通 邮箱
* cookie => string // 获取数据cookie
*
* );
*/
function login($cookie)
{
/* 生成参数字符串 */
$post = array();
foreach($_post as $k => $v) {
$post[] = $k.'='.urlencode($v);
}
$poststr = implode('&',$post);
$r['server_no'] = $_get['server_no'];
$login = array(
'url'=>'http://'.$r['server_no'].'.mail.qq.com/cgi-bin/login?sid=0,2,zh_cn',
'header' => true,
'cookie' => 'verifysession='.$cookie,
'referer' => 'http://mail.qq.com/cgi-bin/loginpage',
'httpheader'=>array(
"host: " . $r['server_no'] . '.mail.qq.com',
"user-agent: mozilla/5.0 (windows; u; windows nt 5.1; zh-cn; rv:1.9.0.9) gecko/2009040821 firefox/3.0.9 firephp/0.2.4",
"content-type: application/x-www-form-urlencoded",
),
'post' => $poststr ,
);
$data = $this->curlfunc($login);
$data['html'] = iconv("gb2312", "utf-8", $data['html']);
if ($data['http_code'] != 200) {
$this->error($data);
return false;
}
/* 测试数据 */
//$data['html'] =file_get_contents('./r.txt');
$r['uin'] = $_post['uin'];
/* 登陆错误的判断 */
if (preg_match('|errtype=(\d)|', $data['html'], $temp_err)) {
$r['login'] = false;
if ($temp_err[1] == 1) {
$r['msg'] = '账号和密码错误';
} elseif ($temp_err[1] == 2) {
$r['msg'] = '验证码错误';
}
return $r;
}
/* 登陆成功 */
preg_match('|urlhead="([^"]+)"|i',$data['html'],$temp_url);
$urlhead = $temp_url[1];
if (preg_match('|frame_html\?sid=([^"]+)"|i',$data['html'],$temp_sid) ) {
$r['sid'] = $temp_sid[1];
$r['active'] = true;
} elseif (preg_match('|autoactivation\?sid=([^&]+)?&|i',$data['html'],$temp_sid) ) {
$r['sid'] = $temp_sid[1];
$r['active'] = false;
}
/* 登录后cookie的获取 ,在后续操作中用到 */
if (preg_match_all('|set-cookie:([^=]+=[^;]+)|i', $data['html'], $new_cookies) ) {
$cookiestr = implode('; ', $new_cookies[1]);
$cookiestr .= '; verifysession='.$cookie;
}
$r['login'] = true;
$r['cookie'] = $cookiestr;
return $r;
}
function openemail($param)
{
$openemail = array(
'url'=>'http://'.$param['server_no'].'.mail.qq.com/cgi-bin/autoactivation?actmode=6&sid='.$param['sid'],
'header' => true,
'cookie' => $param['cookie'],
'referer' => 'http://'.$param['server_no'].'mail.qq.com/cgi-bin/autoactivation?sid='.$param['sid'].'&action=reg_activate&actmode=6',
'httpheader'=>array(
"host: " . $param['server_no'] . '.mail.qq.com',
'accept-charset: gb2312,utf-8;q=0.7,*;q=0.7',
"user-agent: mozilla/5.0 (windows; u; windows nt 5.1; zh-cn; rv:1.9.0.9) gecko/2009040821 firefox/3.0.9 firephp/0.2.4",
),
);
$data = $this->curlfunc($openemail);
if (preg_match('|set-cookie:qqmail_activated=0|i', $data['html'])) {
$param['active'] = true;
$param['cookie'] = $param['cookie'] .'; qqmail_activated=0; qqmail_alias=';
}
return $param;
}
/**
*
* 获取friends数据
*
* @param $param = array(
* sid=>string , //用户认证的唯一标示
* login => boolean, //true 登陆成功 ,false 登陆失败
* server_no => string // 服务器编号
* active => boolean //true 已开通 ,false 未开通 邮箱
* cookie => string // 获取数据cookie
*
* );
* @return array(
* key=>value, // key:qq号,value: nickname
* );
*/
function getfriends($param)
{
$friend = array(
'url'=>'http://'.$param['server_no'].'.mail.qq.com/cgi-bin/addr_listall?type=user&&category=all&sid='.$param['sid'],
'header' => true,
'cookie' => $param['cookie'],
'referer' => 'http://m151.mail.qq.com/cgi-bin/addr_listall?sid='.$param['sid'].'&sorttype=null&category=common',
'httpheader'=>array(
"host: " . $param['server_no'] . '.mail.qq.com',
'accept-charset:utf-8;q=0.7,*;q=0.7',
"user-agent: mozilla/5.0 (windows; u; windows nt 5.1; zh-cn; rv:1.9.0.9) gecko/2009040821 firefox/3.0.9 firephp/0.2.4",
),
);
$r = $this->curlfunc($friend);
if ($r['http_code'] != 200) {
$this->error($r);
return false;
}
$data = $r['html'];
$preg = preg_match_all('|<p class="l_n"><span><img class="l_q" name=qqplusimg key="(\d+)"[^>]+/> ([^<]+)</span></p>|i', $data, $temp_list);
if ($preg == 0) return array();
$list = array_combine($temp_list[1],$temp_list[2]);
return $list;
}
/**
* 错误显示
*
* @param $str array
*
* @return
*/
function error($str) {
$str['html'] = str_replace('script','', $str['html']);
var_dump($str);
exit;
}
}
?>
<?php
/**
* @file class.qqhttp.php
* qq邮箱登陆获取类
* @author wc<cao8222@gmail.com>
* @date 2009-04-27
*/
class qqhttp {
var $cookie = '';
function __cunstrut() {
}
function makeform() {
$form = array(
'url' => "http://mail.qq.com/cgi-bin/loginpage",
);
$data = $this->curlfunc($form);
preg_match('/name="ts"\svalue="(\d+)"/',$data['html'], $tspre);
$ts = $tspre[1];
preg_match('/action="http:\/\/(m\d+)\.mail\.qq\.com/',$data['html'], $server);
$server_no = $server[1];
/* login.html 载入 */
$html = file_get_contents(dirname(__file__).'/login.htm');
$html = str_replace('{_ts_}',$ts, $html);
$html = str_replace('{_server_no_}',$server_no, $html);
return $html;
}
function curlfunc($array)
{
$ch = curl_init();
curl_setopt($ch, curlopt_url, $array['url']);
curl_setopt($ch, curlopt_returntransfer, true);
if( isset($array['header']) && $array['header'] ) {
curl_setopt($ch, curlopt_header, 1);
}
if(isset($array['httpheader'])) {
curl_setopt($ch, curlopt_httpheader, $array['httpheader']);
}
if(isset($array['referer'])) {
curl_setopt($ch, curlopt_referer, $array['referer']);
}
if( isset($array['post']) ) {
curl_setopt($ch, curlopt_post, 1 );
curl_setopt($ch, curlopt_postfields, $array['post']);
}
if( isset($array['cookie']) ){
curl_setopt($ch, curlopt_cookie, $array['cookie']);
}
$r['erro'] = curl_error($ch);
$r['errno'] = curl_errno($ch);
$r['html'] = curl_exec($ch);
$r['http_code'] = curl_getinfo($ch, curlinfo_http_code);
curl_close($ch);
return $r;
}
/**
* 获取验证码图片和cookie
* @param null
*
* @return array('img'=>string, 'cookie'=>string)
*/
function getvfcode ()
{
$vfcode = array(
'header' => true,
'cookie' => false,
'url'=>'http://ptlogin2.qq.com/getimage?aid='.$_get['aid'].'&'.@$_get['t'],
);
$r = $this->curlfunc($vfcode);
if ($r['http_code'] != 200 ) return false;
$data = split("\n", $r['html']);
preg_match('/verifysession=([^;]+);/',$data[5], $temp);
$cookie = trim($temp[1]);
$img = $data[9];
return array('img'=>$img,'cookie'=>$cookie);
}
/**
* 登陆qq邮箱
*
* @param $cookie getvfcode中生成的cookie
*
* @return array(
* sid=>string , //用户认证的唯一标示
* login => boolean, //true 登陆成功 ,false 登陆失败
* server_no => string // 服务器编号
* active => boolean //true 已开通 ,false 未开通 邮箱
* cookie => string // 获取数据cookie
*
* );
*/
function login($cookie)
{
/* 生成参数字符串 */
$post = array();
foreach($_post as $k => $v) {
$post[] = $k.'='.urlencode($v);
}
$poststr = implode('&',$post);
$r['server_no'] = $_get['server_no'];
$login = array(
'url'=>'http://'.$r['server_no'].'.mail.qq.com/cgi-bin/login?sid=0,2,zh_cn',
'header' => true,
'cookie' => 'verifysession='.$cookie,
'referer' => 'http://mail.qq.com/cgi-bin/loginpage',
'httpheader'=>array(
"host: " . $r['server_no'] . '.mail.qq.com',
"user-agent: mozilla/5.0 (windows; u; windows nt 5.1; zh-cn; rv:1.9.0.9) gecko/2009040821 firefox/3.0.9 firephp/0.2.4",
"content-type: application/x-www-form-urlencoded",
),
'post' => $poststr ,
);
$data = $this->curlfunc($login);
$data['html'] = iconv("gb2312", "utf-8", $data['html']);
if ($data['http_code'] != 200) {
$this->error($data);
return false;
}
/* 测试数据 */
//$data['html'] =file_get_contents('./r.txt');
$r['uin'] = $_post['uin'];
/* 登陆错误的判断 */
if (preg_match('|errtype=(\d)|', $data['html'], $temp_err)) {
$r['login'] = false;
if ($temp_err[1] == 1) {
$r['msg'] = '账号和密码错误';
} elseif ($temp_err[1] == 2) {
$r['msg'] = '验证码错误';
}
return $r;
}
/* 登陆成功 */
preg_match('|urlhead="([^"]+)"|i',$data['html'],$temp_url);
$urlhead = $temp_url[1];
if (preg_match('|frame_html\?sid=([^"]+)"|i',$data['html'],$temp_sid) ) {
$r['sid'] = $temp_sid[1];
$r['active'] = true;
} elseif (preg_match('|autoactivation\?sid=([^&]+)?&|i',$data['html'],$temp_sid) ) {
$r['sid'] = $temp_sid[1];
$r['active'] = false;
}
/* 登录后cookie的获取 ,在后续操作中用到 */
if (preg_match_all('|set-cookie:([^=]+=[^;]+)|i', $data['html'], $new_cookies) ) {
$cookiestr = implode('; ', $new_cookies[1]);
$cookiestr .= '; verifysession='.$cookie;
}
$r['login'] = true;
$r['cookie'] = $cookiestr;
return $r;
}
function openemail($param)
{
$openemail = array(
'url'=>'http://'.$param['server_no'].'.mail.qq.com/cgi-bin/autoactivation?actmode=6&sid='.$param['sid'],
'header' => true,
'cookie' => $param['cookie'],
'referer' => 'http://'.$param['server_no'].'mail.qq.com/cgi-bin/autoactivation?sid='.$param['sid'].'&action=reg_activate&actmode=6',
'httpheader'=>array(
"host: " . $param['server_no'] . '.mail.qq.com',
'accept-charset: gb2312,utf-8;q=0.7,*;q=0.7',
"user-agent: mozilla/5.0 (windows; u; windows nt 5.1; zh-cn; rv:1.9.0.9) gecko/2009040821 firefox/3.0.9 firephp/0.2.4",
),
);
$data = $this->curlfunc($openemail);
if (preg_match('|set-cookie:qqmail_activated=0|i', $data['html'])) {
$param['active'] = true;
$param['cookie'] = $param['cookie'] .'; qqmail_activated=0; qqmail_alias=';
}
return $param;
}
/**
*
* 获取friends数据
*
* @param $param = array(
* sid=>string , //用户认证的唯一标示
* login => boolean, //true 登陆成功 ,false 登陆失败
* server_no => string // 服务器编号
* active => boolean //true 已开通 ,false 未开通 邮箱
* cookie => string // 获取数据cookie
*
* );
* @return array(
* key=>value, // key:qq号,value: nickname
* );
*/
function getfriends($param)
{
$friend = array(
'url'=>'http://'.$param['server_no'].'.mail.qq.com/cgi-bin/addr_listall?type=user&&category=all&sid='.$param['sid'],
'header' => true,
'cookie' => $param['cookie'],
'referer' => 'http://m151.mail.qq.com/cgi-bin/addr_listall?sid='.$param['sid'].'&sorttype=null&category=common',
'httpheader'=>array(
"host: " . $param['server_no'] . '.mail.qq.com',
'accept-charset:utf-8;q=0.7,*;q=0.7',
"user-agent: mozilla/5.0 (windows; u; windows nt 5.1; zh-cn; rv:1.9.0.9) gecko/2009040821 firefox/3.0.9 firephp/0.2.4",
),
);
$r = $this->curlfunc($friend);
if ($r['http_code'] != 200) {
$this->error($r);
return false;
}
$data = $r['html'];
$preg = preg_match_all('|<p class="l_n"><span><img class="l_q" name=qqplusimg key="(\d+)"[^>]+/> ([^<]+)</span></p>|i', $data, $temp_list);
if ($preg == 0) return array();
$list = array_combine($temp_list[1],$temp_list[2]);
return $list;
}
/**
* 错误显示
*
* @param $str array
*
* @return
*/
function error($str) {
$str['html'] = str_replace('script','', $str['html']);
var_dump($str);
exit;
}
}
?>
qq_mail.rar
便于你理解, 用你的例子转换了下:
复制php内容到剪贴板
php代码:
<?php
switch($action)
{
case 'add':
add();break;
case 'modify':
modify();break;
case 'modifysave':
modifysave();break();
case 'addsave':
addsave();break;
case 'del':
del();break;
default:
main(); // 名称与php自带函数冲突 =.=!
}
?>
<?php function main() { ?>
内容
<?php }?>
php中switch语句的用法-类似asp中的select case语句
switch 循环,通常处理复合式的条件判断,每个子条件,都是 case 指令部分。在实作上若使用许多类似的 if 指令,可以将它综合成 switch 循环。
语法如下
代码:switch (expr) {
case expr1: //注意这里是冒号:
statement1; //这里是分号;
break; //这里是分号;
case expr2:
statement2;
break;
:
:
default:
statementn;
break;
}
其中的 expr 条件,通常为变量名称。而 case 后的 exprn,通常表示变量值。冒号后则为符合该条件要执行的部分。注意要用 break 跳离循环。
代码:<?php
switch (date("d")) {
case "mon":
echo "今天星期一";
break;
case "tue":
echo "今天星期二";
break;
case "wed":
echo "今天星期三";
break;
case "thu":
echo "今天星期四";
break;
case "fri":
echo "今天星期五";
break;
default:
echo "今天放假";
break;
}
?>
很明显的,上述的例子用 if 循环就很麻烦了。当然在设计时,要将出现机率最大的条件放在最前面,最少出现的条件放在最后面,可以增加程序的执行效率。上例由于每天出现的机率相同,所以不用注意条件的顺序。
asp中的select case
<%
select case action
case "add"
call add()
case "modify"
call modify()
case "modifysave"
call modifysave()
case "addsave"
call addsave()
case "del"
call del()
case else
call main()
end select
%>
<%sub main()%>
内容
<%end sub%>
这个是asp的语法.
在php中是哪个
$datetime=date("y-m-d",time());//取得目前的时间
$c=strtotime($datetime)-strtotime($votedate);
$c=ceil($c/(60*60*24));//目前的时间与开始时间差
$c求出来就是天数拉
-------------------------------
主要的论点是集中在select something from table
where to_days(now()) - to_days(date_col) < = 5; 上,我试验了半天,结果还是出错,今天看了mysql的函数,终于出来了结果,不敢独享,贴出来供大家研究,(虽然技术含量不高,别扔我柿子就行,呵呵)
mysql的to_days(date)函数是这样说明的:
传回date到公元0年的总日数,我测试了一下
mysql>select to_days(now(0));
+--------------------------+
| to_days(now()) |
+--------------------------+
| 730839 |
+--------------------------+
出来的是当前时间距离公元0年的总日数,接着我试着用上面的语句测试;
mysql>select to_days(now()) - to_days(date_col) < = 5;
出现结果:
error 1054:unknown column 'date_col' in 'field first'
此路不通了,我就试着直接把5代到date_col里去
mysql>select to_days(now()) - to_days(5);
出现结果:
+---------------------------+
|to_days(now()) - to_days(5)|
+---------------------------+
| null |
+---------------------------+
啊?不会吧?这样也不行啊?
我接着试命令
mysql>select 。。。。
突然猛的想到,嘿嘿,to_days(now())出来的是整数,我直接跟整数运算就行了,何必再to_days(date)呢?马上试验
mysql>select to_days(now()) - 5;
+--------------------------+
| to_days(now()) -5 |
+--------------------------+
| 730834 |
+--------------------------+
ok,万岁,终于得到了我想要的结果,呵呵 下面就是在php代码中用select 查询了
我存数据库向来的习惯就是dateandtime用now()直接赋值,显示的时候不用格式化,直接取出来就能用,
下面是我的一个库的部分结构
create table infomess (
infoid int(11) not null auto_increment,
topic varchar(255) not null,
……
email varchar(50),
dateandtime datetime default '0000-00-00 00:00:00' not null,
primary key (infoid)
);
这里的dateandtime是标准的日期格式,然后我要查询5天内的记录,下面是sql查询语句
$sql="select * from infomess where to_days(dateandtime) >= (to_days(now()) - 5) order by infoid desc limit $offset,$psize";
就要一个where to_days(dateandtime) >= (to_days(now()) - 5)就够了 后面的是另外的,这里的5可以设为一个变量
where to_days(dateandtime) >= (to_days(now()) - $limitdays)
然后$limitdays可以用get方式传递(多数是有get方式传递)
在你的php后面跟上?limitdays=5就行了 显示10天内也一样,$limitdasy改成10就行了
以上是利用mysql函数得到这样的结果,以上的结果都经过测试,因为时间匆忙,如果代码有什么问题,请跟帖提出,谢谢
还有朋友说利用unix戳记来得到这样的结果,请问哪位写过这样的代码,贴点出来,供大家参考比较,也可以测试判断一下php函数还是mysql函数实现的效率高
在mysql里还有几个函数直接能实现。
mysql> selectdate_add("1997-12-31 23:59:59",interval "1:1"minute_second);
返回的是1998-01-01 00:01:00
手册上有.
<?php
/* 使用unitx时间截记实现 */
$time_now =time();
$time_limit = $time_now - (60*60*24*5);
$sql ="select * from table where date>$time_limit order by xxx limitm,n";
mysql_query( $sql );
?>
---------------------
php里没有内置的日期比较函数,不过处理一下格式还是可以比较的,代码如下:
$date2="2007-1-20";
$date="2006-1-1";
if(date("y-m-d",strtotime($date))>date("y-m-d",strtotime($date2))){
echo "y";
}
else{
echo "n";
}
strtotime函数将字段值字符串转换成日期格式,作为date函数的参数,date函数将指定的日期值进行格式化,"y-m-d"为输出格式.
---------------------
<?php
//圣诞节的字符串日期
$date1 = "2008-12-25";
//获取今天日期的时间戳
$date2 = time();
//去掉$date1中的“-”
$datearr = explode("-",$date1);
//使用mktime函数将$datearr转化成时间戳
$date1int = mktime(0,0,0,$datearr[1],$datearr[2],$datearr[0]) ;
echo "$date1int 与 $date2 相比较,结果是 ".($date1int-$date2);
//获得时间戳差值
$diff=$date1int-$date2;
//用差值除以一天的总秒数(86400秒),然后使用floor四舍五入即得天数
$daysleft = floor($diff / 86400);
echo "<br>今天距离2008年圣诞节还有: $daysleft 天。";
?>
win下比较简单:
1.安装sql服务器并添加php的mssql扩展.
2.使用以下代码连接并测试
<?php
$myserver = "localhost"; //主机
$myuser = "sa"; //用户名
$mypass = "password"; //密码
$mydb = "northwind"; //mssql库名
$s = @mssql_connect($myserver, $myuser, $mypass)
or die("couldn't connect to sql server on $myserver");
$d = @mssql_select_db($mydb, $s)
or die("couldn't open database $mydb");
$query = "select titleofcourtesy+' '+firstname+' '+lastname as employee ";
$query .= "from employees ";
$query .= "where country='usa' and left(homephone, 5) = '(206)'";
$result = mssql_query($query);
$numrows = mssql_num_rows($result);
echo "<h1>" . $numrows . " row" . ($numrows == 1 ? "" : "s") . " returned </h1>";
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["employee"] . "</li>";
}
?>
代码来源:php手册
-------------------------------------------------
linux下的方法如下:(以tcp/ip 远程连接mssql)
1.安装freetds后.配置好.
一般是这样:
[mssql_2000]
host = 192.168.0.25
port = 1433
tds version = 8.0
2.编译php时.加上 --with-mssql=/freetbs的path
3.连接测试:
<?
$msconnect=mssql_connect("mssql_2000","sa","");
$msdb=mssql_select_db("northwind",$msconnect);
$msquery = "select titleofcourtesy,firstname,lastname from employees";
$msresults= mssql_query($msquery);
while ($row = mssql_fetch_array($msresults)) {
echo "<li>" . $row['titleofcourtesy'] . " " . $row['firstname'] . " " . $row['lastname'] . "</li>\n";
}
?>
最近需要从数据库中随机读取n条不重复记录,发现网上好多都是用
select * from test order by rand() limit 0,n
当数据库量大的时候排序好像费不少时间!
于是就自己写了一个,希望高手指点一二!
test的结构
id test
-----
1 asdfasfdasdf
2 sdfsdfsdf
... ...
<?php
//假设数据库已经连接了
$n = 10; //随机显示的记录数
$results = $result = array(); //记录结果的数组
$rownum = mysql_result(mysql_query( "select count(*) as cnt from test "), 0, 0);
if($rownum < 50) { //数据量小的话,这样反而可以提高效率,当然50可以随便改
$query = mysql_query( "select * from test order by rand() limit 0,$n ");
while($result = mysql_fetch_array($query)) {
$results[$result[ 'id ']] = $result;
}
} else {
//随机的范围
$maxnum = mysql_result(mysql_query( "select max(vid) as cnt from test "), 0, 0);
$minnum = 1;
$midnum = intval($maxnum / 2);
//随机的id
$randid = null;
//已存在的id集合 格式为 xx,xx,xx,xx
$existid = ' ';
$comma = ' ';
$i = 0;
while($i < $n && $minnum <= $maxnum) {
$query = ' ';
//再查询中剔除已存在的id
$existidexp = $existid ? "and id not in ($existid) " : ' ';
do{
mt_srand((float)microtime() * 1000000);
$randid = mt_rand($minnum, $maxnum);
}while(array_key_exists($randid, $results)); //如果产生id已经存在,继续随机
if($randid <= $midnum) {
$query = mysql_query( "select * from test where id <= $randid $existidexp limit 0,1 ");
if($result = mysql_fetch_array($query)) { //找到记录记录内容,重新随机
$results[$result[ 'id ']] = $result;
$existid .= $comma.$result[ 'id '];
$comma = ', ';
$i++;
} else { //没有找到记录,缩小随机的范围
$minnum++;
}
} else {
$query = mysql_query( "select * from test where id > = $randid $existidexp limit 0,1 ");
if($result = mysql_fetch_array($query)) { //找到记录记录内容,重新随机
$results[$result[ 'id ']] = $result;
$existid .= $comma.$result[ 'id '];
$comma = ', ';
$i++;
} else { //没有找到记录,缩小随机的范围
$maxnum--;
}
}
}
}
var_dump($results);
?>