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

Home Backend Development PHP Tutorial PHP札記(PHP高級(jí)篇)

PHP札記(PHP高級(jí)篇)

Jun 13, 2016 pm 12:17 PM
mysql mysqli nbsp session

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

高級(jí)篇中將涉及數(shù)據(jù)庫(kù)的使用以及Cookie和Session會(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 用戶名 -p密碼,如mysql -h localhost -u root -p123456
  • 安全的方法:先輸入“mysql -h sql地址 -u 用戶名 -p”,回車(chē),再輸入密碼

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

  • 定義:用來(lái)創(chuàng)建數(shù)據(jù)庫(kù)中的各種對(duì)象-----表、視圖、索引、同義詞、聚簇等
  • SQL語(yǔ)句
    • 創(chuàng)建數(shù)據(jù)庫(kù)
    • <span style="color: #0000ff;">CREATE</span> <span style="color: #0000ff;">DATABASE</span> <span style="color: #ff0000;">[</span><span style="color: #ff0000;">IF NO EXISTS</span><span style="color: #ff0000;">]</span> DatabaseName
    • 創(chuàng)建表
    • <span style="color: #0000ff;">CREATE</span> <span style="color: #0000ff;">TABLE</span> <span style="color: #ff0000;">[</span><span style="color: #ff0000;">IF NOT EXISTS</span><span style="color: #ff0000;">]</span><span style="color: #000000;"> TableName (colname1 type </span><span style="color: #ff0000;">[</span><span style="color: #ff0000;">property</span><span style="color: #ff0000;">]</span> <span style="color: #ff0000;">[</span><span style="color: #ff0000;">index</span><span style="color: #ff0000;">]</span><span style="color: #000000;">,colname2 type </span><span style="color: #ff0000;">[</span><span style="color: #ff0000;">property</span><span style="color: #ff0000;">]</span> <span style="color: #ff0000;">[</span><span style="color: #ff0000;">index</span><span style="color: #ff0000;">]</span><span style="color: #000000;">,...)[tableType] [tableCharSet];</span>
      • 修改表
        • alter table 操作
      • 數(shù)據(jù)類型
        • 數(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,枚舉類型,最多能存儲(chǔ)65535個(gè)值,一個(gè)字段只能存一個(gè)值
          • SET,集合類型,最多可存儲(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ù)類型以字符串的形式存入,都可以自動(dòng)轉(zhuǎn)換類型

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

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

      • MySQL可以針對(duì)不同的存儲(chǔ)引擎需求可以選擇最優(yōu)的存儲(chǔ)引擎
      • 數(shù)據(jù)表類型即存儲(chǔ)引擎
      • 使用type或engine關(guān)鍵字指定表類型
      • 常用的表類型
        • 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ù)查詢語(yǔ)言(DQL)

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

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

      • 定義:用來(lái)授予或回收訪問(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,以此類推,否則返回fault
            • 其他用法:mysql 語(yǔ)句case when
        • 其他函數(shù)
          • database():返回?cái)?shù)據(jù)庫(kù)名
          • version():返回MySQL版本
          • user():返回MySQL的用戶
          • inet_aton(ip):將IP轉(zhuǎn)換為網(wǎng)路字節(jié)序
          • inet_nton():將網(wǎng)絡(luò)字節(jié)序轉(zhuǎn)為IP
          • password():MySQL用戶密碼加密
          • md5(str):將字符串加密

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

      • 連接數(shù)據(jù)庫(kù)
        • mysql_connect(IP,user,psw):IP為數(shù)據(jù)庫(kù)地址,user為用戶名,psw為用戶密碼,連接成功,返回?cái)?shù)據(jù)庫(kù)資源,連接失敗,返回false
      • 選擇庫(kù)
        • mysql_select_db($dbname,[$res]):$dbname為庫(kù)名稱;$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è)類
        • mysqli:和連接有關(guān)的類
          • 構(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ù)的查詢所返回的結(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ù)處理類
          • 優(yōu)點(diǎn):
            • mysqli和mysqli_result能完成的功能,mysqil_stmt都能完成
            • 效率比較高,執(zhí)行多條相同的sql語(yǔ)句,只有數(shù)據(jù)不同的話,不用重復(fù)傳語(yǔ)句,直接傳數(shù)據(jù)即可
            • 防止sql注入,因?yàn)槌鋈氲臄?shù)據(jù)只會(huì)當(dāng)做值類使用,不會(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中的類型個(gè)數(shù)要與占位符相同,$var個(gè)數(shù)也要與占位符個(gè)數(shù)相同
            • 給變量$var賦值
          • 執(zhí)行sql語(yǔ)句
            • 沒(méi)有結(jié)果集返回
              • 使用execute()方法執(zhí)行插入的參數(shù),返回boolean類型
            • 有結(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ù)處理
        • 建立表
          • 表類型為MyISAM不支持事務(wù)功能,需要建立InnoDB類型的表
        • 關(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è)類
        • 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第一次查詢數(shù)據(jù)時(shí),會(huì)將數(shù)據(jù)存儲(chǔ)在mamcache中,下次查詢時(shí),先訪問(wèn)mamcache。
      • 安裝  
        • Linux下安裝
          • 基于libevent事件,所以必須先安裝libevent庫(kù)

        • Windows下安裝
          • 默認(rèn)端口11211
      • memcache命令
      Command Description Example
      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

      • 類:memcache
      • 連接:memcache::connect($host,$port)
      • <span style="color: #008080;">1</span> <span style="color: #000000;">php</span><span style="color: #008080;">2</span>     <span style="color: #800080;">$memcache</span> = <span style="color: #0000ff;">new</span><span style="color: #000000;"> Memcache;</span><span style="color: #008080;">3</span>     <span style="color: #800080;">$memcache</span>->connect("localhost",11211) or <span style="color: #0000ff;">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ì)話控制中使用
      • 技巧
        • 用sql語(yǔ)句作為key
        • 用md5()修改sql語(yǔ)句,使sql語(yǔ)句變短,便于保存
      • 會(huì)話控制:面向連接的可靠的連接方式,通過(guò)會(huì)話控制,判斷用戶的登錄行為

        • cookie技術(shù)
          • 服務(wù)器給客戶端的一個(gè)文件,通過(guò)客戶端的這個(gè)文件,保存用戶信息,服務(wù)器根據(jù)文件,區(qū)分用戶
          • 設(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ù)器中保存用戶數(shù)據(jù),會(huì)產(chǎn)生一個(gè)SessionID,可使用cookie和url傳遞該id
          • session配置
            • 配置服務(wù)器端的php.ini
          • 開(kāi)啟會(huì)話
            • session_start():讓php的核心程序?qū)⒑蛃ession有關(guān)的內(nèi)建環(huán)境變量預(yù)先載入到內(nèi)存中
              • 開(kāi)啟一個(gè)會(huì)話
                • 基于cookie的session,使用該函數(shù)不能有任何輸出
              • 返回已開(kāi)啟的會(huì)話
          • 設(shè)置和獲取session
            • 使用$_SESSION[]設(shè)置和獲取session
            • session_id()獲取和設(shè)置session的id
          • 刪除session
            • $_SESSION=array();將session設(shè)置為空數(shù)組
            • 刪除cookie中的session
            • session_destory():銷毀session
          • 基于url傳遞sessionid,設(shè)置url的參數(shù)為session_name,session_start()后,會(huì)自動(dòng)尋找該參數(shù)
          • 常量SID,當(dāng)用戶關(guān)閉cookie時(shí),該常量表示session_name和session_id;當(dāng)用戶開(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()被銷毀時(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)

Performing logical backups using mysqldump in MySQL Performing logical backups using mysqldump in MySQL Jul 06, 2025 am 02:55 AM

mysqldump is a common tool for performing logical backups of MySQL databases. It generates SQL files containing CREATE and INSERT statements to rebuild the database. 1. It does not back up the original file, but converts the database structure and content into portable SQL commands; 2. It is suitable for small databases or selective recovery, and is not suitable for fast recovery of TB-level data; 3. Common options include --single-transaction, --databases, --all-databases, --routines, etc.; 4. Use mysql command to import during recovery, and can turn off foreign key checks to improve speed; 5. It is recommended to test backup regularly, use compression, and automatic adjustment.

Handling NULL Values in MySQL Columns and Queries Handling NULL Values in MySQL Columns and Queries Jul 05, 2025 am 02:46 AM

When handling NULL values ??in MySQL, please note: 1. When designing the table, the key fields are set to NOTNULL, and optional fields are allowed NULL; 2. ISNULL or ISNOTNULL must be used with = or !=; 3. IFNULL or COALESCE functions can be used to replace the display default values; 4. Be cautious when using NULL values ??directly when inserting or updating, and pay attention to the data source and ORM framework processing methods. NULL represents an unknown value and does not equal any value, including itself. Therefore, be careful when querying, counting, and connecting tables to avoid missing data or logical errors. Rational use of functions and constraints can effectively reduce interference caused by NULL.

Aggregating data with GROUP BY and HAVING clauses in MySQL Aggregating data with GROUP BY and HAVING clauses in MySQL Jul 05, 2025 am 02:42 AM

GROUPBY is used to group data by field and perform aggregation operations, and HAVING is used to filter the results after grouping. For example, using GROUPBYcustomer_id can calculate the total consumption amount of each customer; using HAVING can filter out customers with a total consumption of more than 1,000. The non-aggregated fields after SELECT must appear in GROUPBY, and HAVING can be conditionally filtered using an alias or original expressions. Common techniques include counting the number of each group, grouping multiple fields, and filtering with multiple conditions.

How to set and get session variables in PHP? How to set and get session variables in PHP? Jul 12, 2025 am 03:10 AM

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

Calculating Database and Table Sizes in MySQL Calculating Database and Table Sizes in MySQL Jul 06, 2025 am 02:41 AM

To view the size of the MySQL database and table, you can query the information_schema directly or use the command line tool. 1. Check the entire database size: Execute the SQL statement SELECTtable_schemaAS'Database',SUM(data_length index_length)/1024/1024AS'Size(MB)'FROMinformation_schema.tablesGROUPBYtable_schema; you can get the total size of all databases, or add WHERE conditions to limit the specific database; 2. Check the single table size: use SELECTta

Setting up asynchronous primary-replica replication in MySQL Setting up asynchronous primary-replica replication in MySQL Jul 06, 2025 am 02:52 AM

To set up asynchronous master-slave replication for MySQL, follow these steps: 1. Prepare the master server, enable binary logs and set a unique server-id, create a replication user and record the current log location; 2. Use mysqldump to back up the master library data and import it to the slave server; 3. Configure the server-id and relay-log of the slave server, use the CHANGEMASTER command to connect to the master library and start the replication thread; 4. Check for common problems, such as network, permissions, data consistency and self-increase conflicts, and monitor replication delays. Follow the steps above to ensure that the configuration is completed correctly.

Implementing Transactions and Understanding ACID Properties in MySQL Implementing Transactions and Understanding ACID Properties in MySQL Jul 08, 2025 am 02:50 AM

MySQL supports transaction processing, and uses the InnoDB storage engine to ensure data consistency and integrity. 1. Transactions are a set of SQL operations, either all succeed or all fail to roll back; 2. ACID attributes include atomicity, consistency, isolation and persistence; 3. The statements that manually control transactions are STARTTRANSACTION, COMMIT and ROLLBACK; 4. The four isolation levels include read not committed, read submitted, repeatable read and serialization; 5. Use transactions correctly to avoid long-term operation, turn off automatic commits, and reasonably handle locks and exceptions. Through these mechanisms, MySQL can achieve high reliability and concurrent control.

Handling character sets and collations issues in MySQL Handling character sets and collations issues in MySQL Jul 08, 2025 am 02:51 AM

Character set and sorting rules issues are common when cross-platform migration or multi-person development, resulting in garbled code or inconsistent query. There are three core solutions: First, check and unify the character set of database, table, and fields to utf8mb4, view through SHOWCREATEDATABASE/TABLE, and modify it with ALTER statement; second, specify the utf8mb4 character set when the client connects, and set it in connection parameters or execute SETNAMES; third, select the sorting rules reasonably, and recommend using utf8mb4_unicode_ci to ensure the accuracy of comparison and sorting, and specify or modify it through ALTER when building the library and table.

See all articles