国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
PHP筆記(PHP高級(jí)篇),php筆記
Home php教程 php手冊(cè) PHP筆記(PHP高級(jí)篇),php筆記

PHP筆記(PHP高級(jí)篇),php筆記

Jun 13, 2016 am 09:07 AM
php

PHP筆記(PHP高級(jí)篇),php筆記

高級(jí)篇中將涉及數(shù)據(jù)庫(kù)的使用以及Cookie和Session會(huì)話(huà),提高PHP的開(kāi)發(fā)效率和運(yùn)行效率

?

PHP程序員需要掌握的MySQL操作

  • 為項(xiàng)目設(shè)計(jì)表
  • 使用SQL語(yǔ)句
  • MySQL的目錄結(jié)構(gòu)
    • data目錄中存放的是庫(kù)文件
    • bin目錄中存放的是MySQL管理命令
    • *.ini文件記錄的是MySQL的配置

連接MySQL DB:

  • mysql -h sql地址 -u 用戶(hù)名 -p密碼,如mysql -h localhost -u root -p123456
  • 安全的方法:先輸入“mysql -h sql地址 -u 用戶(hù)名 -p”,回車(chē),再輸入密碼

?數(shù)據(jù)定義語(yǔ)言(DDL)

  • 定義:用來(lái)創(chuàng)建數(shù)據(jù)庫(kù)中的各種對(duì)象-----表、視圖、索引、同義詞、聚簇等
  • SQL語(yǔ)句
    • 創(chuàng)建數(shù)據(jù)庫(kù)
    • <span>CREATE</span> <span>DATABASE</span> <span>[</span><span>IF NO EXISTS</span><span>]</span> DatabaseName
    • 創(chuàng)建表
<span>CREATE</span> <span>TABLE</span> <span>[</span><span>IF NOT EXISTS</span><span>]</span><span> TableName (
colname1 type </span><span>[</span><span>property</span><span>]</span> <span>[</span><span>index</span><span>]</span><span>,
colname2 type </span><span>[</span><span>property</span><span>]</span> <span>[</span><span>index</span><span>]</span><span>,
...
)[tableType] [tableCharSet];</span>
  • 修改表
    • alter table 操作
  • 數(shù)據(jù)類(lèi)型
    • 數(shù)值型
      • UNSIGNED:指定為無(wú)符號(hào)存儲(chǔ)
      • 整型
        • TINYINT 1 Byte (-128,127) (0,255) 小整數(shù)值
          SMALLINT 2 Byte (-32 768,32 767) (0,65 535) 大整數(shù)值
          MEDIUMINT 3 Byte (-8 388 608,8 388 607) (0,16 777 215) 大整數(shù)值
          INT或INTEGER 4 Byte (-2 147 483 648,2 147 483 647) (0,4 294 967 295) 大整數(shù)值
          BIGINT 8 Byte (-9 233 372 036 854 775 808,9 223 372 036 854 775 807) (0,18 446 744 073 709 551 615) 極大整數(shù)值
      • 浮點(diǎn)型
        • FLOAT 4 字節(jié) (-3.402 823 466 E+38,1.175 494 351 E-38),0,(1.175 494 351 E-38,3.402 823 466 351 E+38) 0,(1.175 494 351 E-38,3.402 823 466 E+38)
        • DOUBLE 8 字節(jié) (1.797 693 134 862 315 7 E+308,2.225 073 858 507 201 4 E-308),0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308) 0,(2.225 073 858 507 201 4 E-308,1.797 693 134 862 315 7 E+308)
    • 字符型
      • CHAR 0-255Byte 定長(zhǎng)字符串,
        VARCHAR 0-255Byte 變長(zhǎng)字符串,必須指定長(zhǎng)度
        TINYBLOB 0-255Byte 不超過(guò) 255 個(gè)字符的二進(jìn)制字符串
        TINYTEXT 0-255Byte 短文本字符串
        BLOB 0-65 535Byte 二進(jìn)制形式的長(zhǎng)文本數(shù)據(jù)
        TEXT 0-65 535Byte 長(zhǎng)文本數(shù)據(jù)
        MEDIUMBLOB 0-16 777 215Byte 二進(jìn)制形式的中等長(zhǎng)度文本數(shù)據(jù)
        MEDIUMTEXT 0-16 777 215Byte 中等長(zhǎng)度文本數(shù)據(jù)
        LOGNGBLOB 0-4 294 967 295Byte 二進(jìn)制形式的極大文本數(shù)據(jù)
        LONGTEXT 0-4 294 967 295Byte 極大文本數(shù)據(jù)
      • CHAR的處理速度比較快,VARCHAR具有可變大小
      • 二進(jìn)制保存主要用于保存非文本文件
      • ENUM,枚舉類(lèi)型,最多能存儲(chǔ)65535個(gè)值,一個(gè)字段只能存一個(gè)值
      • SET,集合類(lèi)型,最多可存儲(chǔ)64個(gè)值,一個(gè)值段可存多個(gè)值
    • 日期型
      • DATE 3Byte 1000-01-01/9999-12-31 YYYY-MM-DD 日期值
        TIME 3Byte '-838:59:59'/'838:59:59' HH:MM:SS 時(shí)間值或持續(xù)時(shí)間
        YEAR 1Byte 1901/2155 YYYY 年份值
        DATETIME 8Byte 1000-01-01 00:00:00/9999-12-31 23:59:59 YYYY-MM-DD HH:MM:SS 混合日期和時(shí)間值
        TIMESTAMP 8Byte 1970-01-01 00:00:00/2037 年某時(shí) YYYYMMDD HHMMSS 混合日期和時(shí)間值,時(shí)間戳

※任何數(shù)據(jù)類(lèi)型以字符串的形式存入,都可以自動(dòng)轉(zhuǎn)換類(lèi)型

※將時(shí)間保存為php時(shí)間戳,方便運(yùn)算

數(shù)據(jù)字段屬性

  • unsigned:設(shè)置該字段為無(wú)符號(hào)數(shù)值,只能是數(shù)值型
  • zerofill:設(shè)置該字段的記錄的值未達(dá)到指定位數(shù)時(shí),用“0”填充,只能是數(shù)值型
  • auto_increment:設(shè)置該字段的值自動(dòng)增長(zhǎng),也可設(shè)定自定義值,需要同時(shí)設(shè)定索引或主鍵,只能是數(shù)值型
  • null和not null:設(shè)置該字段是否允許為空,建議設(shè)定為非空,配合default使用
  • default:設(shè)置該字段的默認(rèn)值,若不輸入,使用默認(rèn)值

索引

  • 優(yōu)點(diǎn):
    • 提高查詢(xún)速度
  • 缺點(diǎn):
    • 創(chuàng)建和維護(hù)成本比較高
    • 占用資源
  • 主鍵索引(primary key):索引值必須唯一,每張表只有一個(gè)
  • 唯一索引(unique):索引值必須唯一,但一張表可以有多個(gè)
  • 常規(guī)索引(index):最基本的索引,沒(méi)有太多的限制
  • 全文索引(filltext):只能在MyISAM上使用,表越大,效果越好,但速度較慢
  • 創(chuàng)建和使用,可查看MySQL索引類(lèi)型一覽表 讓MySQL高效運(yùn)行起來(lái)

數(shù)據(jù)表類(lèi)型及存儲(chǔ)位置

  • MySQL可以針對(duì)不同的存儲(chǔ)引擎需求可以選擇最優(yōu)的存儲(chǔ)引擎
  • 數(shù)據(jù)表類(lèi)型即存儲(chǔ)引擎
  • 使用type或engine關(guān)鍵字指定表類(lèi)型
  • 常用的表類(lèi)型
    • MyISAM
      • 強(qiáng)調(diào)快速讀取操作
      • 對(duì)一些功能不支持(事務(wù))
    • InnoDB
      • 支持一些MyISAM不支持的功能
      • 不支持全文索引
        • 占用空間比較大
          功能 MyISAM InnoDB
          事務(wù)處理 不支持 支持
          數(shù)據(jù)行鎖定 不支持 支持
          外鍵約束 不支持 支持
          表空間占用 相對(duì)較小 較大
          全文索引 支持 不支持

MySQL默認(rèn)字符集

  • 推薦utf8
  • 字符集:用來(lái)定義MySQL存儲(chǔ)字符串的方式
    • 使用character set關(guān)鍵字指定字符集
  • 校對(duì)規(guī)則:對(duì)規(guī)則定義了比較字符串的方式
    • 使用collate指定校對(duì)規(guī)則

數(shù)據(jù)操作語(yǔ)言(DML)

  • 主要有三種形式:
    • 1) 插入:INSERT
      • insert into tablename[(字段列表)] values(值列表1)[,(值列表2)...]
        • 表名后面,若有字段列表,則值列表與字段列表一一對(duì)應(yīng),若沒(méi)有字段列表,則值列表與表中的字段一一對(duì)應(yīng)
    • 2) 更新:UPDATE
      • update tablename set 字段名='值' [條件]
    • 3) 刪除:DELETE
      • delete from tablename [條件]
    • 可以使用運(yùn)算符,包括算術(shù)運(yùn)算符、邏輯運(yùn)算符、比較運(yùn)算符、位運(yùn)算符

數(shù)據(jù)查詢(xún)語(yǔ)言(DQL)

  • 基本結(jié)構(gòu)是由SELECT[ALL|DISTINCT]子句,F(xiàn)ROM子句,WHERE
    • 子句組成的查詢(xún)塊:
      • SELECT <字段列表>
      • FROM <表或視圖名>
      • [WHERE<查詢(xún)條件>/GROUP BY/ORDER BY]
    • DISTINCT表示不顯示重復(fù)的記錄
    • 使用as關(guān)鍵字,可為字段名起別名,用于可能產(chǎn)生歧義的字段名

數(shù)據(jù)控制語(yǔ)言(DCL)

  • 定義:用來(lái)授予或回收訪(fǎng)問(wèn)數(shù)據(jù)庫(kù)的某種特權(quán),并控制數(shù)據(jù)庫(kù)操縱事務(wù)發(fā)生的時(shí)間及效果,對(duì)數(shù)據(jù)庫(kù)實(shí)行監(jiān)視等。

MySQL內(nèi)置函數(shù)

  • 位置:select語(yǔ)句,及子句where order by having 中,update delete語(yǔ)句及子句
  • 函數(shù)中可以將字段名當(dāng)作變量來(lái)用,變量的值就是該列對(duì)應(yīng)的所有值
  • 常用
    • 字符串函數(shù)
      • concat:把傳入的參數(shù)連接成一個(gè)字符串
      • insert(str,x,y,insert):從str的x位置開(kāi)始,替換y長(zhǎng)度的字符串為insert
      • lower(str),upper(str):將字符串轉(zhuǎn)換為大寫(xiě),小寫(xiě)
      • left(str,x) right(str,x) 返回str左邊(右邊)x個(gè)字符,x為null則返回null
      • lpad(str,n,pad) rpad(str,n,pad) 用pad對(duì)字符串str從最左邊(右邊)進(jìn)行填充,直到總長(zhǎng)度n
      • trim(str),ltrim(str),rtrim(str)去掉兩邊,左邊,右邊空格
      • replace(str,a,b) 在字符串str中用字符串b替換所有的字符串a(chǎn)
      • strcmp(s1,s2):如果S1比S2小,返回-1;如果S1比S2大則返回1;如果相等則返回0(比較的是ASCII碼)

      • substring(str,x,y) 返回字符串str中從位置x起,長(zhǎng)度為y的子字符串
    • 數(shù)值函數(shù)
      • abs(x):返回絕對(duì)值
      • ceil(x):返回大于x的最小整數(shù)
      • floor(x):返回小于x的最大整數(shù)
      • mod(x,y):返回x與y的模
      • rand():返回0-1之間的隨機(jī)數(shù)
      • round(x,y):返回參數(shù)x的y位小數(shù)的四舍五入結(jié)果
      • truncate(x,y):返回?cái)?shù)字x截?cái)酁閥位小數(shù)的結(jié)果
    • 日期函數(shù)
      • curdate():返回當(dāng)前年月日
      • curtime():返回當(dāng)前時(shí)分秒
      • now():返回當(dāng)前日期
      • unix_timestamp(time):返回unix時(shí)間戳
      • from_unixtime():將Unix時(shí)間戳轉(zhuǎn)換為日期
      • week():返回時(shí)間戳的周
      • year():返回時(shí)間戳的年
      • hour():返回時(shí)間戳的小時(shí)
      • minute():返回時(shí)間戳的分鐘
      • month():返回時(shí)間戳的月
      • date_format(time,"%Y-%m-%d %H:%i:%s"):格式化返回時(shí)間
    • 流程控制函數(shù)
      • if(value,t,f):如果value值為true,返回t,如果value值為false,返回f
      • ifnull(value1,value2):如果value1為空,則返回value2,如果value1不為空,返回value1
      • case
        when value1 then value2
        when value3 then value4
        ......
        else fault END
        • 當(dāng)value1為true,返回value2,當(dāng)value3位true,返回value4,以此類(lèi)推,否則返回fault
        • 其他用法:mysql 語(yǔ)句case when
    • 其他函數(shù)
      • database():返回?cái)?shù)據(jù)庫(kù)名
      • version():返回MySQL版本
      • user():返回MySQL的用戶(hù)
      • inet_aton(ip):將IP轉(zhuǎn)換為網(wǎng)路字節(jié)序
      • inet_nton():將網(wǎng)絡(luò)字節(jié)序轉(zhuǎn)為IP
      • password():MySQL用戶(hù)密碼加密
      • md5(str):將字符串加密

PHP操作數(shù)據(jù)庫(kù)

  • 連接數(shù)據(jù)庫(kù)
    • mysql_connect(IP,user,psw):IP為數(shù)據(jù)庫(kù)地址,user為用戶(hù)名,psw為用戶(hù)密碼,連接成功,返回?cái)?shù)據(jù)庫(kù)資源,連接失敗,返回false
  • 選擇庫(kù)
    • mysql_select_db($dbname,[$res]):$dbname為庫(kù)名稱(chēng);$res為連接數(shù)據(jù)庫(kù)是返回的資源,若不添加該參數(shù),則默認(rèn)為最近創(chuàng)建的數(shù)據(jù)庫(kù)資源
  • SQL語(yǔ)句輸入
    • mysql_query():執(zhí)行SQL語(yǔ)句,若語(yǔ)句有返回結(jié)果集,則函數(shù)執(zhí)行成功返回結(jié)果集,若語(yǔ)句沒(méi)有返回結(jié)果集,函數(shù)執(zhí)行成功返回true
  • 解決錯(cuò)誤
    • mysql_errno():返回錯(cuò)誤號(hào)
    • mysql_error():返回錯(cuò)誤信息
  • 關(guān)閉數(shù)據(jù)庫(kù)資源
    • mysql_close():關(guān)閉數(shù)據(jù)庫(kù)資源,不使用參數(shù),默認(rèn)關(guān)閉開(kāi)啟的資源(推薦)
  • 函數(shù)
    • mysql_insert_id():返回自動(dòng)增長(zhǎng)的id,若沒(méi)有設(shè)置AUTO_INCREMENT,則返回false
    • mysql_affected_rows():獲取受影響的行數(shù)
  • 從結(jié)果集中取出數(shù)據(jù)
    • mysql_fetch_row($result):從結(jié)果集中取得一條數(shù)據(jù),返回索引數(shù)組
    • mysql_fetch_assoc($result):從結(jié)果集中取得一條數(shù)據(jù),返回關(guān)聯(lián)數(shù)組
    • mysql_fetch_array($result):從結(jié)果集中取得一條數(shù)據(jù),返回索引數(shù)組和關(guān)聯(lián)數(shù)組
    • mysql_fetch_object($result):從結(jié)果集中取得一條數(shù)據(jù),返回對(duì)象
    • mysql_data_seek($result,$row):將指針移動(dòng)到指定位置
  • 從結(jié)果集中獲取字段
    • mysql_num_rows($result):獲取結(jié)果集的字段數(shù)
    • mysql_num_fields($result):獲取結(jié)果集的列數(shù)
    • mysql_field_name($result):獲取結(jié)果集的字段名

mysqli操作數(shù)據(jù)庫(kù)

  • PHP5以后的新添加的功能都是面向?qū)ο蟮?,所以mysqli是以對(duì)象的形式添加的
  • mysqli優(yōu)點(diǎn)
    • 表示改進(jìn)
    • 功能增加
    • 效率大大增加
    • 更穩(wěn)定
  • mysqli擴(kuò)展提供的三個(gè)類(lèi)
    • mysqli:和連接有關(guān)的類(lèi)
      • 構(gòu)造方法
        • mysqli([$host [, $username [, $passd[, $dbname [,$port [, $socket ]]]]]] )
        • 連接成功返回對(duì)象,失敗返回false
      • 查看連接失敗信息
        • connect_errno():返回連接錯(cuò)誤號(hào)碼
        • connect_error():返回連接錯(cuò)誤信息
      • SQL語(yǔ)句輸入
        • query(sql):執(zhí)行SQL語(yǔ)句,若語(yǔ)句有返回結(jié)果集,則函數(shù)執(zhí)行成功返回結(jié)果集對(duì)象mysqli_result,若語(yǔ)句沒(méi)有返回結(jié)果集,函數(shù)執(zhí)行成功返回true
      • 方法
        • affected-rows():返回影響行數(shù)
        • errno():返回錯(cuò)誤號(hào)
        • error():返回錯(cuò)誤信息
        • insert_id():返回自動(dòng)增長(zhǎng)的id
      • 關(guān)閉資源
        • close():關(guān)閉連接
    • mysqli_result:表達(dá)對(duì)數(shù)據(jù)庫(kù)的查詢(xún)所返回的結(jié)果集
      • 屬性:
        • $num_rows:結(jié)果集中記錄數(shù)
        • $field_count:結(jié)果集中字段數(shù)
        • $current_field:獲取當(dāng)前列的位置
      • 方法:
        • 處理記錄
          • fetch_row():與mysql_fetch_row()一致
          • fetch_assoc():與mysql_fetch_assoc()一致
          • fetch_array():與mysql_fetch_array()一致
          • fetch_object():與mysql_fetch_object()一致
          • data_seek():與mysql_data_seek()一致
          • free():釋放結(jié)果集
        • 處理字段
          • fetch_field():取出列信息,并作為對(duì)象返回
          • fetch_fields():取出所有列信息,并作為對(duì)象返回
          • field_seek():移動(dòng)字段指針
        • 執(zhí)行多條SQL語(yǔ)句
          • multi_query(sql1[;sql2]):可執(zhí)行多條sql語(yǔ)句,語(yǔ)句間用“;”隔開(kāi),若有多個(gè)結(jié)果集,則均會(huì)被返回
          • next_result():返回multi_query()的下一個(gè)結(jié)果集
          • more_results():檢查是否含有下一個(gè)結(jié)果集
    • mysqli_stmt:預(yù)處理類(lèi)
      • 優(yōu)點(diǎn):
        • mysqli和mysqli_result能完成的功能,mysqil_stmt都能完成
        • 效率比較高,執(zhí)行多條相同的sql語(yǔ)句,只有數(shù)據(jù)不同的話(huà),不用重復(fù)傳語(yǔ)句,直接傳數(shù)據(jù)即可
        • 防止sql注入,因?yàn)槌鋈氲臄?shù)據(jù)只會(huì)當(dāng)做值類(lèi)使用,不會(huì)當(dāng)做可執(zhí)行語(yǔ)句
      • 創(chuàng)建對(duì)象
        • 創(chuàng)建好mysqli對(duì)象后,使用該對(duì)象的stmt_init()方法初始化mysqli_stmt對(duì)象
      • 準(zhǔn)備并發(fā)送語(yǔ)句
        • 語(yǔ)句中的參數(shù)值要使用占位符“?”代替
          • 使用mysqli_stmt中的prepare($sql)方法將語(yǔ)句發(fā)送到服務(wù)器準(zhǔn)備
          • 不用創(chuàng)建mysqli_stmt對(duì)象,直接使用mysqli中的prepare($sql)準(zhǔn)備sql語(yǔ)句,并返回mysqli_stmt對(duì)象
      • 給占位符傳值(綁定參數(shù))
        • 使用bind_param($type,$var1[,$var2...])綁定參數(shù)
          • $type可以為i、d、s、b,分別代表integer、double、string和二進(jìn)制資源
          • $type中的類(lèi)型個(gè)數(shù)要與占位符相同,$var個(gè)數(shù)也要與占位符個(gè)數(shù)相同
        • 給變量$var賦值
      • 執(zhí)行sql語(yǔ)句
        • 沒(méi)有結(jié)果集返回
          • 使用execute()方法執(zhí)行插入的參數(shù),返回boolean類(lèi)型
        • 有結(jié)果集返回
          • 使用bind_result($var1[,$var2...])綁定結(jié)果集
            • 使用fetch()執(zhí)行語(yǔ)句,每次獲取一條結(jié)果,并傳遞到bind_result()中的變量
            • 使用store_result()執(zhí)行語(yǔ)句,將所有結(jié)果一次性取出,返回結(jié)果集,再用fetch()獲取每一條記錄
          • result_matedate()返回結(jié)果集,用于獲取字段信息
          • 使用result_free()釋放結(jié)果集
      • 關(guān)閉資源
        • 使用close()方法關(guān)閉
      • 函數(shù)
        • mysqli和mysqli_result支持函數(shù),mysqli_stmt基本都支持
  • 事務(wù)處理
    • 建立表
      • 表類(lèi)型為MyISAM不支持事務(wù)功能,需要建立InnoDB類(lèi)型的表
    • 關(guān)閉自動(dòng)提交
      • autocommit():參數(shù)為0或false時(shí),關(guān)閉自動(dòng)提交
    • 提交事務(wù)
      • commit():提交事務(wù)(多條執(zhí)行后的sql語(yǔ)句)
    • 回滾事務(wù)
      • rollback():回滾事務(wù)(多條已執(zhí)行的sql語(yǔ)句)
  • 其他方法
    • set_charset($string):設(shè)置取出字符集

PDO

  • 優(yōu)點(diǎn):
    • 更換數(shù)據(jù)庫(kù)時(shí),不用更改代碼
  • 缺點(diǎn):
    • 效率不如mysql和mysqli高
  • 三個(gè)類(lèi)
    • PDO:代表 PHP 和數(shù)據(jù)庫(kù)服務(wù)之間的一個(gè)連接
      • 創(chuàng)建PDO對(duì)象
        • dpo($dsn,$username,$passd[,$array]):$dsn連接mysql數(shù)據(jù)庫(kù)時(shí),設(shè)置為'mysql:host=ip:port;dbname=$string',$array為調(diào)優(yōu)參數(shù)
        • DSN(data source name)數(shù)據(jù)源:包括主機(jī)位置、庫(kù)名和不同數(shù)據(jù)庫(kù)所需驅(qū)動(dòng)
        • 可用getattribute($attribute)查看屬性,使用setattribute($attribute,$value)設(shè)置屬性
      • 執(zhí)行sql語(yǔ)句
        • query($string):執(zhí)行有結(jié)果集返回的語(yǔ)句,返回預(yù)處理對(duì)象PDOStatement
        • exec($string):執(zhí)行對(duì)表有影響的語(yǔ)句,返回被影響行數(shù)
      • 設(shè)計(jì)錯(cuò)誤報(bào)告
        • 使用setAttribute()設(shè)置錯(cuò)誤報(bào)告模式
        • ERRMODE_SILENT:不顯示錯(cuò)誤,開(kāi)發(fā)人員自行檢查錯(cuò)誤
          • errorCode:返回錯(cuò)誤號(hào)碼
          • errorInfo:返回錯(cuò)誤信息數(shù)組
        • ERRMODE_WARNING:發(fā)生錯(cuò)誤,顯示一個(gè)E_WARNING消息
        • ERRMODE_EXCEPTION:發(fā)生錯(cuò)誤,拋出PDOException異常
      • 事務(wù)處理
        • 使用setAttribute(),設(shè)置開(kāi)啟事務(wù)處理,關(guān)閉自動(dòng)提交
        • 使用commit()提交已執(zhí)行的sql語(yǔ)句
        • 使用rollback()回滾已執(zhí)行的sql語(yǔ)句
    • PDOStatement:代表一條預(yù)處理語(yǔ)句,并在該語(yǔ)句被執(zhí)行后代表一個(gè)相關(guān)的結(jié)果集
      • 作用
        • 準(zhǔn)備一條語(yǔ)句
        • 處理結(jié)果集
      • 準(zhǔn)備并發(fā)送語(yǔ)句
        • 語(yǔ)句中的參數(shù)值可使用占位符“?”
        • 占位符“:占位符名字”代替
        • 使用PDO::prepare($sql)方法將語(yǔ)句發(fā)送到服務(wù)器準(zhǔn)備,返回PDOStatement對(duì)象,存儲(chǔ)結(jié)果集
      • 給占位符傳值(綁定參數(shù))
        • 使用bind_param($key,$value)綁定參數(shù)
          • “?”占位符
            • $key設(shè)置為索引號(hào),
            • $value設(shè)置為傳送值
          • 名字占位符
            • $key設(shè)置為鍵名
            • $value設(shè)置為傳送值
      • sql語(yǔ)句執(zhí)行
        • 使用execute()方法執(zhí)行已綁定參數(shù)的語(yǔ)句
        • 使用execute($array),$array數(shù)組中添加參數(shù),避免綁定參數(shù)
      • 記錄獲取
        • 使用fetch()獲取結(jié)果集中的每一條記錄,返回索引和關(guān)聯(lián)混合數(shù)組
          • 參數(shù)為PDO::FETCH_ASSOC,返回關(guān)聯(lián)數(shù)組
          • 參數(shù)為PDO::FETCH_NUM,返回索引數(shù)組
          • 參數(shù)為PDO::FETCH_BOTH,返回索引關(guān)聯(lián)混合數(shù)組
        • fetchAll()獲取結(jié)果集的每一條記錄,返回二維數(shù)組
        • 使用setFatchMode()設(shè)置獲取模式,就可以避免每次獲取都要設(shè)置模式
      • 字段獲取
        • columnCount()獲取字段數(shù)
        • getColumnMeta()返回結(jié)果集中一列的元數(shù)據(jù)
    • PDOException:代表一個(gè)由 PDO 產(chǎn)生的錯(cuò)誤。在自己的代碼不應(yīng)拋出一個(gè) PDOException 異常
      • 使用try catch捕獲各種異常,包括連接異常、sql語(yǔ)句異常等

mamcache/memcached

  • 一個(gè)高性能的分布式的內(nèi)存對(duì)象緩存系統(tǒng)。通過(guò)在內(nèi)存中維護(hù)一個(gè)巨大的hash表,維護(hù)內(nèi)存中的數(shù)據(jù)
  • 工作原理
    • PHP第一次查詢(xún)數(shù)據(jù)時(shí),會(huì)將數(shù)據(jù)存儲(chǔ)在mamcache中,下次查詢(xún)時(shí),先訪(fǎng)問(wèn)mamcache。
  • 安裝  
    • Linux下安裝
      • 基于libevent事件,所以必須先安裝libevent庫(kù)

    • Windows下安裝
      • 默認(rèn)端口11211
  • memcache命令
CommandDescriptionExample
get Reads a value get mykey
set Set a key unconditionally set mykey 0 60 5
add Add a new key add newkey 0 60 5
replace Overwrite existing key replace key 0 60 5
append Append data to existing key append key 0 60 15
prepend Prepend data to existing key prepend key 0 60 15
incr Increments numerical key value by given number incr mykey 2
decr Decrements numerical key value by given number decr mykey 5
delete Deletes an existing key delete mykey
flush_all Invalidate specific items immediately flush_all
Invalidate all items in n seconds flush_all 900
stats Prints general statistics stats
Prints memory statistics stats slabs
Prints memory statistics stats malloc
Print higher level allocation statistics stats items
stats detail
stats sizes
Resets statistics stats reset
version Prints server version. version
verbosity Increases log level verbosity
quit Terminate telnet session quit

PHP中使用memcache

  • 類(lèi):memcache
  • 連接:memcache::connect($host,$port)
  • <span>1</span> <?<span>php
    </span><span>2</span>     <span>$memcache</span> = <span>new</span><span> Memcache;
    </span><span>3</span>     <span>$memcache</span>->connect("localhost",11211) or <span>die</span>("could not connect");
  • 其他方法
    • add:添加數(shù)據(jù)
    • set/replace:修改數(shù)據(jù)
    • get:獲取數(shù)據(jù)
    • delete:刪除數(shù)據(jù)
    • ......
  • 何時(shí)使用memcache
    • 數(shù)據(jù)庫(kù)中讀出來(lái)的數(shù)據(jù),方便下次使用
    • 會(huì)話(huà)控制中使用
  • 技巧
    • 用sql語(yǔ)句作為key
    • 用md5()修改sql語(yǔ)句,使sql語(yǔ)句變短,便于保存

會(huì)話(huà)控制:面向連接的可靠的連接方式,通過(guò)會(huì)話(huà)控制,判斷用戶(hù)的登錄行為

  • cookie技術(shù)
    • 服務(wù)器給客戶(hù)端的一個(gè)文件,通過(guò)客戶(hù)端的這個(gè)文件,保存用戶(hù)信息,服務(wù)器根據(jù)文件,區(qū)分用戶(hù)
    • 設(shè)置cookie
      • setcookie($key,$value,$time):頭信息,不能有任何輸出
    • 獲取cookie
      • 使用全局?jǐn)?shù)組$_COOKIE[]獲取cookie內(nèi)容
    • 刪除cookieti
      • 用setcookie設(shè)置$value為空或不設(shè)置,$time設(shè)置為0或不設(shè)置
  • session技術(shù)
    • 在服務(wù)器中保存用戶(hù)數(shù)據(jù),會(huì)產(chǎn)生一個(gè)SessionID,可使用cookie和url傳遞該id
    • session配置
      • 配置服務(wù)器端的php.ini
    • 開(kāi)啟會(huì)話(huà)
      • session_start():讓php的核心程序?qū)⒑蛃ession有關(guān)的內(nèi)建環(huán)境變量預(yù)先載入到內(nèi)存中
        • 開(kāi)啟一個(gè)會(huì)話(huà)
          • 基于cookie的session,使用該函數(shù)不能有任何輸出
        • 返回已開(kāi)啟的會(huì)話(huà)
    • 設(shè)置和獲取session
      • 使用$_SESSION[]設(shè)置和獲取session
      • session_id()獲取和設(shè)置session的id
    • 刪除session
      • $_SESSION=array();將session設(shè)置為空數(shù)組
      • 刪除cookie中的session
      • session_destory():銷(xiāo)毀session
    • 基于url傳遞sessionid,設(shè)置url的參數(shù)為session_name,session_start()后,會(huì)自動(dòng)尋找該參數(shù)
    • 常量SID,當(dāng)用戶(hù)關(guān)閉cookie時(shí),該常量表示session_name和session_id;當(dāng)用戶(hù)開(kāi)啟cookie時(shí),該常量為空
    • 設(shè)置php.ini中的session.use_trans_sid=1,會(huì)使頁(yè)面跳轉(zhuǎn)(超鏈接、header、表單)后面自動(dòng)添加SID
  • session高級(jí)技術(shù)
    • php.ini中,session的設(shè)置
      • session_name:設(shè)置存在cookie以及SID中的session_name
      • session.use_trans_sid:設(shè)置SID是否開(kāi)啟,開(kāi)啟后,可自動(dòng)添加SID
      • session.save_path:設(shè)置session文件的保存位置,如果不設(shè)置,則不生成session文件
      • session.gc_maxlifetime:設(shè)置session文件有效時(shí)間,超過(guò)該時(shí)間session未刷新,session文件將失效
      • session.gc_probability和session.gc_divisor結(jié)合使用,定義session垃圾回收概率,算法為session.gc_probability/session.gc_divisor
      • session.use_cookie:設(shè)置session寫(xiě)入到cookie中
      • session.cookie_path:設(shè)置哪些文件的session寫(xiě)入到cookie中
      • session.cookie_lifetime:設(shè)置session的生命周期
      • session.save_handler:設(shè)置session寫(xiě)入方式及位置,當(dāng)值為user時(shí),可使用session_set_save_handler()函數(shù)
    • session_set_save_handler(open(),close(),read(),write(),destroy(),gc()):可自定義session文件的存儲(chǔ)路徑及存儲(chǔ)方式等
      • 使用該函數(shù)定義了各個(gè)方法,像往常一樣使用session
      • open():在執(zhí)行session_start()時(shí),被調(diào)用
      • close():在執(zhí)行session_write_close()時(shí),被調(diào)用
      • read():在調(diào)用open()后,被調(diào)用
      • write():腳本結(jié)束時(shí)和session_write_close()執(zhí)行時(shí),被調(diào)用
      • destroy():當(dāng)session使用session_destroy()或者session_regenerate_id()被銷(xiāo)毀時(shí),被調(diào)用
      • gc():由session.gc_probability和session.gc_divisor決定,任何時(shí)候軍可能被調(diào)用?
      • 具體用法
      • 將Session寫(xiě)入數(shù)據(jù)庫(kù)
      • 將Session寫(xiě)入Memcache

至此,PHP的基礎(chǔ)學(xué)習(xí)算是完成了,需要多做多學(xué),方能提高!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the current session ID in PHP? How to get the current session ID in PHP? Jul 13, 2025 am 03:02 AM

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

PHP get substring from a string PHP get substring from a string Jul 13, 2025 am 02:59 AM

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

How do you perform unit testing for php code? How do you perform unit testing for php code? Jul 13, 2025 am 02:54 AM

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

How to split a string into an array in PHP How to split a string into an array in PHP Jul 13, 2025 am 02:59 AM

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

How to pass a session variable to another page in PHP? How to pass a session variable to another page in PHP? Jul 13, 2025 am 02:39 AM

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

How does PHP handle Environment Variables? How does PHP handle Environment Variables? Jul 14, 2025 am 03:01 AM

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

See all articles