PHP函数库(other)

PHP函数库(other)

Session函数:
  • session_abort — Discard session array changes and finish 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 信息的数组:
  • "lifetime" - cookie 的生命周期,以秒为单位。
  • "path" - cookie 的访问路径。
  • "domain" - cookie 的域。
  • "secure" - 仅在使用安全链接时发送 cookie。
  • "httponly" - 只能经过 http 协议访问 cookie
  • session_id — 获取/设置当前会话 ID
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_write_close() 函数注册为关闭会话的函数。参数:
此函数没有参数。
返回值:没有返回值。
  • 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 — Re-initialize session array with original values
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函数:
你能够经过定义这个函数来启用类的自动加载。参数:
class

待加载的类名。

返回值:没有返回值。
基于用户定义的类 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();
}
?>
  • get_called_class — 后期静态绑定("Late Static Binding")类的名称
获取静态方法调用的类名。参数:
返回类的名称,若是不是在类中调用则返回 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";
}
?>
myclass
myfunc1
myfunc2
返回由类的默认公有属性组成的关联数组,此数组的元素以 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';
}
?>
  • is_subclass_of — 若是此对象是该类的子类,则返回 TRUE
若是对象 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_nameFALSEotherwise.
<?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");
?>
Updated Records: 10
从 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);
?>
Connected successfully
打开或重复使用一个到 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_SSLMYSQL_CLIENT_COMPRESSMYSQL_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);
?>
取得 mysql_list_dbs() 调用所返回的数据库名。参数:
result

mysql_list_dbs() 调用所返回的结果指针。

row

结果集中的行号。

field

字段名。

返回值:若是成功则返回数据库名,失败返回 FALSE。若是返回了 FALSE,用 mysql_error() 来判断错误的种类。
<?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_errno — 返回上一个 MySQL 操做中的错误信息的数字编码

返回上一个 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_error — 返回上一个 MySQL 操做产生的文本错误信息

返回上一个 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
本函数将 unescaped_string 转义,使之能够安全用于 mysql_query()
<?php
    $item = "Zak's Laptop";
    $escaped_item = mysql_escape_string($item);
    printf ("Escaped string: %s\n", $escaped_item);
?>
Escaped string: Zak\'s Laptop
  • mysql_fetch_array — 从结果集中取得一行做为关联数组,或数字数组,或两者兼有
返回根据从结果集取得的行生成的数组,若是没有更多行则返回 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);
?>

以数组返回上一次用 mysql_fetch_row() 取得的行中每一个字段的长度,若是出错返回 FALSE

mysql_fetch_lengths() 将上一次 mysql_fetch_row()mysql_fetch_array() 和 mysql_fetch_object() 所返回的每一个列的长度储存到一个数组中,偏移量从 0 开始。参数:

返回根据所取得的行生成的对象,若是没有更多行则返回 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);
?>
user_id
password
  • mysql_field_seek — 将结果集中的指针设定为制定的字段偏移量
用指定的字段偏移量检索。若是下一个 mysql_fetch_field() 的调用不包括字段偏移量,则会返回本次mysql_field_seek() 中指定的偏移量的字段。

返回指定字段所在的表的名字。

为向下兼容仍然可使用 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 — 取得最近一条查询的信息

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());
?>
mysql_list_dbs() 将返回一个结果指针,包含了当前 MySQL 进程中全部可用的数据库。用 mysql_tablename() 函数来遍历此结果指针,或者任何使用结果表的函数,例如 mysql_fetch_array()
<?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
...
mysql_list_fields() 取得给定表名的信息。参数是数据库名和表名。返回一个结果指针,能够用于mysql_field_flags()mysql_field_len()mysql_field_name() 和 mysql_field_type()
<?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 — Ping 一个服务器链接,若是没有链接则从新链接
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);
?>

  • mysql_real_escape_string — 转义 SQL 语句中使用的字符串中的特殊字符,并考虑到链接的当前字符集
本函数将 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
)
mysql_tablename() 接受 mysql_list_tables() 返回的结果指针以及一个整数索引做为参数并返回表名。能够用mysql_num_rows() 函数来判断结果指针中的表的数目。用 mysql_tablename() 函数来遍历此结果指针,或者任何处理结果表的函数,例如 mysql_fetch_array()
<?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);
}
?>
current thread id is 73
mysql_unbuffered_query() 向 MySQL 发送一条 SQL 查询 query,但不像 mysql_query() 那样自动获取并缓存结果集。一方面,这在处理很大的结果集时会节省可观的内存。另外一方面,能够在获取第一行后当即对结果集进行操做,而不用等到整个 SQL 语句都执行完毕。当使用多个数据库链接时,必须指定可选参数 link_identifier
----------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------
Math函数:
  • abs — 绝对值
<?php
$abs = abs(-4.2); // $abs = 4.2; (double/float)
$abs2 = abs(5);   // $abs2 = 5; (integer)
$abs3 = abs(-5);  // $abs3 = 5; (integer)
?>
  • acos — 反余弦
  • acosh — 反双曲余弦
  • asin — 反正弦
  • asinh — 反双曲正弦
  • atan2 — 两个参数的反正切
  • atan — 反正切
  • atanh — 反双曲正切
  • base_convert — 在任意进制之间转换数字
<?php
$hexadecimal = 'A37334';
echo base_convert($hexadecimal, 16, 2);    //101000110111001100110100
?>
  • bindec — 二进制转换为十进制
  • ceil — 进一法取整
<?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?>
  • cos — 余弦
<?php
echo cos(M_PI); // -1
?>
  • cosh — 双曲余弦
  • decbin — 十进制转换为二进制
<?php
echo decbin(12) . "\n";    //1100
echo decbin(26);    //11010
?>
  • dechex — 十进制转换为十六进制
<?php
echo dechex(10) . "\n";    //a
echo dechex(47);    //2f
?>
  • decoct — 十进制转换为八进制
<?php
echo decoct(15) . "\n";    //17
echo decoct(264);    //410
?>
  • deg2rad — 将角度转换为弧度
<?php
echo deg2rad(45); // 0.785398163397
var_dump(deg2rad(45) === M_PI_4); // bool(true)
?>
  • exp — 计算 e 的指数
<?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
?>
  • fmod — 返回除法的浮点数余数
<?php
$x = 5.7;
$y = 1.3;
$r = fmod($x, $y);
// $r equals 0.5, because 4 * 1.3 + 0.5 = 5.7
?>
  • getrandmax — 显示随机数最大的可能值
  • hexdec — 十六进制转换为十进制
  • hypot — 计算一直角三角形的斜边长度
  • intdiv — Integer division
  • is_finite — 判断是否为有限值
  • is_infinite — 判断是否为无限值
  • is_nan — 判断是否为合法数值
<?php
// Invalid calculation, will return a 
// NaN value
$nan = acos(8);
var_dump($nan, is_nan($nan));
?>
float(NAN)
bool(true)
  • lcg_value — 组合线性同余发生器
  • log10 — 以 10 为底的对数
  • log1p — 返回 log(1 + number),甚至当 number 的值接近零也能计算出准确结果
  • log — 天然对数
  • max — 找出最大值
<?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)
?>
  • min — 找出最小值
<?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)
  • mt_rand — 生成更好的随机数
若是没有提供可选参数 min 和 max,mt_rand() 返回 0 到 mt_getrandmax() 之间的伪随机数。例如想要 5 到 15(包括 5 和 15)之间的随机数,用 mt_rand(5, 15)。参数:
min

可选的、返回的最小值(默认:0)

max

可选的、返回的最大值(默认:mt_getrandmax()

返回值:返回 min (或者 0) 到 max (或者是到 mt_getrandmax() ,包含这个值)之间的随机整数。
<?php
echo mt_rand() . "\n";
echo mt_rand() . "\n";
echo mt_rand(5, 15);
?>

以上例程的输出相似于:

1604716014
1478613278
6
  • mt_srand — 播下一个更好的随机数发生器种子
用 seed 来给随机数发生器播种。 没有设定 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();
?>
  • octdec — 八进制转换为十进制
<?php
echo octdec('77') . "\n";    //63
echo octdec(decoct(45));    //45
?>
  • pi — 获得圆周率值
<?php
echo pi(); // 3.1415926535898
echo M_PI; // 3.1415926535898
?>
  • pow — 指数表达式
  • rad2deg — 将弧度数转换为相应的角度数
<?php
echo rad2deg(M_PI_4); // 45
?>
  • rand — 产生一个随机整数
<?php
echo rand() . "\n";    //7771
echo rand() . "\n";    //22264
echo rand(5, 15);    //11
?>
  • round — 对浮点数进行四舍五入
<?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
?>
  • sin — 正弦
<?php
// 返回值的精度由配置中的 precision 指示肯定
echo sin(deg2rad(60));  //  0.866025403 ...
echo sin(60);           // -0.304810621 ...
?>
  • sinh — 双曲正弦
  • sqrt — 平方根
<?php
// Precision depends on your precision directive
echo sqrt(9); // 3
echo sqrt(10); // 3.16227766 ...
?>
  • srand — 播下随机数发生器种子
<?php
// seed with microseconds
function make_seed(){
  list($usec, $sec) = explode(' ', microtime());
  return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand();
?>
  • tan — 正切
<?php
echo tan(M_PI_4); // 1
?>
  • tanh — 双曲正切
----------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------
Date/Time函数:
  • checkdate — 验证一个格里高里日期
检查由参数构成的日期的合法性。若是每一个参数都正肯定义了则会被认为是有效的。参数:
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 的默认时区。

返回值:返回一个 string
 获取默认时区:
<?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 — 返回给定的日期与地点的日出时间
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_latitudelongitude    默认是指东经。所以若是要指定西经,必须传递一个负值。 参见  date.default_longitudezenith    默认:  date.sunrise_zenithgmtoffset    单位是小时。返回值:按指定格式  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 — 返回给定的日期与地点的日落时间
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_latitudelongitude    默认是指东经。所以若是要指定西经,必须传递一个负值。参见:  date.default_longitude zenith    默认:  date.sunset_zenithgmtoffset    单位是小时。返回值:用指定的格式  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');
?>
date() 和 mktime() 联合使用示例:
<?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
?>
  • getdate — 取得日期/时间信息
返回一个根据 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
  • gmdate — 格式化一个 GMT/UTC 日期/时间
同 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));
?>
  • gmmktime — 取得 GMT 日期的 UNIX 时间戳

和 mktime() 彻底同样,只除了返回值是格林威治标准时的时间戳。

参数老是表示 GMT 日期,所以 is_dst 对结果没有影响。

和 mktime() 同样,参数能够从右到左依次空着,空着的参数会被设为相应的当前 GMT 值。

  • gmstrftime — 根据区域设置格式化 GMT/UTC 时间/日期
和 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";
?>
  • idate — 将本地时间日期格式化为整数

根据给定的格式字符对 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 时间戳和微秒数

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";
?>
  • mktime — 取得一个日期的 Unix 时间戳
根据给出的参数返回 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);
?>
  • strftime — 根据区域设置格式化本地时间/日期
返回值:根据指定的 timestamp 或未给出 timestamp 是使用当前本地时间, 返回 format 格式化的字符。 月份、星期名和其余与语言相关的字符串遵照 setlocale() 设置的当前区域设置。
  • strptime — 解析由 strftime 生成的日期/时间

strptime() 返回一个将 date 解析后的数组,若是出错返回 FALSE

月份和星期几的名字以及其它与语种有关的字符串对应于 setlocale()设定的当前区域(LC_TIME)。参数:

datestring

被解析的字符串(例如从 strftime() 返回的)

formatstring

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] =>
)
  • strtotime — 将任何英文文本的日期时间描述解析为 Unix 时间戳
本函数预期接受一个包含美国英语日期格式的字符串并尝试将其解析为 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);
}
?>
  • time — 返回当前的 Unix 时间戳
返回自从 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.
返回值:Returns a string.
<?php
echo timezone_version_get();
?>
 
 
 
标签:  php
相关文章
相关标签/搜索