码迷,mamicode.com
首页 > Web开发 > 详细

PHP从入门到精通

时间:2017-10-09 00:38:29      阅读:1183      评论:0      收藏:0      [点我收藏+]

标签:tco   open   回调函数   empty   edr   install   换行   oracle   必须   

php基本语法

1.变量类型
a.标量类型
bool
integer
float
string
b.复合类型
array
object
c.特殊类型
resource
null
d.伪类型
mixd
number
callback
2.数据类型转换
a.自动类型转换
b.强制类型转换
intval(), floatval(), strval()
setType()
(bool)
(int), (integer)
(float), (double), (real)
(string)
(array)
(object)
c.类型判断函数
is_bool()
is_int(), is_integer(), is_long()
is_float(), is_double(), is_real()
is_string()
is_scalar()
is_array()
is_object()
is_resource()
is_null()
is_numeric()
is_callback()
3.常量
a.常量的定义
define(‘CONSTANT‘, $value);
defined()
b.系统预定义常量
PHP_OS
PHP_VERSION
PHP_EOL
PATH_SEPARATOR
DIRECTORY_SEPARATOR
M_PI
c.魔术常量
__CLASS__
__METHOD__
__FUNCTION__
__FILE__ 当前文件名
__LINE__ 当前行号
 
 php的函数应用
1.php变量的范围
a.局部变量
作用范围仅限于函数内部
b.全局变量
作用范围从声明处开始到本程序文件的末尾
全局变量不能自动设置为可用,局部变量会覆盖全局变量的能见度
在函数内部使用全局变量时可用global关键字声明或者使用$GLOBAL全局数组
例:
$a = 100;
$b = 200;
function test(){
    echo $a + $b;
}
test();
结果输出为0
例:
$a = 100;
$b = 200;
function test(){
    global $a, $b;
    echo $a + $b;
}
test();
结果输出为300
例:
$a = 100;
$b = 200;
function test(){
    echo $GLOBALS[‘a‘] + $GLOBALS[‘b‘];
}
test();
结果输出为300
c.静态变量
静态分配内存 的局部变量,函数执行完后静态变量不释放
例:
function test_static(){
    static $a = 0;
    echo $a;
    $a++;
}
test_static();
test_static();
test_static();
结果输出为012

2.php函数总结
可用phpinfo()或者get_loaded_extensions()查看加载了哪些函数
a.常规参数的函数
string example(string name, int age, double height)
限定参数必须为某种类型,无法展示php弱类型的优势
b.伪参数的函数
包括mixed, number, callback三种
c.引用参数的函数
使用内存地址传值,连带父程序造成影响
$a = 100;
function test(&$a){
    $a = 500;
}
test($a);
echo $a;
结果输出为500
d.默认参数的函数
e.可变参数的函数
使用func_num_args(),func_get_arg($i),func_get_args()
array(), echo(), array_merge()可以传递多个参数
例如:
function merge_array(){
    $arr_res = array();
    $arrs = func_get_args();
    foreach($arrs as $arr){
        foreach($arr as $v){
            if(!in_array($v, $arr_res)){
                array_push($arr_res, $v);
            }
        }
    }
    return $arr_res;
}
$arr_res = merge_array(array(1,2), array(1,3,4));
print_r($arr_res);
f.回调函数
使用call_user_func_array()回调用户函数或类函数
例:
call_user_func_aray(test(), array($param1, $param2));
call_user_func_aray(array(new Clazz(), test()), array($param1, $param2));
call_user_func_aray(array(Clazz, test()), array($param1, $param2));

3.递归函数
在循环语句的判断语句里调用自身
4.使用自定义函数库
include(),require(),include_once()与require_once()
include()每次执行时每次都要读取文件和评估,一般放在流程控制语句中。
require()则只需处理一次,一般放在主程序文件开头。
在多次包含同样文件时require()的效率较高
在循环包含不同文件时则用include()
include_once()和require_once()如果已经包含了制定文件则不再包含
如果包含的文件不存在,4个函数均会报错
例:
require(‘config1.php‘);
if($condition){
include(‘a.php‘);
}else{
include(‘b.php‘);
}
require(‘config2.php‘);

 

 

1.类与对象的关系
OOP   Oriented Object Programming
类:为该类的实例提供了统一的抽象描述,包括成员属性和方法两个部分
对象:系统中用来描述客观事物的一个实体

2.类的定义和类的实例化
class Clazz{
private $name;
public function getName(){
return $this->name;
}
}
$class = new Clazz();
构造与析构方法
__construct()
__destroy()
3.面向对象的三大性质
a.封装性
将对象的全部属性和全部方法集合在一起形成一个不可分割的整体,尽可能隐藏内部细节,只对外界保留有限的接口进行访问。
__set()
__get()
__isset()
__unset()
b.继承性
通过子类对已经存在的父类的功能进行扩展。
public 
protected
private
重载:子类中与父类具有相同方法名但方法体不一样。
c.多态性
通过运用抽象类或者接口,让类的不同对象对相同方法名的方法调用产生不同的效果。
抽象类:
abstract class Clazz{
protected $property;
public function getProperty(){
return $this->property;
}
abstract function do();
}
接口:
interface Able{
const CONST = 1;
function do();
}

4.面向对象的其他知识
a.一些关键字
final: 
被final修饰的类不能被继承,成员属性不能使用final修饰,被final修饰的成员方法不能被重写
static与self :
被static修饰的类的对象唯一,被static修饰的成员属性属于类唯一,  被final修饰的成员方法属于类且唯一
const:
将类中的成员属性定义成常量
instanceof:
判断对象是否为类的实例,类的子类,类是否实现了某个接口

b.魔术方法
__clone()   
使用该魔术方法克隆对象
__call()
__toString()

c.类自动加载
无需手动使用include()加载某个类,在使用时自动调用全局函数__autoload()加载该类的源文件
例:类自动加载器
function __autoload($className){
    if(file_exists($className.‘.php‘)){
        include_once($className.‘.php‘);
    }elseif(file_exists($className.‘.class.php‘)){
        include_once($className.‘.class.php‘);
    }else{
        trigger_error($className.‘相关的文件未找到‘, E_USER_ERROR);
    }
}

d.对象串行化
将对象转换为二进制在网络上传输
将对象持久化保存到文件或数据库中
serialize()  
将会自动调用魔术方法__sleep()将部分成员串行化
unserialize()
将回自动调用魔术方法__wakeup()将部分成员重新初始化

5.UML

6.设计模式

 

1.数组的定义
a.直接赋值声明数组
b.使用array()新建数组

2.数组的遍历
a.使用for遍历数组
b.使用foreach遍历数组
c.联合使用while, list(), each()遍历数组
例:
$arr = array(
    ‘a‘=>‘aaa‘,
    ‘b‘=>‘bbb‘,
    ‘c‘=>‘ccc‘,
    4
);
while(list($key, $value) = each($arr)){
    echo $key.‘=>‘.$value.‘<br/>‘;
}
结果输出为:
a=>aaa
b=>bbb
c=>ccc
0=>4
d.使用数组内部指针遍历数组
reset()  移至第一个索引位置
prev()   移至前一个索引位置
key()  移至当前索引
current()  获取当前值
next()  移至下一个索引位置
end()  移至最后一个索引位置
例:
$arr = array(
    ‘a‘=>‘aaa‘,
    ‘b‘=>‘bbb‘,
    ‘c‘=>‘ccc‘,
    4
);
echo key($arr).‘=>‘.current($arr).‘<br/>‘;
next($arr);
echo key($arr).‘=>‘.current($arr).‘<br/>‘;
end($arr);
echo key($arr).‘=>‘.current($arr).‘<br/>‘;
prev($arr);
echo key($arr).‘=>‘.current($arr).‘<br/>‘;
reset($arr);
echo key($arr).‘=>‘.current($arr).‘<br/>‘;
结果输出为:
a=>aaa
b=>bbb
0=>4
c=>ccc
a=>aaa

3.预定义数组
$GLOBALS  
$_COOKIE    
$_SESSION
$_GET
$_POST
$_REQUEST
$_ENV   
$_SERVER
$_FILES
例:
获取客户端的IP使用$_SERVER[‘REMOTE_ADDR‘]

4.数组的处理函数
a.键值操作函数
array_keys()
array_values()
array_key_exists()
in_array()   判断是否存在,返回bool
array_search()   判断是否存在,返回键名
array_flip()   交换数组中的键和值
array_reverse()  翻转数组的顺序

b.统计长度和唯一性函数
count()
array_count_values()   统计数组中元素出现个数
array_unique()
例:
$arr = array(1, ‘mysql‘, ‘1‘, ‘php‘, ‘mysql‘, ‘mysql‘);
$new_arr = array_count_values($arr);
print_r($new_arr);
结果输出为Array ( [1] => 2 [mysql] => 3 [php] => 1 )

c.作为回调函数
array_filter()
array_walk()
array_map()

d.数组排序函数
e.拆分合并分解函数
f.实现数据结构
g.其他有用函数

 

1. 文件类型
block   
char
dir 
fifo
file
link
unknown
获取文件类型
filetype($filename)

2. 文件的属性
stat()
file_exists()
filesize()
is_dir()
is_file()
is_writable()
is_executable()
is_readable()
filectime()
filemtime()
fileatime()

3. 目录操作
dirname()
basename()
pathinfo()
opendir()
readdir()
closedir()
rewinddir()
mkdir()
rmdir()

4. 遍历目录及统计目录大小
function getDirMsg($dirName){
$dirHandler = opendir($dirName);
if(!$dirHandler){
return false;
}
$fileList = array();
while($file = readdir($dirName)){
$fileName = $dirName.‘/‘.$file;
$fileSize = filesize($fileName);
array_push($fileSize, array([‘fileName‘=>$fileName, ‘fileSize‘=>$fileSize]));
}
closedir($dirHandler);
return $fileList;
}

function getDirSize($dirName){
$dirHandler = opendir($dirName);
if($dirName){
return false;
}
$dirSize = 0;
while($file = readdir($dirHandler)){
if($file != ‘.‘ && $file != ‘..‘){
$fileName = $dirName .‘/‘. $file;
if(is_dir($fileName)){
if(!($tempSize = getDirSize($fileName))){
return false;
}else{
$dirSize += $tempSize;
}
}
if(is_file($fileName)){
$dirSize += filesize($fileName);
}
}
}
return $dirSize;
}

5. 文件打开与关闭
$fileHandler = fopen($fileName, $fileMode);
bool fclose($fileHandler);
文件模式
r    从文件开头只读
r+   从文件开头读写,不覆盖后面内容
w    覆盖只写, 文件不存在则创建
w+  覆盖读写,文件不存在则创建
a  追加只写, 文件不存在则创建
a+  追加读写, 文件不存在则创建
x  只写,文件存在则警告,不存在则创建
x+  读写,文件存在则警告,不存在则创建
b  二进制打开
t  文本打开

6. 文件读写
fgetc()
fgets()
fread()
readfile()
file()
file_get_contents()

7. 移动文件指针
int ftell(fileHandler)
int fseek(fileHandler, offset)
bool rewind(handler)

8.文件的上传
a.客户端处理
例:
<form method="post" action="upload.php" enctype="multipart/form-data">
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000"/>
    上传文件<input name="uploadfile" type="file"/>
    <input type="submit" value="提交"/>
</form>
b.php.ini中的相关配置
file_uploads = On
upload_max_filesize = 2M
post_max_size = 8M
upload_tmp_dir = NULL
c.获取上传文件的信息
$_FILES[][‘name‘]
$_FILES[][‘tmp_name‘]
$_FILES[][‘type‘]
$_FILES[][‘size‘]
$_FILES[][‘error‘]  0:成功  1:超出upload_max_filesize  2:超出MAX_FILE_SIZE  3:部分上传 4:没上传任何文件 
d.文件上传函数
bool is_uploaded_file($filename)
bool move_uploaded_file($filename, $destination)
例:文件上传助手
class UploadFileUtils
{
    private $allowTypes = array();
    private $maxSize = 0;
    private $savePath = ‘‘;

    /**
     * @return array
     */
    public function getAllowTypes()
    {
        return $this->allowTypes;
    }

    /**
     * @param array $allowTypes
     */
    public function setAllowTypes($allowTypes)
    {
        $this->allowTypes = $allowTypes;
    }

    /**
     * @return int
     */
    public function getMaxSize()
    {
        return $this->maxSize;
    }

    /**
     * @param int $maxSize
     */
    public function setMaxSize($maxSize)
    {
        $this->maxSize = $maxSize;
    }

    /**
     * @return string
     */
    public function getSavePath()
    {
        return $this->savePath;
    }

    /**
     * @param string $savePath
     */
    public function setSavePath($savePath)
    {
        $this->savePath = $savePath;
    }

    public function upload(){
        if(empty($_FILES)) {
            throw new Exception(‘未选择文件‘);
        }
        $fileInfo = array_values($_FILES);
        //判断错误
        if($fileInfo[0][‘error‘] > 0){
            switch($fileInfo[0][‘error‘]){
                case 1:
                    throw new Exception(‘超过了配置项upload_max_filesize的设置‘);
                    break;
                case 2:
                    throw new Exception(‘超过了表单中MAX_FILE_SIZE的设置‘);
                    break;
                case 3:
                    throw new Exception(‘文件部分上传‘);
                    break;
                case 4:
                    throw new Exception(‘文件没有上传‘);
                    break;
                default:
                    throw new Exception(‘未知错误‘);
            }
        }
        //判断文件类型
        $type = array_pop(explode(‘.‘, $fileInfo[0][‘name‘]));
        if(!in_array($type, $this->getAllowTypes())){
            throw new Exception(‘文件类型为{$type}不符要求‘);
        }
        //判断文件大小
        $size = $fileInfo[0][‘size‘];
        if($size > $this->getMaxSize()){
            throw new Exception(‘文件大小为{$size}不符要求‘);
        }
        //判断是否为用户上传的文件
        $tmp_name = $fileInfo[0][‘tmp_name‘];
        if(!is_uploaded_file($tmp_name)){
            throw new Exception(‘文件暂存名为{$size}不是用户要上传的文件‘);
        }
        //上传到服务器指定目录
        $dest_name = rtrim($this->getSavePath(), DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR.date(‘YmdHis‘).rand(1000, 9999).‘.‘.$type;
        if(!move_uploaded_file($tmp_name, $dest_name)){
            throw new Exception(‘文件上传到服务器失败‘);
        }else{
            return $dest_name;
        }
    }
}

9.文件的下载
例:文件下载助手
class DownloadFileUtils
{
    private $filepath;
    private $mimetype;

    /**
     * DownloadFileUtils constructor.
     * @param $filepath
     * @param $mimetype
     */
    public function __construct($filepath, $mimetype)
    {
        $this->filepath = $filepath;
        $this->mimetype = $mimetype;
    }

    /**
     * @return mixed
     */
    public function getFilepath()
    {
        return $this->filepath;
    }

    /**
     * @param mixed $filepath
     */
    public function setFilepath($filepath)
    {
        $this->filepath = $filepath;
    }

    /**
     * @return mixed
     */
    public function getMimetype()
    {
        return $this->mimetype;
    }

    /**
     * @param mixed $mimetype
     */
    public function setMimetype($mimetype)
    {
        $this->mimetype = $mimetype;
    }

    public function download(){
//        $fp = finfo_open(FILEINFO_MIME);
//        $mime_type = finfo_file($fp, $this->getFilepath());
//        finfo_close($fp);
        header(‘Content-type:{$this->getMimetype()}‘);
        //指定文件作文附件下载
        header(‘Content-Disposition:attachment;filename=‘.$this->getFilepath());
        //指定文件的大小
        header(‘Content-Length:‘.file$this->getFilepath());
        //输出文件内容进行下载
        readfile($this->getFilepath());
    }
}

 

1.将格式化时间转化为时间戳
time()
microtime(true)     当前时间戳,小数点前为秒,小数点后为微秒
mktime(hour, minute, second, month, day, year)
strtotime(timestr)

2.将时间戳格式化
getdate($time)
date($format, $time)

3.修改默认时区
a.php.ini中的配置项
date.timezone=Etc/GMT-8
b.直接修改
date_default_timezone_set(‘RPC‘)

4.例:程序计时器
class TimeUtils
{
    private $startAt;
    private $stopAt;

    /**
     * @return mixed
     */
    public function getStartAt()
    {
        return $this->startAt;
    }

    /**
     * @param mixed $startAt
     */
    public function setStartAt($startAt)
    {
        $this->startAt = $startAt;
    }

    /**
     * @return mixed
     */
    public function getStopAt()
    {
        return $this->stopAt;
    }

    /**
     * @param mixed $stopAt
     */
    public function setStopAt($stopAt)
    {
        $this->stopAt = $stopAt;
    }

    public function start(){
        $this->setStartAt(microtime(true));
    }

    public function stop(){
        $this->setStopAt(microtime(true));
    }

    public function spend(){
        return round($this->getStopAt() - $this->getStartAt(), 4);
    }
}

5.例:日历

 

 
 
1.为什么使用会话控制
答:因为http协议是无状态的,http协议没有一个内建的机制来维护两个事务之间的状态;
会话控制的思想是允许服务器跟踪同一个客户端做出的连续请求。

2.会话控制的方式
a.使用超链接,header(), 网页中隐藏表单存储客户资料。
b.使用cookie存放于客户端计算机中,其他程序通过读取客户端cookie存取客户资料。
c.使用session存放于服务器计算机中,其他程序读取服务端session获取客户资料。

3.设置cookie
setcookie($key, $value, $expire, $path, $domian, $secure);
例:
setcookie(‘username‘, ‘liudaoqiang‘, 3600 * 24 * 7, ‘/test‘, ‘example.com‘, 1);

4.配置session和使用session
a.php.ini中的session配置
session.auto_start
session.cookie_domain
session.cookie_lifetime
session.cookie_path
session.name
session.save_path
session.use_cookies
session.use_trans_sid
session.gc_probability
session.gc_divisor
session.gc_maxlifetime
session.save_handler

b.使用session
注册session
session_start();
$_SESSION[‘username‘] = ‘liudaoqiang‘;
注销session
session_start();
$_SESSION = array();
if(isset($_COOKIE[session_name()])){
setcookie(session_name(), ‘‘, time() - 1, ‘/‘);
}
session_destroy();

5.自定义session处理方式
session_set_save_handler(‘open‘, ‘close‘, ‘read‘, ‘write‘, ‘destroy‘, ‘gc‘);
session_start();
例:
$session_path = ‘‘;
function open($_session_path, $session_name){
    global $session_path;
    $session_path = $_session_path;
    return true;
}
function close(){
    return true;
}
function read($session_id){
    global $session_path;
    $session = @file_get_contents(‘{$session_path}/sess_{$session_id}‘);
    return $session;
}
function write($session_id, $session){
    global $session_path;
    $session_file = ‘{$session_path}/sess_{$session_id}‘;
    if(!($fp = fopen($session_file, ‘w‘))){
        return false;
    }else{
        fwrite($fp, $session);
        fclose($fp);
    }
}
function destroy($session_id){
    global $session_path;
    $session_file = ‘{$session_path}/sess_{$session_id}‘;
    return @unlink($session_file);
}
function gc($session_maxlifetime){
    global $session_path;
    $session_file = ‘{$session_path}/sess_*‘;
    foreach(glob($session_file) as $file){
        if(filemtime($file) + $session_maxlifetime < time()){
            @unlink($file);
        }
    }
    return true;
}
session_set_save_handler(‘open‘, ‘close‘, ‘read‘, ‘write‘, ‘destroy‘, ‘gc‘);
session_start();

 

1.mvc框架具备的功能
a.目录组织结构
b.类自动加载
c.可继承基础类库
d.url的管理
e.输入验证
f.错误异常处理
g.扩展工具类
例如:rbac, 代码生成工具,分页工具,上传工具,验证码工具


2.比较流行的mvc框架
a.Yii
b.ZendFramwork
c.laravel
d.ThinkPHP
e.CakePHP
f.CodeIgniter
g.Symfony
h.Kohana
i.PHPDevShell

3.常见项目
cms
crm
oa
cns
电商
1.常用字符串输出函数
echo  输出一个或多个字符串
echo()  输出一个字符串
die()  输出一条消息并退出当前脚本
print() 与echo()一样,只是有bool返回值,效率没有echo()高
printf()  格式化输出字符串
spintf()  将格式化字符串写入到一个变量中

2.常用字符串格式化函数
a.去除空格和字符串填补函数
trim()
ltrim()
rtrim()
str_pad()  扩充字符串
例:去除变量左右两边的数字和大写字母及点
$str = ‘123 This is a test ...‘;
echo trim($str, ‘0..9 A..Z .‘);
结果输出为his is a test
例:对LAMP进行字符串填充
echo str_pad(‘LAMP‘, 9, ‘-‘, STR_PAD_BOTH);
结果输出为--LAMP---

b.字符串大小写转换函数
strtolower()
strtoupper()
ucfirst()  字符串首字母大写
ucwords()  单词首字母大写

c.html标签相关字符串格式化函数
nl2br()   在字符串换行符处插入<br/>
htmlspecialchars()   将html标记中特殊字符转换为html实体
htmlentities()   将所有非ASCII码字符转换为对应实体
stripslashes()   删除‘  ‘‘   \等字符自动添加的反斜线
addslashes()    在‘  ‘‘   \等字符自动添加反斜线
strip_tags()    保留部分html标记
例:
echo nl2br(‘One line.\nAnother line.‘);
echo htmlspecialchars($str, ENT_COMPAT); 转换html标记和双引号
echo htmlspecialchars($str, ENT_QUOTES); 转换html标记和两种引号
echo htmlspecialchars($str, ENT_NOQUOTES); 转换html标记和不对引号转换
echo strip_tags($str, ‘<font><b>‘);   去除html标记除<font><b>外

d.其他字符串格式化函数
strrev()    反转字符串
number_format()
md5()

e.按字节顺序比较字符串函数
strcmp()   区分字母大小写比较
strcasecmp()   不区分字母大小写比较
大于则返回1,小于返回-1, 等于返回0

f.按自然顺序比较字符串函数
strnatcmp()
strnatcasecmp()

 

1.常见正则表达式
url:   ‘/[a-zA-Z]+://[^\s]*/‘
html:   ‘/<(\S*?)[^>]*>.*?</\1>|<.*?/>/i‘
email:    

2.正则表达式语法规则
a.定界符
//
||
!!
{}
b.原子
普通字符
a-z
A-Z
0-9
特殊字符
\‘
\"
\.
\*
\+
非打印字符
\f      换页符
\n     换行符
\r      回车符
\t      制表符
\v     垂直制表符
通用字符类型
\d    十进制数字,相当于[0-9]
\D    非十进制数字,相当于[^0-9]
\s     空白字符,相当于[\f\n\r\t\v]
\S     非空白字符,相当于[^\f\n\r\t\v]
\w    字母数字下划线,相当于[0-9a-zA-z_]
\W   非字符数字下划线,相当于[^0-9a-zA-Z_]
c.元字符
?
*
+
.
|
{n}
{n,}
{n, m}

d.模式修正符


3.正则表达式函数
a.字符串的查找
int preg_match($pattern, $subject, $matches)
int preg_match_all($pattern, $subject, $matches)
preg_grep()
strstr(), strpos(), strrpos(), substr()
b.字符串的替换
preg_replace()
str_replace()
c. 字符串的分割与连接
preg_split()
explode()
implode()

 

1.数据库管理
a.结构化查询语句sql
DDL:
数据定义语言,定义和管理数据对象如数据库和数据表
DQL
数据查询语言,查询数据表中的数据
DML
数据操作语言,增删改数据表中的数据
DCL
数据控制语言,包括权限和事务
b.数据库的连接与关闭
mysql -h 数据库主机地址 -u 用户名 -p 密码
c.权限管理
grant insert,delete,update,select on db.table to user@host identified by pass
d.数据库管理
create database if not exists dbnane;
drop dbname if exists dbname;
show databases;
use dbname;

2.数据表管理
a.表类型
MyISAM
不支持事务,支持表锁定,不支持外键约束,支持全文索引
InnoDB
支持事务,支持表锁定,支持外键约束,不支持全文索引
HEAP
BOB
ARCHIVE
CSV
例:
create table t type=myisam;
create table t engine=innodb;
b.表默认字符集
ASCII
ISO-8859
Unicode
my.ini的配置项:
character-set-server = gbk
collation-server = gbk-chinese-ci
例:
CREATE DATABASE IF NOT EXISTS mydb DEFAULT CHARACTER SET utf8 COLLATION utf8-general-ci;
c.表操作
创建表:
CREATE TABLE IF NOT EXISTS customer (
id int(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
username varchar(50) NOT NULL, 
phone varchar(20) NOT NULL UNIQUE,
sex ENUM(‘男‘, ‘女‘) NOT NULL DEFAULT ‘男‘,
INDEX username(username)
) TYPE=MyISAM DEFAULT CHARACTER SET utf8 COLLATION utf8-general-ci;
删除表:
DROP TABLE IF EXISTS customer;
修改表:
ALTER TABLE customer ADD created_at int(10) AFTER sex;
d.字段类型
TINYINT, SMALLINT, MEDIUMINT, INT, BIGINT
FLOAT, DOUBLE, DECIMAL
CHAR, VARCHAR
TINYBLOB, SMALLBLOB, MEDIUMBLOB, BLOB, LONGBLOB
TINYTEXT, SMALLTEXT, MEDIUMTEXT, TEXT, LONGTEXT
ENUM(‘value1‘, ‘value2‘)
SET(‘value1‘, ‘value2‘)
e.字段属性
UNSIGNED
ZEROFILL
DEFAULT
NULL/NOT NULL
AUTO_INCREMENT
f.字段索引
PRIMARY KEY
UNIQUE
INDEX
FULLTEXT

3.数据增删改查
a.DML的insert
例:
INSERT INTO  desttb(destfield1, destfield2, destfield3) VALUES(
SELECT srcfield1, srcfield2, srcfield3 FROM srctb
);
b.DML的delete
DELETE FROM tb WHERE condition ORDER BY field ASC/DESC LIMIT num;
c.DML的update
UPDATE tb1 AS t1, tb2 AS t2 SET t1.field = expression WHERE t1.field = t2.field WHERE condition ORDER BY field ASC/DESC LIMIT num;
d.DQL
SELECT ALL/DISTINCT tb.field AS alias FROM tb LEFT JOIN jtb AS jt ON tb.field = jt.field WHERE condition GROUP BY gfield1, gfield2 HAVING gcondition ORDER BY ofield ASC/DESC LIMIT num;
注意:
ALL与DISTINCT
特定字段与*
COUNT(), SUM(), AVG(), MAX(), MIN()
AS
JOIN ON
子查询IN(SELECT ...)
IS NULL与IS NOT NULL
BETWEEN AND与NOT BETWEEN AND
IN与NOT IN
LIKE与NOT LIKE
GROUP BY HAVING
ORDER BY LIMIT

4.mysql扩展函数
a.连接与关闭
mysql_connect($host, $user, $pass)
mysql_select_db($dbname, $link)
mysql_close($link)
mysql_error()
mysql_errno()
mysql_get_client_info()
mysql_client_encoding()
mysql_get_host_info()
mysql_get_server_info()
mysql_get_proto_info()
mysql_stat()
b.执行sql
mysql_query()
mysql_affected_rows()
mysql_num_rows()
musql_num_fields()
mysql_fetch_row()
mysql_fetch_assoc()
mysql_fetch_array()
mysql_fetch_object()
例:分页助手类
class PageUtils
{
    private $query;
    private $noSum;
    private $numPerPage;
    private $pageNo;
    private $pageSum;
    private $data;

    private $link;

    /**
     * PageUtils constructor.
     * @param $query
     * @param $noSum
     * @param $numPerPage
     */
    public function __construct($query, $noSum, $numPerPage)
    {
        $this->query = $query;
        $this->noSum = $noSum;
        $this->numPerPage = $numPerPage;
    }

    /**
     * @return mixed
     */
    public function getQuery()
    {
        return $this->query;
    }

    /**
     * @param mixed $query
     */
    public function setQuery($query)
    {
        $this->query = $query;
    }

    /**
     * @return mixed
     */
    public function getNumPerPage()
    {
        return $this->numPerPage;
    }

    /**
     * @param mixed $numPerPage
     */
    public function setNumPerPage($numPerPage)
    {
        $this->numPerPage = $numPerPage;
    }

    /**
     * @return mixed
     */
    public function getPageNo()
    {
        return $this->pageNo;
    }

    /**
     * @param mixed $pageNo
     */
    public function setPageNo($pageNo)
    {
        $this->pageNo = $pageNo;
    }

    /**
     * @return mixed
     */
    public function getNoSum()
    {
        return $this->noSum;
    }

    /**
     * @param mixed $noSum
     */
    public function setNoSum($noSum)
    {
        $this->noSum = $noSum;
    }

    /**
     * @return mixed
     */
    public function getPageSum()
    {
        return $this->pageSum;
    }

    /**
     * @param mixed $pageSum
     */
    public function setPageSum($pageSum)
    {
        $this->pageSum = $pageSum;
    }

    /**
     * @return mixed
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param mixed $data
     */
    public function setData($data)
    {
        $this->data = $data;
    }

    /**
     * @return mixed
     */
    public function getLink()
    {
        return $this->link;
    }

    /**
     * @param mixed $link
     */
    public function setLink($link)
    {
        $this->link = $link;
    }

    public function page(){
        if(!isset($_GET[‘pageNo‘])){
            $this->setPageNo(1);
        }else{
            $this->setPageNo($_GET[‘pageNo‘]);
        }
        $sql = $this->getQuery().‘ LIMIT ‘.$this->getNumPerPage().‘ OFFSET ‘.$this->getNumPerPage()*($this->getPageNo() - 1);
        $result = mysql_query($sql, $this->getLink());
        $data = array();
        while($row = mysql_fetch_array($result)){
            array_push($data, $row);
        }
        $this->setData($data);
        $this->update();
        return $this->getData();
    }

    private function update(){
        $this->setNoSum(count($this->getData()));
        $this->setPageSum(floor(count($this->getData())/$this->getNumPerPage()));
    }
}

5.mysql抽象层PDO
a.PDO的安装
extension=php_pdo.dll
extension=php_pdo_mysql.dll
b.PDO对象
new PDO(‘mysql:dbname=test;host=127.0.0.1;charset=UTF-8‘, ‘root‘, ‘pass‘, $option);
new PDO(‘uri:file:///user/local/dbconnect‘, ‘root‘, ‘pass‘, $option);
php.ini中pdo.dsn.mysqlpdo=‘mysql:dbname=test;host=127.0.0.1;charset=UTF-8‘;
new PDO(‘mysqlpdo‘, ‘root‘, ‘pass‘, $option);
PDO::ATTR_AUTOCOMMIT
PDO::ATTR_CASE
PDO::ATTR_ERRMODE
PDO::ATTR_PERSISTENT
PDO::ATTR_ORACLE_NULLS
PDO::ATTR_PREFETCH
PDO::ATTR_TIMEOUT
PDO::ATTR_SERVER_INFO
PDO::ATTR_SERVER_VERSION
PDO::ATTR_CLIENT_VERSION
PDO::ATTR_CONNECTION_STATUS
getAvailableDrivers()
getAttribute()
setAttribute()
errorCode()
errorInfo()
quote()
prepare()
query()
exec()
lastInsertId()
beginTransaction()
commit()
rollback()
c.PDOStatement对象
getAttribute()
setAttribute()
errorCode()
errorInfo()
bindColumn()
bindParam()
bindValue()
execute()
rowCount()
setFetchMode()
fetch()
fetchAll()
fetchColumn()
fetchObject()
columnCount()
getMetaData()
nextRowSet()
closeCursor()
d.事务
性质:ACID
原子性:Atomicity
一致性:Consistency
独立性:Isolation
持久性:Durability
SET AUTOCOMMIT = 0;
START TRANSACTION;
COMMIT;
ROLLBACK;

 

1.memcache的安装和管理
a.安装
memcached.exe -d install
若安装时提示找不到某dll文件则下载该dll文件放入c:/windows/system32目录中
b.卸载
memcached.exe -d uninstall
c.启动
memcached.exe -d start
d.停止
memcached.exe -d stop
-d 以守护程序方式运行
-m 分配内存数量
-u 指定运行的用户
-l 监听的服务器ip地址
-p 监听端口
-c 最大并发连接数
-p 指定pid文件
-vv  调试信息和错误信息到控制台

2.使用telnet作为memcache的客户端
若未开启telnet客户端则开启,开启方法如下
控制面板>程序和功能>启用或关闭windows功能>开启telnet客户端
telnet localhost 11211  使用telnet连接memcache
stat      查看memcached服务器的运行状态
add      增
delete    删
set     改
get     查

3.使用php操作memcache
a.安装配置
将下载的php_memcache.dll保存到ext目录下
在php.ini中加入extension=php_memcache.dll
重启web服务器
b.php.ini中memcache的配置选项
memcache.allow_failover
memcache.chunk_size
memcache.default_port
memcache.hash_function
memcache.hash_strategy
memcache.max_failover_attempts
c.Memcache的api
Memcache::connect($host, $port, $timeout)
Memcache::pconnect($host, $port, $timeout)
Memcache::addServer($host, $port)
Memcache::close()
Memcache::getStats()
Memcache::add($key, $value, $flag, $expire)
Memcache::set($key, $value, $flag, $expire)
Memcache::replace($key, $value, $flag, $expire)
Memcache::get($key)
Memcache::delete($key)
Memcache::flush()

 


PHP从入门到精通

标签:tco   open   回调函数   empty   edr   install   换行   oracle   必须   

原文地址:http://www.cnblogs.com/liuzhiqaingxyz/p/7639185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!