Session函數:
session_abort() finishes session without saving data. Thus the original values in session data are kept.
返回值:沒有你返回值。
session_cache_expire() 返回 session.cache_expire 的設定值。php
請求開始的時候,緩存到期時間會被重置爲 180,而且保存在 session.cache_expire 配置項中。 所以,針對每一個請求,須要在 session_start() 函數調用以前 調用 session_cache_expire() 來設置緩存到期時間。參數:html
new_cache_expire
若是給定 new_cache_expire
,就使用 new_cache_expire
的值設置當前緩存到期時間。mysql
Note: 僅在 session.cache_limiter 的設置值 不是 nocache 的時候, 才能夠設置 new_cache_expire
參數。git
返回值:返回 session.cache_expire 的當前設置值, 以分鐘爲單位,默認值是 180 (分鐘)。
<?php
/* 設置緩存限制爲 「private」 */
session_cache_limiter('private');
$cache_limiter = session_cache_limiter();
/* 設置緩存過時時間爲 30 分鐘 */
session_cache_expire(30);
$cache_expire = session_cache_expire();
/* 開始會話 */
session_start();
echo "The cache limiter is now set to $cache_limiter<br />";
echo "The cached session pages expire after $cache_expire minutes";
?>
session_cache_limiter() 返回當前緩存限制器的名稱。參數:
cache_limiter
若是指定了
cache_limiter
參數, 將使用指定值做爲緩存限制器的值。
可選的值
值 |
發送的響應頭 |
public |
Expires:(根據 session.cache_expire 的設定計算得出)
Cache-Control: public, max-age=(根據 session.cache_expire 的設定計算得出)
Last-Modified:(會話最後保存時間) |
private_no_expire |
Cache-Control: private, max-age=(根據 session.cache_expire 的設定計算得出), pre-check=(根據 session.cache_expire 的設定計算得出)
Last-Modified: (會話最後保存時間) |
private |
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: private, max-age=(根據 session.cache_expire 的設定計算得出), pre-check=(根據 session.cache_expire 的設定計算得出)
Last-Modified: (會話最後保存時間) |
nocache |
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache |
返回值:返回當前所用的緩存限制器名稱。
<?php
/* 設置緩存限制器爲 'private' */
session_cache_limiter('private');
$cache_limiter = session_cache_limiter();
echo "The cache limiter is now set to $cache_limiter<br />";
?>
session_decode() 對 $data
參數中的已經序列化的會話數據進行解碼, 而且使用解碼後的數據填充 $_SESSION 超級全局變量。參數:
data
編碼後的數據sql
返回值:成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
session_destroy() 銷燬當前會話中的所有數據, 可是不會重置當前會話所關聯的全局變量, 也不會重置會話 cookie。 若是須要再次使用會話變量, 必須從新調用 session_start() 函數。數據庫
爲了完全銷燬會話,好比在用戶退出登陸的時候,必須同時重置會話 ID。 若是是經過 cookie 方式傳送會話 ID 的,那麼同時也須要 調用 setcookie() 函數來 刪除客戶端的會話 cookie。後端
返回值:成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
<?php
// 初始化會話。
// 若是要使用會話,別忘了如今就調用:
session_start();
// 重置會話中的全部變量
$_SESSION = array();
// 若是要清理的更完全,那麼同時刪除會話 cookie
// 注意:這樣不但銷燬了會話中的數據,還同時銷燬了會話自己
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// 最後,銷燬會話
session_destroy();
?>
session_encode() 返回一個序列化後的字符串,包含被編碼的、儲存於 $_SESSION 超全局變量中的當前會話數據。參數:
返回值:返回當前會話編碼後的內容。
獲取會話 cookie 的參數。
返回值:返回一個包含當前會話 cookie 信息的數組:
session_id() 能夠用來獲取/設置 當前會話 ID。參數:
id
若是指定了 id
參數的值, 則使用指定值做爲會話 ID。 必須在調用 session_start() 函數以前調用 session_id()函數。 不一樣的會話管理器對於會話 ID 中可使用的字符有不一樣的限制。 例如文件會話管理器僅容許會話 ID 中使用如下字符:a-z A-Z 0-9 , (逗號)和 - (減號)數組
Note: 若是使用 cookie 方式傳送會話 ID,而且指定了 id
參數, 在調用 session_start() 以後都會向客戶端發送新的 cookie, 不管當前的會話 ID 和新指定的會話 ID 是否相同。緩存
返回值:session_id() 返回當前會話ID。 若是當前沒有會話,則返回空字符串("")。
檢查變量是否已經在會話中註冊。參數:
name
變量名稱。安全
返回值:session_is_registered() 返回 TRUE
則表示 name
變量已經在當前會話中註冊使用,不然返回 FALSE
。
session_module_name() 獲取或設置會話模塊名稱。參數:
module
若是指定 module
參數,則使用 指定值做爲會話模塊。
返回值:返回當前所用的會話模塊名稱。
session_name() 函數返回當前會話名稱。 若是指定 name
參數, session_name() 函數會更新會話名稱, 並返回 原來的 會話名稱。參數:
name
用在 cookie 或者 URL 中的會話名稱, 例如:PHPSESSID。 只能使用字母和數字做爲會話名稱,建議儘量的短一些, 而且是望文知意的名字(對於啓用了 cookie 警告的用戶來講,方便其判斷是否要容許此 cookie)。 若是指定了 name
參數, 那麼當前會話也會使用指定值做爲名稱。
會話名稱至少須要一個字母,不能所有都使用數字, 不然,每次都會生成一個新的會話 ID。
返回值:返回當前會話名稱。
<?php
/* 設置會話名稱爲 WebsiteID */
$previous_name = session_name("WebsiteID");
echo "The previous session name was $previous_name<br />";
?>
session_regenerate_id() 在不修改當前會話中數據的前提下使用新的 ID 替換原有會話 ID。參數:
delete_old_session
是否刪除原 ID 所關聯的會話存儲文件。
返回值:成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
<?php
session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";
print_r($_SESSION);
?>
此函數沒有參數。
返回值:沒有返回值。
- session_register — Register one or more global variables with the current session
<?php
// Use of session_register() is deprecated
$barney = "A big purple dinosaur.";
session_register("barney");
// Use of $_SESSION is preferred, as of PHP 4.1.0
$_SESSION["zim"] = "An invader from another planet.";
// The old way was to use $HTTP_SESSION_VARS
$HTTP_SESSION_VARS["spongebob"] = "He's got square pants.";
?>
session_reset() reinitializes a session with original values stored in session storage. This function requires an active session and discards changes in $_SESSION.
沒有返回值
session_save_path() 返回當前會話的保存路徑。參數:
path
指定會話數據保存的路徑。 必須在調用 session_start() 函數以前調用 session_save_path() 函數。
Note:
在某些操做系統上,建議使用能夠高效處理 大量小尺寸文件的文件系統上的路徑來保存會話數據。 例如,在 Linux 平臺上,對於會話數據保存的工做而言,reiserfs 文件系統會比 ext2fs 文件系統可以提供更好的性能。
返回值:返回保存會話數據的路徑。
Cookie 參數能夠在 php.ini 文件中定義,本函數僅在當前腳本執行過程當中有效。 所以,若是要經過函數修改 cookie 參數,須要對每一個請求都要 在調用 session_start() 函數以前調用 session_set_cookie_params() 函數。
本函數會修改運行期 ini 設置值, 能夠經過 ini_get() 函數獲取這些值。參數:
lifetime
Cookie 的 生命週期,以秒爲單位。
path
此 cookie 的有效 路徑。 on the domain where 設置爲「/」表示對於本域上全部的路徑此 cookie 均可用。
domain
Cookie 的做用 域。 例如:「www.php.net」。 若是要讓 cookie 在全部的子域中均可用,此參數必須以點(.)開頭,例如:「.php.net」。
secure
設置爲 TRUE
表示 cookie 僅在使用 安全 連接時可用。
httponly
設置爲 TRUE
表示 PHP 發送 cookie 的時候會使用 httponly 標記。
返回值:沒有返回值。
session_set_save_handler() 設置用戶自定義 會話存儲函數。 若是想使用 PHP 內置的會話存儲機制以外的方式, 可使用本函數。 例如,能夠自定義會話存儲函數來將會話數據存儲到數據庫。
返回值:成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
這裏使用了 session_set_save_handler() 函數的 OOP 原型 而且使用第二個參數來註冊 shutdown 函數。 當將對象註冊爲會話保存管理器時,建議使用這種方式。
<?php
class MySessionHandler implements SessionHandlerInterface{
// 在這裏實現接口
}
$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();
// 如今可使用 $_SESSION 保存以及獲取數據了
session_start() 會建立新會話或者重用現有會話。 若是經過 GET 或者 POST 方式,或者使用 cookie 提交了會話 ID, 則會重用現有會話。
返回值:成功開始會話返回 TRUE
,反之返回 FALSE
session_status() is used to return the current session status.
返回值:
PHP_SESSION_DISABLED
if sessions are disabled.
PHP_SESSION_NONE
if sessions are enabled, but none exists.
PHP_SESSION_ACTIVE
if sessions are enabled, and one exists.
- session_unregister — Unregister a global variable from the current session
session_unregister() unregisters the global variable named name
from the current session.
The session_unset() function frees all session variables currently registered.
返回值:沒有返回值。
Session data is usually stored after your script terminated without the need to call session_write_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done.
返回值:沒有返回值。
----------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------
Classes/Object函數:
基於用戶定義的類 original
建立別名 alias
。 這個別名類和原有的類徹底相同。參數:
original
原有的類。
alias
類的別名。
autoload
若是原始類沒有加載,是否使用自動加載(autoload)。
返回值:成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
<?php
class foo { }
class_alias('foo', 'bar');
$a = new foo;
$b = new bar;
// the objects are the same
var_dump($a == $b, $a === $b); //bool(true) bool(false)
var_dump($a instanceof $b); //bool(true)
// the classes are the same
var_dump($a instanceof foo); //bool(true)
var_dump($a instanceof bar); //bool(true)
var_dump($b instanceof foo); //bool(true)
var_dump($b instanceof bar); //bool(true)
?>
檢查指定的類是否已定義。參數:
class_name
類名。名字的匹配是大小寫不敏感的。
autoload
是否默認調用 __autoload。
返回值:若是由 class_name
所指的類已經定義,此函數返回 TRUE
,不然返回 FALSE
。
class_exists() 例子:
<?php
// 使用前檢查類是否存在
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>
autoload
parameter 例子:
<?php
function __autoload($class){
include($class . '.php');
// Check to see whether the include declared the class
if (!class_exists($class, false)) {
trigger_error("Unable to load class: $class", E_USER_WARNING);
}
}
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>
獲取靜態方法調用的類名。參數:
返回類的名稱,若是不是在類中調用則返回 FALSE
。
<?php
class foo {
static public function test() {
var_dump(get_called_class());
}
}
class bar extends foo {
}
foo::test();
bar::test();
?>
string(3) "foo"
string(3) "bar"
返回由類的方法名組成的數組。參數:
class_name
類名或者對象實例。
返回值:返回由 class_name
指定的類中定義的方法名所組成的數組。若是出錯,則返回 NULL
。
<?php
class myclass {
// constructor
function myclass(){
return(true);
}
// method 1
function myfunc1(){
return(true);
}
// method 2
function myfunc2(){
return(true);
}
}
$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());
foreach ($class_methods as $method_name) {
echo "$method_name\n";
}
?>
返回由類的默認公有屬性組成的關聯數組,此數組的元素以 varname => value
的形式存在。參數:
class_name
The class name
返回值:Returns an associative array of declared properties visible from the current scope, with their default value. The resulting array elements are in the form of varname => value. In case of an error, it returns FALSE
.
get_class_vars() example:
<?php
class myclass {
var $var1; // this has no default value...
var $var2 = "xyz";
var $var3 = 100;
private $var4; // PHP 5
// constructor
function myclass() {
// change some properties
$this->var1 = "foo";
$this->var2 = "bar";
return true;
}
}
$my_class = new myclass();
$class_vars = get_class_vars(get_class($my_class));
foreach ($class_vars as $name => $value) {
echo "$name : $value\n";
}
?>
// Before PHP 4.2.0
var2 : xyz
var3 : 100
// As of PHP 4.2.0
var1 :
var2 : xyz
var3 : 100
get_class_vars() and scoping behaviour:
<?php
function format($array){
return implode('|', array_keys($array)) . "\r\n";
}
class TestCase{
public $a = 1;
protected $b = 2;
private $c = 3;
public static function expose(){
echo format(get_class_vars(__CLASS__));
}
}
TestCase::expose();
echo format(get_class_vars('TestCase'));
?>
// 5.0.0
a| * b| TestCase c
a| * b| TestCase c
// 5.0.1 - 5.0.2
a|b|c
a|b|c
// 5.0.3 +
a|b|c
a
返回對象實例 obj
所屬類的名字。若是 obj
不是一個對象則返回 FALSE
。
使用 get_class():
<?php
class foo {
function foo(){
// implements some logic
}
function name(){
echo "My name is " , get_class($this) , "\n";
}
}
// create an object
$bar = new foo();
// external call
echo "Its name is " , get_class($bar) , "\n";
// internal call
$bar->name();
?>
Its name is foo
My name is foo
參數:object
The tested object. This parameter may be omitted when inside a class.
Using get_class() in superclass:
<?php
abstract class bar {
public function __construct(){
var_dump(get_class($this));
var_dump(get_class());
}
}
class foo extends bar {
}
new foo;
?>
string(3) "foo"
string(3) "bar"
返回值:返回由當前腳本中已定義類的名字組成的數組。
<?php
print_r(get_declared_classes());
?>
Array
(
[0] => stdClass
[1] => __PHP_Incomplete_Class
[2] => Directory
)
返回值:本函數返回一個數組,其內容是當前腳本中全部已聲明的接口的名字。
<?php
print_r(get_declared_interfaces());
?>
Array
(
[0] => Traversable
[1] => IteratorAggregate
[2] => Iterator
[3] => ArrayAccess
[4] => reflector
[5] => RecursiveIterator
[6] => SeekableIterator
)
參數:此函數沒有參數
返回值:返回一個數組,其值包含了全部已定義的 traits 的名稱。 在失敗的狀況下返回 NULL
。
返回由 obj
指定的對象中定義的屬性組成的關聯數組。
<?php
class Point2D {
var $x, $y;
var $label;
function Point2D($x, $y){
$this->x = $x;
$this->y = $y;
}
function setLabel($label){
$this->label = $label;
}
function getPoint(){
return array("x" => $this->x,
"y" => $this->y,
"label" => $this->label);
}
}
// "$label" is declared but not defined
$p1 = new Point2D(1.233, 3.445);
print_r(get_object_vars($p1));
$p1->setLabel("point #1");
print_r(get_object_vars($p1));
?>
Array
(
[x] => 1.233
[y] => 3.445
[label] =>
)
Array
(
[x] => 1.233
[y] => 3.445
[label] => point #1
)
若是 obj
是對象,則返回對象實例 obj
所屬類的父類名。
若是 obj
是字符串,則返回以此字符串爲名的類的父類名。此功能是在 PHP 4.0.5 中增長的。
<?php
class dad {
function dad(){
// implements some logic
}
}
class child extends dad {
function child(){
echo "I'm " , get_parent_class($this) , "'s son\n";
}
}
class child2 extends dad {
function child2(){
echo "I'm " , get_parent_class('child2') , "'s son too\n";
}
}
$foo = new child();
$bar = new child2();
?>
I'm dad's son
I'm dad's son too
參數:object
The tested object or class name
檢查接口是否已被定義。參數:
interface_name
接口名。
autoload
默認是否調用 __autoload。
返回值:本函數在由 interface_name
給出的接口已定義時返回 TRUE
,不然返回 FALSE
。
<?php
// 在嘗試使用前先檢查接口是否存在
if (interface_exists('MyInterface')) {
class MyClass implements MyInterface{
// Methods
}
}
?>
- is_a — 若是對象屬於該類或該類是此對象的父類則返回 TRUE
若是 object
是該類或該類是此對象的父類。參數:
object
The tested object
class_name
The class name
allow_string
If this parameter set to FALSE
, string class name as object
is not allowed. This also prevents from calling autoloader if the class doesn't exist.
返回值:Returns TRUE
if the object is of this class or has this class as one of its parents, FALSE
otherwise.
is_a() 例子:
<?php
// define a class
class WidgetFactory{
var $oink = 'moo';
}
// create a new object
$WF = new WidgetFactory();
if (is_a($WF, 'WidgetFactory')) {
echo "yes, \$WF is still a WidgetFactory\n";
}
?>
在 PHP 5 中使用 instanceof 運算符:
<?php
if ($WF instanceof WidgetFactory) {
echo 'Yes, $WF is a WidgetFactory';
}
?>
若是對象 object
所屬類是類 class_name
的子類,則返回 TRUE
,不然返回 FALSE
。參數:
object
A class name or an object instance
class_name
The class name
allow_string
If this parameter set to false, string class name as object
is not allowed. This also prevents from calling autoloader if the class doesn't exist.
返回值:This function returns TRUE
if the object object
, belongs to a class which is a subclass of class_name
, FALSE
otherwise.
<?php
// define a class
class WidgetFactory{
var $oink = 'moo';
}
// define a child class
class WidgetFactory_Child extends WidgetFactory{
var $oink = 'oink';
}
// create a new object
$WF = new WidgetFactory();
$WFC = new WidgetFactory_Child();
if (is_subclass_of($WFC, 'WidgetFactory')) {
echo "yes, $WFC is a subclass of WidgetFactory\n";
} else {
echo "no, $WFC is not a subclass of WidgetFactory\n";
}
if (is_subclass_of($WF, 'WidgetFactory')) {
echo "yes, $WF is a subclass of WidgetFactory\n";
} else {
echo "no, $WF is not a subclass of WidgetFactory\n";
}
// usable only since PHP 5.0.3
if (is_subclass_of('WidgetFactory_Child', 'WidgetFactory')) {
echo "yes, WidgetFactory_Child is a subclass of WidgetFactory\n";
} else {
echo "no, WidgetFactory_Child is not a subclass of WidgetFactory\n";
}
?>
yes, $WFC is a subclass of WidgetFactory
no, $WF is not a subclass of WidgetFactory
yes, WidgetFactory_Child is a subclass of WidgetFactory
檢查類的方法是否存在於指定的 object
中。參數:
object
對象示例或者類名。
method_name
方法名。
返回值:若是 method_name
所指的方法在 object
所指的對象類中已定義,則返回 TRUE
,不然返回 FALSE
。
method_exists() 例子:
<?php
$directory = new Directory('.');
var_dump(method_exists($directory,'read')); //bool(true)
?>
Static method_exists() 例子:
<?php
var_dump(method_exists('Directory','read')); //bool(true)
?>
本函數檢查給出的 property
是否存在於指定的類中(以及是否能在當前範圍內訪問)。參數:
class
字符串形式的類名或要檢查的類的一個對象
property
屬性的名字
返回值:若是該屬性存在則返回 TRUE
,若是不存在則返回 FALSE
,出錯返回 NULL
。
<?php
class myClass {
public $mine;
private $xpto;
static protected $test;
static function test() {
var_dump(property_exists('myClass', 'xpto')); //true
}
}
var_dump(property_exists('myClass', 'mine')); //true
var_dump(property_exists(new myClass, 'mine')); //true
var_dump(property_exists('myClass', 'xpto')); //true, as of PHP 5.3.0
var_dump(property_exists('myClass', 'bar')); //false
var_dump(property_exists('myClass', 'test')); //true, as of PHP 5.3.0
myClass::test();
?>
參數:
traitname
待檢查的 trait 的名稱
autoload
若是還沒有加載,是否使用自動加載(autoload)。
返回值:若是 trait 存在返回 TRUE
,不存在則返回 FALSE
。發生錯誤的時候返回 NULL
。
----------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------
MySQL函數:
取得最近一次與 link_identifier
關聯的 INSERT,UPDATE 或 DELETE 查詢所影響的記錄行數。參數:
link_identifier
MySQL 鏈接。如不指定鏈接標識,則使用由 mysql_connect() 最近打開的鏈接。若是沒有找到該鏈接,會嘗試不帶參數調用 mysql_connect() 來建立。如沒有找到鏈接或沒法創建鏈接,則會生成 E_WARNING
級別的錯誤。
mysql_affected_rows() 例子:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* 本例返回被刪除記錄的準確數目 */
mysql_query('DELETE FROM mytable WHERE id < 10');
printf("Records deleted: %d\n", mysql_affected_rows());
/* 對於非真值的 WHERE 子句,應返回 0 */
mysql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", mysql_affected_rows());
?>
Records deleted: 10
Records deleted: 0
使用事務處理的 mysql_affected_rows() 例子:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
/* Update records */
mysql_query("UPDATE mytable SET used=1 WHERE id < 10");
printf ("Updated records: %d\n", mysql_affected_rows());
mysql_query("COMMIT");
?>
從 MySQL 中取得 character_set 變量的值。參數:
link_identifier
MySQL 鏈接。如不指定鏈接標識,則使用由 mysql_connect() 最近打開的鏈接。若是沒有找到該鏈接,會嘗試不帶參數調用 mysql_connect() 來建立。如沒有找到鏈接或沒法創建鏈接,則會生成 E_WARNING
級別的錯誤。
返回值:返回當前鏈接的默認字符集名稱。
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$charset = mysql_client_encoding($link);
echo "The current character set is: $charset\n";
?>
The current character set is: latin1
mysql_close() 關閉指定的鏈接標識所關聯的到 MySQL 服務器的非持久鏈接。若是沒有指定 link_identifier
,則關閉上一個打開的鏈接。參數:
link_identifier
MySQL 鏈接. 若是該鏈接標識符未給出, 將使用最近一次mysql_connect()創建的鏈接. 若是沒有找到可以使用的鏈接, 將產生一個 E_WARNING
錯誤.
返回值:成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
打開或重複使用一個到 MySQL 服務器的鏈接。參數:
server
MySQL 服務器。能夠包括端口號,例如 "hostname:port",或者到本地套接字的路徑,例如對於 localhost 的 ":/path/to/socket"。
若是 PHP 指令 mysql.default_host 未定義(默認狀況),則默認值是 'localhost:3306'。 在 SQL 安全模式 時,參數被忽略,老是使用 'localhost:3306'。
username
用戶名。默認值由 mysql.default_user 定義。 在 SQL 安全模式 時,參數被忽略,老是使用服務器進程全部者的用戶名。
password
密碼。默認值由mysql.default_password定義。在 SQL 安全模式 時,參數被忽略,老是使用空密碼。
new_link
若是用一樣的參數第二次調用 mysql_connect(),將不會創建新鏈接,而將返回已經打開的鏈接標識。參數new_link
改變此行爲並使 mysql_connect() 老是打開新的鏈接,甚至當 mysql_connect() 曾在前面被用一樣的參數調用過。
client_flags
client_flags
參數能夠是如下常量的組合:MYSQL_CLIENT_SSL
,MYSQL_CLIENT_COMPRESS
,MYSQL_CLIENT_IGNORE_SPACE
或MYSQL_CLIENT_INTERACTIVE
。進一步信息見MySQL 客戶端常量。
返回值:若是成功則返回一個 MySQL 鏈接標識, 或者在失敗時返回 FALSE
。
mysql_connect() 例子:
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
mysql_connect() 例子:使用
hostname:port 語法:
<?php
// we connect to example.com and port 3307
$link = mysql_connect('example.com:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
// we connect to localhost at port 3307
$link = mysql_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
mysql_connect() 例子:使用 ":/path/to/socket" 語法:
<?php
// we connect to localhost and socket e.g. /tmp/mysql.sock
//variant 1: ommit localhost
$link = mysql_connect('/tmp/mysql', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
// variant 2: with localhost
$link = mysql_connect('localhost:/tmp/mysql.sock', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
mysql_create_db() 嘗試在指定的鏈接標識所關聯的服務器上創建一個新數據庫。參數:
database_name
要建立的數據庫名。
link_identifier
MySQL 鏈接。如不指定鏈接標識,則使用由 mysql_connect() 最近打開的鏈接。若是沒有找到該鏈接,會嘗試不帶參數調用 mysql_connect() 來建立。如沒有找到鏈接或沒法創建鏈接,則會生成 E_WARNING
級別的錯誤。
返回值:成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
?>
Database my_db created successfully
mysql_data_seek() 將指定的結果標識所關聯的 MySQL 結果內部的行指針移動到指定的行號。接着調用mysql_fetch_row() 將返回那一行。參數:
result
resource 型的結果集。此結果集來自對 mysql_query() 的調用。
row_number
想要設定的新的結果集指針的行數。
返回值:成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sample_db');
if (!$db_selected) {
die('Could not select database: ' . mysql_error());
}
$query = 'SELECT last_name, first_name FROM friends';
$result = mysql_query($query);
if (!$result) {
die('Query failed: ' . mysql_error());
}
/* fetch rows in reverse order */
for ($i = mysql_num_rows($result) - 1; $i >= 0; $i--) {
if (!mysql_data_seek($result, $i)) {
echo "Cannot seek to row $i: " . mysql_error() . "\n";
continue;
}
if (!($row = mysql_fetch_assoc($result))) {
continue;
}
echo $row['last_name'] . ' ' . $row['first_name'] . "<br />\n";
}
mysql_free_result($result);
?>
<?php
error_reporting(E_ALL);
$link = mysql_connect('dbhost', 'username', 'password');
$db_list = mysql_list_dbs($link);
$i = 0;
$cnt = mysql_num_rows($db_list);
while ($i < $cnt) {
echo mysql_db_name($db_list, $i) . "\n";
$i++;
}
?>
根據查詢結果返回一個正的 MySQL 結果資源號,出錯時返回 FALSE
。本函數會對 INSERT/UPDATE/DELETE 查詢返回TRUE
/FALSE
來指示成功或失敗。
mysql_db_query() 選擇一個數據庫並在其上執行查詢。若是沒有提供可選的鏈接標識,本函數會去找一個到 MySQL 服務器的已打開的鏈接,若是找不到已打開鏈接則會嘗試無參數調用 mysql_connect() 來創建一個。
注意此函數不會切換回先前鏈接到的數據庫。換句話說,不能用此函數臨時在另外一個數據庫上執行 sql 查詢,只能手工切換回來。強烈建議用戶在 sql 查詢中使用 database.table 語法來替代此函數。
mysql_drop_db() 嘗試丟棄(刪除)指定鏈接標識所關聯的服務器上的一整個數據庫。
成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
爲向下兼容也能夠用 mysql_dropdb(),但反對這樣作。
不提倡使用 mysql_drop_db() 函數最好用 mysql_query() 提交一條 SQL DROP DATABASE 語句來替代。
database_name
The name of the database that will be deleted.
link_identifier
MySQL 鏈接。如不指定鏈接標識,則使用由
mysql_connect() 最近打開的鏈接。若是沒有找到該鏈接,會嘗試不帶參數調用
mysql_connect() 來建立。如沒有找到鏈接或沒法創建鏈接,則會生成
E_WARNING
級別的錯誤。返回值:成功時返回
TRUE
, 或者在失敗時返回
FALSE
。
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$sql = 'DROP DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db was successfully dropped\n";
} else {
echo 'Error dropping database: ' . mysql_error() . "\n";
}
?>
返回上一個 MySQL 函數的錯誤號碼,若是沒有出錯則返回 0(零)。
從 MySQL 數據庫後端來的錯誤再也不發出警告,要用 mysql_errno() 來提取錯誤代碼。注意本函數僅返回最近一次 MySQL 函數的執行(不包括 mysql_error() 和 mysql_errno())的錯誤代碼,所以若是要使用此函數,確保在調用另外一個 MySQL 函數以前檢查它的值。
<?php
mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("nonexistentdb");
echo mysql_errno() . ": " . mysql_error(). "\n";
mysql_select_db("kossu");
mysql_query("SELECT * FROM nonexistenttable");
echo mysql_errno() . ": " . mysql_error() . "\n";
?>
1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist
返回上一個 MySQL 函數的錯誤文本,若是沒有出錯則返回 ''(空字符串)。若是沒有指定鏈接資源號,則使用上一個成功打開的鏈接從 MySQL 服務器提取錯誤信息。
從 MySQL 數據庫後端來的錯誤再也不發出警告,要用 mysql_error() 來提取錯誤文本。注意本函數僅返回最近一次 MySQL 函數的執行(不包括 mysql_error() 和 mysql_errno())的錯誤文本,所以若是要使用此函數,確保在調用另外一個 MySQL 函數以前檢查它的值。
<?php
mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("nonexistentdb");
echo mysql_errno() . ": " . mysql_error(). "\n";
mysql_select_db("kossu");
mysql_query("SELECT * FROM nonexistenttable");
echo mysql_errno() . ": " . mysql_error() . "\n";
?>
1049: Unknown database 'nonexistentdb'
1146: Table 'kossu.nonexistenttable' doesn't exist
<?php
$item = "Zak's Laptop";
$escaped_item = mysql_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?>
Escaped string: Zak\'s Laptop
返回根據從結果集取得的行生成的數組,若是沒有更多行則返回 FALSE
。
mysql_fetch_array 使用 MYSQL_NUM:
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf ("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>
mysql_fetch_array 使用 MYSQL_ASSOC:
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
printf ("ID: %s Name: %s", $row["id"], $row["name"]);
}
mysql_free_result($result);
?>
mysql_fetch_array 使用 MYSQL_BOTH:
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
printf ("ID: %s Name: %s", $row[0], $row["name"]);
}
mysql_free_result($result);
?>
返回對應結果集的關聯數組,而且繼續移動內部數據指針。 mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二個可選參數 MYSQL_ASSOC 徹底相同。它僅僅返回關聯數組。參數:
result
resource 型的結果集。此結果集來自對 mysql_query() 的調用。
返回值:
返回根據從結果集取得的行生成的關聯數組;若是沒有更多行則返回 FALSE
。
若是結果中的兩個或以上的列具備相同字段名,最後一列將優先。要訪問同名的其它列,要麼用 mysql_fetch_row()來取得數字索引或給該列起個別名。 參見 mysql_fetch_array() 例子中有關別名說明。
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
?>
返回一個包含字段信息的對象。
mysql_fetch_field() 能夠用來從某個查詢結果中取得字段的信息。若是沒有指定字段偏移量,則下一個還沒有被mysql_fetch_field() 取得的字段被提取。
對象的屬性爲:
- name - 列名
- table - 該列所在的表名
- max_length - 該列最大長度
- not_null - 1,若是該列不能爲
NULL
- primary_key - 1,若是該列是 primary key
- unique_key - 1,若是該列是 unique key
- multiple_key - 1,若是該列是 non-unique key
- numeric - 1,若是該列是 numeric
- blob - 1,若是該列是 BLOB
- type - 該列的類型
- unsigned - 1,若是該列是無符號數
- zerofill - 1,若是該列是 zero-filled
<?php
mysql_connect('localhost:3306', $user, $password)
or die("Could not connect: " . mysql_error());
mysql_select_db("database");
$result = mysql_query("select * from table")
or die("Query failed: " . mysql_error());
/* get column metadata */
$i = 0;
while ($i < mysql_num_fields($result)) {
echo "Information for column $i:<br />\n";
$meta = mysql_fetch_field($result);
if (!$meta) {
echo "No information available<br />\n";
}
echo "<pre>
blob: $meta->blob
max_length: $meta->max_length
multiple_key: $meta->multiple_key
name: $meta->name
not_null: $meta->not_null
numeric: $meta->numeric
primary_key: $meta->primary_key
table: $meta->table
type: $meta->type
unique_key: $meta->unique_key
unsigned: $meta->unsigned
zerofill: $meta->zerofill
</pre>";
$i++;
}
mysql_free_result($result);
?>
返回根據所取得的行生成的對象,若是沒有更多行則返回 FALSE
。
mysql_fetch_object() 和 mysql_fetch_array() 相似,只有一點區別 - 返回一個對象而不是數組。間接地也意味着只能經過字段名來訪問數組,而不是偏移量(數字是合法的屬性名)。
mysql_fetch_object() example:
<?php
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
mysql_free_result($result);
?>
mysql_fetch_object() example:
<?php
class foo {
public $name;
}
mysql_connect("hostname", "user", "password");
mysql_select_db("mydb");
$result = mysql_query("select name from mytable limit 1");
$obj = mysql_fetch_object($result, 'foo');
var_dump($obj);
?>
返回根據所取得的行生成的數組,若是沒有更多行則返回 FALSE
。
mysql_fetch_row() 從和指定的結果標識關聯的結果集中取得一行數據並做爲數組返回。每一個結果的列儲存在一個數組的單元中,偏移量從 0 開始。
依次調用 mysql_fetch_row() 將返回結果集中的下一行,若是沒有更多行則返回 FALSE
。
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
mysql_field_flags() 返回指定字段的字段標誌。每一個標誌都用一個單詞表示,之間用一個空格分開,所以能夠用explode() 將其分開。
mysql_field_len() 返回指定字段的長度。
爲向下兼容仍然可使用 mysql_fieldlen(),但反對這樣作。
mysql_field_name() 返回指定字段索引的字段名。result
必須是一個合法的結果標識符,field_index
是該字段的數字偏移量。參數:
result
resource 型的結果集。此結果集來自對 mysql_query() 的調用。
field_offset
數值型字段偏移量。 field_offset
從 0 開始。若是 field_offset
不存在,則會發出一個 E_WARNING
級別的錯誤
返回值:The name of the specified field index on success 或者在失敗時返回 FALSE
.
<?php
/* The users table consists of three fields:
* user_id
* username
* password.
*/
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'mydb';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from users', $link);
echo mysql_field_name($res, 0) . "\n";
echo mysql_field_name($res, 2);
?>
返回指定字段所在的表的名字。
爲向下兼容仍然可使用 mysql_fieldtable(),但反對這樣作。
參數:
result
resource 型的結果集。此結果集來自對 mysql_query() 的調用。
field_offset
數值型字段偏移量。 field_offset
從 0 開始。若是 field_offset
不存在,則會發出一個 E_WARNING
級別的錯誤
<?php
mysql_connect("localhost", "mysql_username", "mysql_password");
mysql_select_db("mysql");
$result = mysql_query("SELECT * FROM func");
$fields = mysql_num_fields($result);
$rows = mysql_num_rows($result);
$table = mysql_field_table($result, 0);
echo "Your '".$table."' table has ".$fields." fields and ".$rows." record(s)\n";
echo "The table has the following fields:\n";
for ($i=0; $i < $fields; $i++) {
$type = mysql_field_type($result, $i);
$name = mysql_field_name($result, $i);
$len = mysql_field_len($result, $i);
$flags = mysql_field_flags($result, $i);
echo $type." ".$name." ".$len." ".$flags."\n";
}
mysql_free_result($result);
mysql_close();
?>
Your 'func' table has 4 fields and 1 record(s)
The table has the following fields:
string name 64 not_null primary_key binary
int ret 1 not_null
string dl 128 not_null
string type 9 not_null enum
mysql_free_result() 將釋放全部與結果標識符 result
所關聯的內存。
mysql_free_result() 僅須要在考慮到返回很大的結果集時會佔用多少內存時調用。在腳本結束後全部關聯的內存都會被自動釋放。
成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
爲向下兼容仍然可使用 mysql_freeresult(),但反對這樣作。參數:
result
resource 型的結果集。此結果集來自對 mysql_query() 的調用。
返回值:成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
/* Use the result, assuming we're done with it afterwards */
$row = mysql_fetch_assoc($result);
/* Now we free up the result and continue on with our script */
mysql_free_result($result);
echo $row['id'];
echo $row['email'];
?>
mysql_get_client_info() 返回一個字符串指出了客戶端庫的版本。
<?php
printf ("MySQL client info: %s\n", mysql_get_client_info());
?>
MySQL client info: 3.23.39
mysql_get_host_info() 返回一個字符串說明了鏈接 link_identifier
所使用的鏈接方式,包括服務器的主機名。若是省略 link_identifier
,則使用上一個打開的鏈接。
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
printf ("MySQL host info: %s\n", mysql_get_host_info());
?>
MySQL host info: Localhost via UNIX socket
mysql_get_proto_info() 返回 link_identifier
所使用的協議版本。若是省略 link_identifier
,則使用上一個打開的鏈接。
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
printf ("MySQL protocol version: %s\n", mysql_get_proto_info());
?>
MySQL protocol version: 10
mysql_get_server_info() 返回 link_identifier
所使用的服務器版本。若是省略 link_identifier
,則使用上一個打開的鏈接。
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
printf ("MySQL server version: %s\n", mysql_get_server_info());
?>
MySQL server version: 4.0.1-alpha
mysql_info() 返回經過給定的 link_identifier
所進行的最新一條查詢的詳細信息。若是沒有指定link_identifier
,則假定爲上一個打開的鏈接。
mysql_info() 對如下列出的全部語句返回一個字符串。對於其它任何語句返回 FALSE
。字符串的格式取決於給出的語句。
mysql_insert_id() 返回給定的 link_identifier
中上一步 INSERT 查詢中產生的 AUTO_INCREMENT 的 ID 號。若是沒有指定 link_identifier
,則使用上一個打開的鏈接。
若是上一查詢沒有產生 AUTO_INCREMENT 的值,則 mysql_insert_id() 返回 0。若是須要保存該值之後使用,要確保在產生了值的查詢以後當即調用 mysql_insert_id()。
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf ("Last inserted record has id %d\n", mysql_insert_id());
?>
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_object($db_list)) {
echo $row->Database . "\n";
}
?>
database1
database2
database3
...
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$fields = mysql_list_fields("database1", "table1", $link);
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {
echo mysql_field_name($fields, $i) . "\n";
}
field1
field2
field3
...
爲向下兼容仍然可使用 mysql_listfields(),但反對這樣作。
mysql_list_processes() 返回一個結果指針,說明了當前服務器的線程。
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_list_processes($link);
while ($row = mysql_fetch_assoc($result)){
printf("%s %s %s %s %s\n", $row["Id"], $row["Host"], $row["db"],
$row["Command"], $row["Time"]);
}
mysql_free_result ($result);
?>
1 localhost test Processlist 0
4 localhost mysql sleep 5
mysql_list_tables() 接受一個數據庫名並返回和 mysql_query() 函數很類似的一個結果指針。用 mysql_tablename()函數來遍歷此結果指針,或者任何使用結果表的函數,例如 mysql_fetch_array()。
database
參數是須要被取得其中的的表名的數據庫名。若是失敗 mysql_list_tables() 返回 FALSE
。
爲向下兼容仍然可使用本函數的別名 mysql_listtables(),但反對這樣作。
<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
print 'Could not connect to mysql';
exit;
}
$result = mysql_list_tables($dbname);
if (!$result) {
print "DB Error, could not list tables\n";
print 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
print "Table: $row[0]\n";
}
mysql_free_result($result);
?>
mysql_num_fields() 返回結果集中字段的數目。爲向下兼容仍然可使用 mysql_numfields(),但反對這樣作。
mysql_num_rows() 返回結果集中行的數目。此命令僅對 SELECT 語句有效。要取得被 INSERT,UPDATE 或者 DELETE 查詢所影響到的行的數目,用 mysql_affected_rows()。
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
若是成功則返回一個正的 MySQL 持久鏈接標識符,出錯則返回 FALSE
。
mysql_pconnect() 創建一個到 MySQL 服務器的鏈接。若是沒有提供可選參數,則使用以下默認值:server
= 'localhost:3306',username
= 服務器進程全部者的用戶名,password
= 空密碼。client_flags
參數能夠是如下常量的組合:MYSQL_CLIENT_COMPRESS,MYSQL_CLIENT_IGNORE_SPACE 或者 MYSQL_CLIENT_INTERACTIVE。
server
參數也能夠包括端口號,例如 "hostname:port",或者是本機套接字的的路徑,例如 ":/path/to/socket"。
mysql_pconnect() 和 mysql_connect() 很是類似,但有兩個主要區別。
首先,當鏈接的時候本函數將先嚐試尋找一個在同一個主機上用一樣的用戶名和密碼已經打開的(持久)鏈接,若是找到,則返回此鏈接標識而不打開新鏈接。
其次,當腳本執行完畢後到 SQL 服務器的鏈接不會被關閉,此鏈接將保持打開以備之後使用(mysql_close() 不會關閉由 mysql_pconnect() 創建的鏈接)。
可選參數 client_flags
自 PHP 4.3.0 版起可用。
此種鏈接稱爲「持久的」。
mysql_ping() 檢查到服務器的鏈接是否正常。若是斷開,則自動嘗試鏈接。本函數可用於空閒好久的腳原本檢查服務器是否關閉了鏈接,若是有必要則從新鏈接上。若是到服務器的鏈接可用則 mysql_ping() 返回 TRUE
,不然返回FALSE
。
mysql_query() 向與指定的 link_identifier
關聯的服務器中的當前活動數據庫發送一條查詢(不支持多條查詢)參數:
query
SQL 查詢語句
查詢字符串不該以分號結束。 查詢中被嵌入的數據應該正確地轉義。
link_identifier
MySQL 鏈接。如不指定鏈接標識,則使用由 mysql_connect() 最近打開的鏈接。若是沒有找到該鏈接,會嘗試不帶參數調用 mysql_connect() 來建立。如沒有找到鏈接或沒法創建鏈接,則會生成 E_WARNING
級別的錯誤。
返回值:
mysql_query() 僅對 SELECT,SHOW,DESCRIBE, EXPLAIN 和其餘語句 語句返回一個 resource,若是查詢出現錯誤則返回 FALSE
。
對於其它類型的 SQL 語句,好比INSERT, UPDATE, DELETE, DROP 之類, mysql_query() 在執行成功時返回 TRUE
,出錯時返回 FALSE
。
返回的結果資源應該傳遞給 mysql_fetch_array() 和其餘函數來處理結果表,取出返回的數據。
假定查詢成功,能夠調用 mysql_num_rows() 來查看對應於 SELECT 語句返回了多少行,或者調用mysql_affected_rows() 來查看對應於 DELETE,INSERT,REPLACE 或 UPDATE 語句影響到了多少行。
若是沒有權限訪問查詢語句中引用的表時,mysql_query() 也會返回 FALSE
。
無效的查詢:
<?php
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
?>
有效的查詢:
<?php
// 這應該由用戶提供,下面是一個示例
$firstname = 'fred';
$lastname = 'fox';
// 構造查詢
// 這是執行 SQL 最好的方式
// 更多例子參見 mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// 執行查詢
$result = mysql_query($query);
// 檢查結果
// 下面顯示了實際發送給 MySQL 的查詢,以及出現的錯誤。這對調試頗有幫助。
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// 結果的使用
// 嘗試 print $result 並不會取出結果資源中的信息
// 因此必須至少使用其中一個 mysql 結果函數
// 參見 mysql_result(), mysql_fetch_array(), mysql_fetch_row() 等。
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
// 釋放關聯結果集的資源
// 在腳本結束的時候會自動進行
mysql_free_result($result);
?>
本函數將 unescaped_string
中的特殊字符轉義,並計及鏈接的當前字符集,所以能夠安全用於 mysql_query()。
<?php
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?>
Escaped string: Zak\'s and Derick\'s Laptop
mysql_result() 返回 MySQL 結果集中一個單元的內容。字段參數能夠是字段的偏移量或者字段名,或者是字段表點字段名(tablename.fieldname)。若是給列起了別名('select foo as bar from...'),則用別名替代列名。
看成用於很大的結果集時,應該考慮使用可以取得整行的函數(在下邊指出)。這些函數在一次函數調用中返回了多個單元的內容,比 mysql_result() 快得多。此外注意在字段參數中指定數字偏移量比指定字段名或者 tablename.fieldname 要快得多。
調用 mysql_result() 不能和其它處理結果集的函數混合調用。
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password")
or die("Could not connect: " . mysql_error());
$result = mysql_query("SELECT name FROM work.employee")
or die("Could not query: . mysql_error());
echo mysql_result($result,2); // outputs third employee's name
mysql_close($link);
?>
成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
mysql_select_db() 設定與指定的鏈接標識符所關聯的服務器上的當前激活數據庫。若是沒有指定鏈接標識符,則使用上一個打開的鏈接。若是沒有打開的鏈接,本函數將無參數調用 mysql_connect() 來嘗試打開一個並使用之。
每一個其後的 mysql_query() 調用都會做用於活動數據庫。
<?php
$lnk = mysql_connect('localhost', 'mysql_user', 'mysql_password')
or die ('Not connected : ' . mysql_error());
// make foo the current db
mysql_select_db('foo', $lnk) or die ('Can\'t use foo : ' . mysql_error());
?>
設置當前鏈接的默認字符集。參數:
charset
一個有效的字符集名稱。
link_identifier
MySQL 鏈接。如不指定鏈接標識,則使用由 mysql_connect() 最近打開的鏈接。若是沒有找到該鏈接,會嘗試不帶參數調用 mysql_connect() 來建立。如沒有找到鏈接或沒法創建鏈接,則會生成 E_WARNING
級別的錯誤。
返回值:成功時返回 TRUE
, 或者在失敗時返回 FALSE
。
mysql_stat() 返回當前服務器狀態。
<?php
$link = mysql_connect('localhost', "mysql_user", "mysql_password");
$status = explode(' ', mysql_stat($link));
print_r($status);
?>
Array
(
[0] => Uptime: 5380
[1] => Threads: 2
[2] => Questions: 1321299
[3] => Slow queries: 0
[4] => Opens: 26
[5] => Flush tables: 1
[6] => Open tables: 17
[7] => Queries per second avg: 245.595
)
<?php
mysql_connect("localhost", "mysql_user", "mysql_password");
$result = mysql_list_tables("mydb");
for ($i = 0; $i < mysql_num_rows($result); $i++)
printf ("Table: %s\n", mysql_tablename($result, $i));
mysql_free_result($result);
?>
mysql_thread_id() 返回當前線程的 ID。若是鏈接丟失了並用 mysql_ping() 從新鏈接上,線程 ID 會改變。這意味着不能取得線程的 ID 後保存起來備用。當須要的時候再去獲取之。
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$thread_id = mysql_thread_id($link);
if ($thread_id){
printf ("current thread id is %d\n", $thread_id);
}
?>
mysql_unbuffered_query() 向 MySQL 發送一條 SQL 查詢 query
,但不像 mysql_query() 那樣自動獲取並緩存結果集。一方面,這在處理很大的結果集時會節省可觀的內存。另外一方面,能夠在獲取第一行後當即對結果集進行操做,而不用等到整個 SQL 語句都執行完畢。當使用多個數據庫鏈接時,必須指定可選參數 link_identifier
。
----------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------
Math函數:
<?php
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5); // $abs2 = 5; (integer)
$abs3 = abs(-5); // $abs3 = 5; (integer)
?>
<?php
$hexadecimal = 'A37334';
echo base_convert($hexadecimal, 16, 2); //101000110111001100110100
?>
<?php
echo ceil(4.3); // 5
echo ceil(9.999); // 10
echo ceil(-3.14); // -3
?>
<?php
echo cos(M_PI); // -1
?>
<?php
echo decbin(12) . "\n"; //1100
echo decbin(26); //11010
?>
<?php
echo dechex(10) . "\n"; //a
echo dechex(47); //2f
?>
<?php
echo decoct(15) . "\n"; //17
echo decoct(264); //410
?>
<?php
echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)
?>
<?php
echo exp(12) . "\n"; //1.6275E+005
echo exp(5.7); //298.87
?>
- expm1 — 返回 exp(number) - 1,甚至當 number 的值接近零也能計算出準確結果
- floor — 捨去法取整
<?php
echo floor(4.3); // 4
echo floor(9.999); // 9
echo floor(-3.14); // -4
?>
<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?>
<?php
// Invalid calculation, will return a
// NaN value
$nan = acos(8);
var_dump($nan, is_nan($nan));
?>
<?php
echo max(1, 3, 5, 6, 7); // 7
echo max(array(2, 4, 5)); // 5
// When 'hello' is cast as integer it will be 0. Both the parameters are equally
// long, so the order they are given in determines the result
echo max(0, 'hello'); // 0
echo max('hello', 0); // hello
echo max('42', 3); // '42'
// Here 0 > -1, so 'hello' is the return value.
echo max(-1, 'hello'); // hello
// With multiple arrays of different lengths, max returns the longest
$val = max(array(2, 2, 2), array(1, 1, 1, 1)); // array(1, 1, 1, 1)
// 對多個數組,max 從左向右比較。
// 所以在本例中:2 == 2,但 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)
// 若是同時給出數組和非數組做爲參數,則老是將數組視爲
// 最大值返回
$val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)
?>
<?php
echo min(2, 3, 1, 6, 7); // 1
echo min(array(2, 4, 5)); // 2
echo min(0, 'hello'); // 0
echo min('hello', 0); // hello
echo min('hello', -1); // -1
// 對多個數組,min 從左向右比較。
// 所以在本例中:2 == 2,但 4 < 5
$val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8)
// 若是同時給出數組和非數組做爲參數,則不可能返回數組,由於
// 數組被視爲最大的
$val = min('string', array(2, 5, 7), 42); // string
?>
<?php
function randomFloat($min = 0, $max = 1) {
return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}
var_dump(randomFloat());
var_dump(randomFloat(2, 20));
?>
float(0.91601131712832)
float(16.511210331931)
若是沒有提供可選參數 min
和 max
,mt_rand() 返回 0 到 mt_getrandmax() 之間的僞隨機數。例如想要 5 到 15(包括 5 和 15)之間的隨機數,用 mt_rand(5, 15)。參數:
<?php
echo mt_rand() . "\n";
echo mt_rand() . "\n";
echo mt_rand(5, 15);
?>
用 seed
來給隨機數發生器播種。 沒有設定 seed
參數時,會被設爲隨時數。參數:
<?php
// seed with microseconds
function make_seed(){
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$randval = mt_rand();
?>
<?php
echo octdec('77') . "\n"; //63
echo octdec(decoct(45)); //45
?>
<?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?>
<?php
echo rad2deg(M_PI_4); // 45
?>
<?php
echo rand() . "\n"; //7771
echo rand() . "\n"; //22264
echo rand(5, 15); //11
?>
<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>
<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP); // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD); // 9
echo round(8.5, 0, PHP_ROUND_HALF_UP); // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD); // 9
?>
<?php
// 返回值的精度由配置中的 precision 指示肯定
echo sin(deg2rad(60)); // 0.866025403 ...
echo sin(60); // -0.304810621 ...
?>
<?php
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>
<?php
// seed with microseconds
function make_seed(){
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand();
?>
<?php
echo tan(M_PI_4); // 1
?>
----------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------
Date/Time函數:
檢查由參數構成的日期的合法性。若是每一個參數都正肯定義了則會被認爲是有效的。參數:
month
month 的值是從 1 到 12。
day
Day
的值在給定的 month
所應該具備的天數範圍以內,閏年已經考慮進去了。
year
year 的值是從 1 到 32767。
返回值:若是給出的日期有效則返回 TRUE
,不然返回 FALSE
。
<?php
var_dump(checkdate(12, 31, 2000)); //bool(true)
var_dump(checkdate(2, 29, 2001)); //bool(false)
?>
本函數返回默認時區,使用以下「假定」的順序:
-
用 date_default_timezone_set() 函數設定的時區(若是設定了的話)
-
僅僅在 PHP 5.4.0 以前: TZ 環境變量(若是非空)
-
date.timezone 配置選項(若是設定了的話)
-
僅僅在 PHP 5.4.0 以前: 查詢操做系統主機 (若是操做系統支持並容許)。
-
若是以上選擇都不成功,date_default_timezone_get() 會則返回 UTC 的默認時區。
獲取默認時區:
<?php
date_default_timezone_set('Europe/London');
if (date_default_timezone_get()) {
echo 'date_default_timezone_set: ' . date_default_timezone_get() . '<br />';
}
if (ini_get('date.timezone')) {
echo 'date.timezone: ' . ini_get('date.timezone');
}
?>
以上例程會輸出:
date_default_timezone_set: Europe/London
date.timezone: Europe/London
獲取一個時區的簡寫:
<?php
date_default_timezone_set('America/Los_Angeles');
echo date_default_timezone_get() . ' => ' . date('e') . ' => ' . date('T');
?>
America/Los_Angeles => America/Los_Angeles => PST
date_default_timezone_set() 設定用於全部日期時間函數的默認時區。參數:
timezone_identifier
時區標識符, UTC 或 Europe/Lisbon。合法標識符列表見所支持的時區列表。
返回值:若是 timezone_identifier
參數無效則返回 FALSE
,不然返回 TRUE
。
獲取默認時區
<?php
date_default_timezone_set('America/Los_Angeles');
$script_tz = date_default_timezone_get();
if (strcmp($script_tz, ini_get('date.timezone'))){
echo 'Script timezone differs from ini-set timezone.';
} else {
echo 'Script timezone and ini-set timezone match.';
}
?>
Returns associative array with detailed info about given date.參數:
format
Format accepted by DateTime::createFromFormat().
date
String representing the date.
<?php
$date = "6.1.2009 13:00+01:00";
print_r(date_parse_from_format("j.n.Y H:iP", $date));
?>
- date_parse — Returns associative array with detailed info about given date
date
Date in format accepted by strtotime().
返回值:Returns array with information about the parsed date on success 或者在失敗時返回 FALSE
.
<?php
print_r(date_parse("2006-12-12 10:00:00.5"));
?>
Array
(
[year] => 2006
[month] => 12
[day] => 12
[hour] => 10
[minute] => 0
[second] => 0
[fraction] => 0.5
[warning_count] => 0
[warnings] => Array()
[error_count] => 0
[errors] => Array()
[is_localtime] =>
)
- date_sub — 別名 DateTime::sub
- date_sun_info — Returns an array with information about sunset/sunrise and twilight begin/end
time
Timestamp.
latitude
Latitude in degrees.
longitude
Longitude in degrees.返回值:Returns array on success 或者在失敗時返回
FALSE
.
<?php
$sun_info = date_sun_info(strtotime("2006-12-12"), 31.7667, 35.2333);
foreach ($sun_info as $key => $val) {
echo "$key: " . date("H:i:s", $val) . "\n";
}
?>
sunrise: 05:52:11
sunset: 15:41:21
transit: 10:46:46
civil_twilight_begin: 05:24:08
civil_twilight_end: 16:09:24
nautical_twilight_begin: 04:52:25
nautical_twilight_end: 16:41:06
astronomical_twilight_begin: 04:21:32
astronomical_twilight_end: 17:12:00
date_sunrise() 返回給定的日期(以 timestamp
指定)與地點的日出時間。參數:
timestamp
取
timestamp
所在日期的日出時間。
format
format
常量
常量 |
說明 |
取值舉例 |
SUNFUNCS_RET_STRING |
以 string 格式返回結果 |
16:46 |
SUNFUNCS_RET_DOUBLE |
以 float 格式返回結果 |
16.78243132 |
SUNFUNCS_RET_TIMESTAMP |
以 integer 格式(時間戳)返回結果 |
1095034606 |
latitude
默認是指北緯。所以若是要指定南緯,必須傳遞一個負值。 參見
date.default_latitude。
longitude
默認是指東經。所以若是要指定西經,必須傳遞一個負值。 參見
date.default_longitude。
zenith
默認:
date.sunrise_zenith。
gmtoffset
單位是小時。返回值:按指定格式
format
返回的日出時間, 或者在失敗時返回
FALSE
。<?php
/* 計算葡萄牙里斯本的日出時間
Latitude: 北緯 38.4 度
Longitude: 西經 9 度
Zenith ~= 90
offset: +1 GMT
*/
echo date("D M d Y"). ', sunrise time : ' .date_sunrise(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);
?>
Mon Dec 20 2004, sunrise time : 08:54
date_sunset() 返回給定的日期(以 timestamp
指定)與地點的日落時間。參數:
timestamp
返回給定的日期(以
timestamp
指定)的日落時間。
format
format
常量
常量 |
說明 |
取值舉例 |
SUNFUNCS_RET_STRING |
以 string 格式返回結果 |
16:46 |
SUNFUNCS_RET_DOUBLE |
以 float 格式返回結果 |
16.78243132 |
SUNFUNCS_RET_TIMESTAMP |
以 integer 格式(時間戳)返回結果 |
1095034606 |
latitude
默認是指北緯。所以若是要指定南緯,必須傳遞一個負值。參見:
date.default_latitude。
longitude
默認是指東經。所以若是要指定西經,必須傳遞一個負值。參見:
date.default_longitude
zenith
默認:
date.sunset_zenith。
gmtoffset
單位是小時。返回值:用指定的格式
format
返回日落時間, 或者在失敗時返回
FALSE
。<?php
/* calculate the sunset time for Lisbon, Portugal
Latitude: 38.4 North
Longitude: 9 West
Zenith ~= 90
offset: +1 GMT
*/
echo date("D M d Y"). ', sunset time : ' .date_sunset(time(), SUNFUNCS_RET_STRING, 38.4, -9, 90, 1);
?>
Mon Dec 20 2004, sunset time : 18:13
返回將整數 timestamp
按照給定的格式字串而產生的字符串。若是沒有給出時間戳則使用本地當前時間。換句話說,timestamp
是可選的,默認值爲 time()。
date() 函數示例:
<?php
// 設置默認時區。PHP 5.1 以後版本可用
date_default_timezone_set('UTC');
// 輸出相似: Monday
echo date("l");
// 輸出相似:Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// 輸出:July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* 使用格式常量 */
// 輸出相似: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);
// 輸出相似:2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>
對 date() 函數中的格式字符串進行轉義:
<?php
// 輸出相似: Wednesday the 15th
echo date('l \t\h\e jS');
?>
<?php
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
?>
date() 函數格式化:
<?php
// 假設今天是 2001 年 3 月 10 日下午 5 點 16 分 18 秒,
// 而且位於山區標準時間(MST)時區
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
?>
返回一個根據 timestamp
得出的包含有日期信息的關聯數組 array。若是沒有給出時間戳則認爲是當前本地時間。參數:
timestamp
可選的 timestamp
參數是一個 integer 的 Unix 時間戳,如未指定,參數值默認爲當前本地時間。也就是說,其值默認爲 time() 的返回值。
返回值:返回一個根據 timestamp
得出的包含有日期信息的關聯數組 array。
<?php
$today = getdate();
print_r($today);
?>
Array
(
[seconds] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
)
本函數是 gettimeofday(2) 的接口。返回一個關聯數組,包含有系統調用返回的數據。參數:
return_float
當其設爲 TRUE
時,會返回一個浮點數而不是一個數組。
返回值:默認返回一個
array。若是
return_float
設置了則會返回一個
float。
數組中的鍵爲:
- "sec" - 自 Unix 紀元起的秒數
- "usec" - 微秒數
- "minuteswest" - 格林威治向西的分鐘數
- "dsttime" - 夏令時修正的類型
<?php
print_r(gettimeofday());
echo gettimeofday(true);
?>
Array
(
[sec] => 1073504408
[usec] => 238215
[minuteswest] => 0
[dsttime] => 1
)
1073504408.23910
同 date() 函數徹底同樣,只除了返回的時間是格林威治標準時(GMT)。例如當在中國(GMT +0800)運行如下程序時,第一行顯示「Jan 01 2000 00:00:00」而第二行顯示「Dec 31 1999 16:00:00」。
<?php
echo date("M d Y H:i:s", mktime (0,0,0,1,1,2000));
echo gmdate("M d Y H:i:s", mktime (0,0,0,1,1,2000));
?>
和 mktime() 徹底同樣,只除了返回值是格林威治標準時的時間戳。
參數老是表示 GMT 日期,所以 is_dst
對結果沒有影響。
和 mktime() 同樣,參數能夠從右到左依次空着,空着的參數會被設爲相應的當前 GMT 值。
和 strftime() 的行爲相同,只除了返回時間是格林威治標準時(GMT)。例如,當在東部標準時(EST,GMT -500)運行時,下面第一行顯示「Dec 31 1998 20:00:00」,而第二行顯示「Jan 01 1999 01:00:00」。
<?php
setlocale(LC_TIME, 'en_US');
echo strftime("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";
echo gmstrftime("%b %d %Y %H:%M:%S", mktime (20,0,0,12,31,98))."\n";
?>
根據給定的格式字符對 timestamp
格式化並返回數字結果。timestamp
爲可選項,默認值爲本地當前時間,即time() 的值。
和 date() 不一樣,idate() 只接受一個字符做爲 format
參數。
<?php
$timestamp = strtotime('1st January 2004'); //1072915200
// 下面以兩位數字格式顯示年份,可是由於
// 以「0」打頭,所以只會顯示「4」
echo idate('y', $timestamp);
?>
localtime() 函數返回一個數組,其結構和 C 函數調用返回的徹底同樣。參數:
timestamp
可選的 timestamp
參數是一個 integer 的 Unix 時間戳,如未指定,參數值默認爲當前本地時間。也就是說,其值默認爲 time() 的返回值。
is_associative
若是設爲 FALSE
或未提供則返回的是普通的數字索引數組。若是該參數設爲 TRUE
則 localtime() 函數返回包含有全部從 C 的 localtime 函數調用所返回的不一樣單元的關聯數組。關聯數組中不一樣的鍵名爲:
- "tm_sec" - 秒數, 0 到 59
- "tm_min" - 分鐘數, 0 到 59
- "tm_hour" - 小時, 0 到 23
- "tm_mday" - 月份中的第幾日, 1 到 31
- "tm_mon" - 年份中的第幾個月, 0 (Jan) 到 11 (Dec)
- "tm_year" - 年份,從 1900 開始
- "tm_wday" - 星期中的第幾天, 0 (Sun) 到 6 (Sat)
- "tm_yday" - 一年中的第幾天, 0 到 365
- "tm_isdst" - 夏令時當前是否生效? 若是是生效的是正數, 0 表明未生效,負數表明未知。
<?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>
microtime() 當前 Unix 時間戳以及微秒數。本函數僅在支持 gettimeofday() 系統調用的操做系統下可用。
若是調用時不帶可選參數,本函數以 "msec sec" 的格式返回一個字符串,其中 sec 是自 Unix 紀元(0:00:00 January 1, 1970 GMT)起到如今的秒數,msec 是微秒部分。字符串的兩部分都是以秒爲單位返回的。
若是給出了 get_as_float
參數而且其值等價於 TRUE
,microtime() 將返回一個浮點數。
用 microtime() 對腳本的運行計時
<?php
/**
* Simple function to replicate PHP 5 behaviour
*/
function microtime_float(){
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
// Sleep for a while
usleep(100);
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "Did nothing in $time seconds\n";
?>
根據給出的參數返回 Unix 時間戳。時間戳是一個長整數,包含了從 Unix 紀元(January 1 1970 00:00:00 GMT)到給定時間的秒數。參數能夠從右向左省略,任何省略的參數會被設置成本地日期和時間的當前值。
mktime() 例子:mktime() 在作日期計算和驗證方面頗有用,它會自動計算超出範圍的輸入的正確值。例以下面例子中每一行都會產生字符串 "Jan-01-1998"。
<?php
echo date("M-d-Y", mktime(0, 0, 0, 12, 32, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 13, 1, 1997));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 1998));
echo date("M-d-Y", mktime(0, 0, 0, 1, 1, 98));
?>
下個月的最後一天:任何給定月份的最後一天均可以被表示爲下個月的第 "0" 天,而不是 -1 天。下面兩個例子都會產生字符串 "The last day in Feb 2000 is: 29"。
<?php
$lastday = mktime(0, 0, 0, 3, 0, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
$lastday = mktime(0, 0, 0, 4, -31, 2000);
echo strftime("Last day in Feb 2000 is: %d", $lastday);
?>
返回值:根據指定的 timestamp
或未給出 timestamp 是使用當前本地時間, 返回 format
格式化的字符。 月份、星期名和其餘與語言相關的字符串遵照 setlocale() 設置的當前區域設置。
strptime() 返回一個將 date
解析後的數組,若是出錯返回 FALSE
。
月份和星期幾的名字以及其它與語種有關的字符串對應於 setlocale()設定的當前區域(LC_TIME
)。參數:
date
(string)
被解析的字符串(例如從 strftime() 返回的)
format
(string)
date
所使用的格式(例如同 strftime() 中所使用的相同)。
返回值:返回一個數組 或者在失敗時返回 FALSE
數組中包含如下單元
鍵名 |
說明 |
tm_sec |
當前分鐘內的秒數(0-61) |
tm_min |
當前小時內的分鐘數(0-59) |
tm_hour |
午夜起的小時數(0-23) |
tm_mday |
月份中的第幾天(1-31) |
tm_mon |
自一月起過了幾個月(0-11) |
tm_year |
自 1900 年起過了幾年 |
tm_wday |
自星期天起過了幾天(0-6) |
tm_yday |
本年自一月一日起過了多少天(0-365) |
unparsed |
date 中未能經過指定的 format 識別的部分 |
<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);
echo "$strf\n";
print_r(strptime($strf, $format));
?>
03/10/2004 15:54:19
Array
(
[tm_sec] => 19
[tm_min] => 54
[tm_hour] => 15
[tm_mday] => 3
[tm_mon] => 9
[tm_year] => 104
[tm_wday] => 0
[tm_yday] => 276
[unparsed] =>
)
本函數預期接受一個包含美國英語日期格式的字符串並嘗試將其解析爲 Unix 時間戳(自 January 1 1970 00:00:00 GMT 起的秒數),其值相對於 now
參數給出的時間,若是沒有提供此參數則用系統當前時間。參數
time
日期/時間字符串。正確格式的說明詳見 日期與時間格式。
now
用來計算返回值的時間戳。
返回值:成功則返回時間戳,不然返回 FALSE
。在 PHP 5.1.0 以前本函數在失敗時返回 -1。
strtotime() 例子:
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
失敗檢查:
<?php
$str = 'Not Good';
// previous to PHP 5.1.0 you would compare with -1, instead of false
if (($timestamp = strtotime($str)) === false) {
echo "The string ($str) is bogus";
} else {
echo "$str == " . date('l dS of F Y h:i:s A', $timestamp);
}
?>
返回自從 Unix 紀元(格林威治時間 1970 年 1 月 1 日 00:00:00)到當前時間的秒數。
<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60secs
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>
Now: 2005-03-30
Next Week: 2005-04-06
Next Week: 2005-04-06
Returns the current version of the timezonedb.
<?php
echo timezone_version_get();
?>