Home >Backend Development >PHP Tutorial >PHP data storage and retrieval
There are two basic ways to store data: save to a normal file, or save to a database.
Data writing:
1. Open the file. If the file does not exist, it needs to be created first.
2. Write data to this file.
3. Close this file.
Data reading:
1. Open the file. If the file cannot be opened, you should be aware of this and exit correctly.
2. Read data from the file.
3. Close this file.
Select file mode:
When opening a file, you have the following three options.
1. Open the file for reading only, writing only or reading and writing.
2. If you want to write a file, you may want to overwrite the existing file content, or just append new data to the unseen end. If the file already exists, program execution can be terminated instead of overwriting the file.
3. If you want to write a file on a system that distinguishes between secondary copy mode and plain text mode, you must also specify the method to be used.
The function fopen() supports the combination of the above three methods.
Depending on the server settings, you can get the document root directory in the following three ways:
$_SERVER['DOCUMENT_ROOT']
$DOCUMENT_ROOT
$HTTP_SERVER_VARS['DOCUMENT_ROOT']
For form data, first One style is preferred.
Open the file fopen(path,mode)
Write the file: fwrite($fp, &outputstring)
Close the file: fclose($fp)
File mode of the fopen() function
r Read-only Read mode - open the file, Start reading from the file header
r+ Read-only read-write mode - open the file, start reading and writing from the file header
w Write-only Write mode - open the file, start reading from the file header. If the file already exists, all existing contents of the file will be deleted. If the file does not exist, the function will create the file.
x Write carefully Open the file in write mode and start writing from the beginning of the file. If the file already exists, the file will not be opened, the fopen() function will return false, and PHP will generate a warning.
x+ Write carefully Open the file in read/write mode and start writing from the beginning of the file. If the file already exists, the file will not be opened, the fopen() function will return false, and PHP will generate a warning.
a Append Append mode - open the file, if the file already has content, append (write) will start from the end of the file, if the file does not exist, the function will create the file
a+ Append Append mode - open the file, If the file already has content, it will be appended (written) from the end of the file. If the file does not exist, the function will create the file
b Binary Binary mode - used to connect with other modes. If the file system can distinguish between binary files and text files, you might use it. Maximum portability is achieved. Binary mode is the default mode.
t Text is used for combination with other modes. This mode is just an option under Windows system.
Open the file in read-only mode: fopen()
Know when you have finished reading the file: feof()
Read one line of data at a time: fgets(), fgetss() and fgetcsv()
Read the entire file: readfile (), fpassthru() and file()
The first way is readfile(). readfile($path); Calling the readfile() function will open the file, output the file contents to standard output, and then close the file.
The second way is fpassthru(). To use this function, you must first open the file using fopen(). Then pass the file pointer as a parameter to fpassthru(), so that the contents of the file pointed to by the file pointer can be sent to standard output. Then close the file. If the read operation is successful, the function returns true, otherwise it returns false.
The third function that reads the entire file is file(). It is the same as readfile. But it sends the result to an array.
$filearray = file($path);
The fourth option is to use the file_get_contents() function. This function is the same as readfile(), but this function will return the file contents as a string instead of echoing the file contents to the browser.
Read a character: fgetc()
while(!feof($fp)){ $char = fgetc($fp); if(!feof($fp)){ echo ($char == "\n "? "<br /> ": $char); } }
读取任意长度:fread()
读取一个文件的最后一种方法是使用fread()函数从文件中读取任意长度的字节。
查看文件是否存在:file_exists()
确定文件大小:filesize()
删除一个文件:unlink()(PHP中没有名为delete的函数)
在文件中定位:rewind()、fseek()和ftell()
rewind()函数可以将指针复位到文件的开始。
ftell()函数可以以字节为单位报告文件指针当前在文件中的位置。
调用fseek()函数可以将文件指针fp从whence位置移动offset个字节。
rewind()函数等价于调用一个具有零偏移量的fseek()函数。
文件的锁定:
为了避免多个方法同时操作一个文件,可以使用文件锁定的方法。
文件锁定是通过flock()函数来实现的。
如果打算使用flock()函数,必须将其添加到所有使用文件的脚本中;否则,就没有任何意义。
flock()的操作值
LOCK_SH 读操作锁定。这意味着文件可以共享,其他人可以读该文件
LOCK_EX 写操作锁定。这是互斥的。该文件不能被共享。
LOCK_UN 释放已有的锁定
LOCK_NB 防止在请求加锁时发生阻塞
数据库管理系统
RDBMS提供了比普通文件更快的数据访问。
RDBMS可以很容易地查找并检索满足特定条件的数据集合。
RDBMS具有内置的处理并发访问的机制。
RDBMS可以随机访问数据。
RDBNS具有内置的权限系统。
vieworders.php
<?php $DOCUMENT_ROOT = $_SERVER["DOCUMENT_ROOT"]; ?> <html> <head> <title>Bob's Auto Parts - Customer Orders</title> </head> <body> <h1]]>Bob's Auto Parts</h1> <h2]]>Customer Orders</h2> <?php @$fp = fopen("$DOCUMENT_ROOT/orders/orders.txt", 'rb'); if(!$fp){ echo "<p><strong>No orders pending.Please try again later.</strong></p>"; exit; } while (!feof($fp)){ $order = fgets($fp,999); echo $order."<br />"; } ?> </body> </html>
proccessorder.php
<?php $tireqty = $_POST['$tireqty']; $oilqty = $_POST['$oilqty']; $sparkqty = $_POST['$sparkqty']; $address = $_POST['address']; $DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT']; $date = date('H:i, jS F Y'); ?> <html> <head> <title>Bob's Auto Parts-Order Results</title> </head> <body> <h1>Bob's Auto Parts</h1> <h2>Order Results</h2> <?php echo "<p>Order processed at ".date('H:i, jS F Y')."</p>"; echo "<p>Your order is as follows: </p>"; $totalqty = 0; $totalqty = $tireqty + $oilqty + $sparkqty; echo "Items ordered: ".$totalqty."<br />"; if($totalqty == 0){ echo "You did not order anything on the previous page!<br />"; }else{ if($tireqty > 0){ echo $tireqty." tires<br />"; } if($oilqty > 0){ echo $oilqty." bottles of oil<br />"; } if($sparkqty > 0){ echo $sparkqty." spark plugs<br />"; } } $totalamount = 0.00; define("TIREPRICE", 100); define("OILPRICE", 10); define("SPARKPRICE", 4); $totalamount = $tireqty * TIREPRICE + $oilqty * OILPRICE + $sparkqty * SPARKPRICE; $totalamount=number_format($totalamount, 2, '.', ' '); echo "<p>Total of order is $.$totalamount.</p>"; echo "<p>Address to ship to is ".$address."</p>"; $outputstring = $date."\t".$tireqty." tires \t".$oilqty." oil\t" .$sparkqty." spark plugs\t\$".$totalamount."\t".$address."\n"; @ $fp= fopen("$DOCUMENT_ROOT/orders/orders.txt", 'ab'); flock($fp, LOCK_EX); if(!$fp){ echo "<p><strong>Your orde could not be processed at this time. Please try again later.</strong></p></body></html>"; exit; } fwrite($fp, $outputstring, strlen($outputstring)); flock($fp, LOCK_UN); fclose($fp); echo "<p>Order written.</p>"; ?> </body> </html>