PHP資料庫操作之簡單學習

2021-07-10 17:22:41 字數 2325 閱讀 2819

1 開啟關閉檔案

fopen()

resource fopen ( string filename, string mode [, bool use_include_path [, resource zcontext]] )


fopen()函式將resource繫結到乙個流或控制代碼。繫結之後,指令碼就可以通過控制代碼與此資源互動;

例1:以唯讀方式開啟乙個位於本地伺服器的文字檔案

$fh = fopen("test.txt", "r");

例2:以唯讀方式開啟乙個遠端檔案

$fh = fopen("", "r");

fclose()

bool fclose ( resource handle )

將 handle 指向的檔案關閉 。如果成功則返回 true,失敗則返回 false;

檔案指標必須有效,並且是通過 fopen() 或 fsockopen() 成功開啟的;

雖然每個請求最後都會自動關閉檔案,但明確的關閉開啟的所有檔案是乙個好的習慣;

例:$fh = fopen("test.txt", "r");

fclose($fh);12

2 讀取檔案

php 提供了很多從檔案中讀取資料的方法,不僅可以一次只讀取乙個字元,還可以一次讀取整個檔案。

fread()

string fread ( int handle, int length )


fread()函式從handle指定的資源中讀取length個字元,

當到達eof或讀取到length個字元時讀取將停止。

如果要讀取整個檔案,使用filesize()函式確定應該讀取的字元數;

file()

array file ( string $filename [, int $flags = 0 [, resource $context ]])

file()函式將檔案讀取到陣列中,各元素由換行符分隔。

例:$arr = file("test.txt");

print_r($arr);12

file_get_contents()

string file_get_contents ( string filename [, bool use_include_path [, resource context [, int offset [, int maxlen]]]] )

file_get_contents()函式將檔案內容讀到字串中;

例:$str = file_get_contents("test.txt");

echo $str;12

3 寫入檔案

fwrite()

int fwrite ( resource handle, string string [, int length] )

fwrite()函式將string的內容寫入到由handle指定的資源中。

如果指定length引數,將在寫入length個字元時停止。

例:$str = "test text";

$fh = fopen("test.txt", "a");

fwrite($fh, $str);

fclose($fh);1234

file_put_contents()

int file_put_contents ( string filename, string data [, int flags [, resource context]] )

file_put_contents()函式將乙個字串寫入檔案,與依次呼叫fopen(),fwrite(),fclose()功能一樣;

例:$str = "hello";

file_put_contents("test.txt", $str);12

4 複製,重新命名,刪除檔案

copy()

bool copy ( string source, string dest )

將檔案從 source 拷貝到 dest。如果成功則返回 true,失敗則返回 false。

例:copy("test.txt", "test.txt.bak");

rename()

bool rename ( string oldname, string newname [, resource context] )

嘗試把 oldname 重新命名為 newname。 如果成 功則返回 true,失敗則返回 false。

例:rename("test.txt", 「test2.txt」);

unlink()

bool unlink ( string filename )

刪除檔案,如果刪除成功返回true, 否則返回false;

5讀取檔案

PHP操作mysql資料庫簡單示例

先建立乙個資料庫mydb create database mydb 再建立乙個簡單的資料表 create table mydb mytable name varchar 20 not null age int not null engine myisam 插入一些資料 insert into myd...

php資料庫操作

獲取鏈結 conn mysql connect localhost root root 測試當前連線的預設字符集名稱。charset mysql client encoding conn echo charset echo if conn else 設定gbk 就不會出現亂碼 雖然專案用的是utf ...

php資料庫操作

連線資料庫 header content type text html charset utf 8 define hostname localhost define username bestpool define password 123456 define database guess x co...