跟燕十八学习PHP-第十九天-热身项目完善

 

/**
燕十八 公益PHP培训
课堂地址:YY频道88354001
学习社区:www.zixue.it
**/

<?php

/*
$sql = 'select * from user';
$rs = mysql_query($sql,$conn);

while($row = mysql_fetch_assoc($rs)) {

}

每次想取多行数据,都要如上步骤,来个while循环,能否用函数封装起来?

要求:
函数 getAll()
parm: string $sql
parm: resource $conn

return 二维数组, false
*/

$conn = mysql_connect('localhost','root','111111');
if(!$conn) {
exit('连接失败');
}

$sql = 'use test';
mysql_query($sql,$conn);


function getAll($sql,$conn) {
// 思路: 沿着$conn通道 发送$sql查询
// 再while循环,取出每一行,
// 装到一个二维数组, 再返回

$rs = mysql_query($sql,$conn);
if(!$rs) {
return false;
}

$res = array();
while($row = mysql_fetch_assoc($rs)) {
$res[] = $row;
}

return $res;
}


echo '<pre>';

$sql = 'select * from stu';

$stus = getAll($sql,$conn);
print_r($stus); // 取多行多列的函数封装

 

// 再封装一个函数,用来专门取一行的场合.
// sql = select * from stu where id=16;

$sql = 'select * from stu where id=16';
$stu = getAll($sql,$conn);

print_r($stu); // 也取出了数据,但是呢是二维数组,不方便

 


/*
getRow 取出单行数据
parm String $sql; sql语句
parm resource $conn; 资源

return 一维数组 array/ false
*/
function getRow($sql,$conn) {
$rs = mysql_query($sql,$conn);

return mysql_fetch_assoc($rs);
}


$sql = 'select * from stu where id=16';
$stu = getRow($sql,$conn);

print_r($stu); // 返回1行数组,一维数组

 


// 又提要求: 帮我查一共有多少个学生?
$sql = 'select count(*) from stu';
$num = getRow($sql,$conn);
print_r($num);
/*
返回的是1维数组,因此就返回 count(*)单元
Array
(
[count(*)] => 3
)

但此处,只是想要数值3,并不想数组形式
*/


/*
getOne
parm: String $sql sql语句
parm: resource $conn 资源

return 单个标量值
*/
function getOne($sql,$conn) {
$rs = mysql_query($sql,$conn);
$row = mysql_fetch_row($rs);

return $row[0];
}


$sql = 'select count(*) from stu';
$num = getOne($sql,$conn);
print_r($num);


<?php
/*
日期时间函数,在PHP中,也是非常常用的函数
频率仅将于字符串和数组函数


时间戳: 是指1970-01-01 00:00:00 --> 某个时刻所经历的秒数

问: 你是什么时间出生的?
答: 我是时间戳1204563241时出生的.

问: 时间戳这么不易于人来理解,为什么用时间戳来储存时间呢?
答: 理由如下
1:便于存储 2038年之前的时间戳,都没超过40亿,因此用4个字符的int型,就可以存储了.
2:时间戳就是数学上的一个值,没有歧义.
如果用格式,比如中国人 喜欢2012年01月01日,比如有人喜欢 01/01 2012 13:00:00
用时间戳没有此争论
3:时间虽然不便于给人看,但是便于给机器运算,便于比较时间差.

举例: 某张表中,有字段,存是是发帖时间, 格式是 yyyy-mm-dd hh:ii:ss
我让你取出24小时内的帖子.

得先根据当前这一瞬间 2012-03-01 09:13:25, 往前移动24小时,计算出24前的日期 ,记为A
然后 pubtime >= A, 是2012-02-28还是02-29, 得考虑平年闰年的问题
很麻烦


而用时间戳则没有此问题
只需要得出当前这一瞬间的时间戳,记为Current, 然后 Current - 24 * 3600 ,记为B
只需要 pubtime >= B 就可以了.

 

问:时间戳虽利于计算机来计算,但人眼看起来,还是不直观啊?
答:有专门的函数,用来把时间戳格式化你想要的格式,date函数

*/

echo '从1970-01-01 00:00:00到现在,已经过去',time(),'秒了';


echo '<br />';


$time = time();
echo date('m/d Y H:i',$time);


echo '<hr />';
/*
strtotime,则是把字符串形式的时间转化成时间戳
*/

$birth = '1985-05-17';
echo strtotime($birth),'<br />';


// 从当前时间,退回1天的时间戳
echo strtotime('-1 day'),'<br />';

// 退回到一周前的时间戳
echo strtotime('-1 week'),'<br />';

 

燕十八老师太幽默了, 昨天的视频如下:



posted on 2012-10-19 15:53  php小二郎  阅读(148)  评论(0编辑  收藏  举报