Home > Backend Development > PHP Tutorial > PHP function library (other), php function library other_PHP tutorial

PHP function library (other), php function library other_PHP tutorial

WBOY
Release: 2016-07-13 09:44:49
Original
1546 people have browsed it

PHP function library (other), php function library other

Session function:
  • 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.
Return value: No return value for you.
  • session_cache_expire — Returns the expiration time of the current cache

session_cache_expire() returns the setting value of session.cache_expire.

When the request starts, the cache expiration time will be reset to 180 and stored in the session.cache_expire configuration item. Therefore, for each request, session_cache_expire() needs to be called before the session_start() function is called to set the cache expiration time. Parameters:

new_cache_expire

If new_cache_expire is given, use the value of new_cache_expire to set the current cache expiration time.

<p>Note: 仅在 <em>session.cache_limiter</em> 的设置值 <em>不是</em> <em>nocache</em> 的时候, 才可以设置 <code>new_cache_expire</code> 参数。</p>

Copy after login
Return value: Returns the current setting value of session.cache_expire in minutes. The default value is 180 (minutes). /* Set cache limit to "private" */
session_cache_limiter('private');
$cache_limiter = session_cache_limiter();
/* Set The cache expiration time is 30 minutes */
session_cache_expire(30);
$cache_expire = session_cache_expire();
/* Start session */
session_start();
echo "The cache limiter is now set to $cache_limiter
";
echo "The cached session pages expire after $cache_expire minutes";
?>
  • session_cache_limiter — Read/set cache limiter
session_cache_limiter() returns the name of the current cache limiter. Parameters:
cache_limiter If the cache_limiter parameter is specified, the specified value will be used as the value of the cache limiter.
可选的值
发送的响应头
public
<span>Expires:(根据 session.cache_expire 的设定计算得出)
Cache-Control: public, max-age=(根据 session.cache_expire 的设定计算得出)
Last-Modified:(会话最后保存时间)</span>
Copy after login
private_no_expire
<span>Cache-Control: private, max-age=(根据 session.cache_expire 的设定计算得出), pre-check=(根据 session.cache_expire 的设定计算得出)
Last-Modified: (会话最后保存时间)</span>
Copy after login
private
<span>Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: private, max-age=(根据 session.cache_expire 的设定计算得出), pre-check=(根据 session.cache_expire 的设定计算得出)
Last-Modified: (会话最后保存时间)</span>
Copy after login
nocache
<span>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</span>
Copy after login
Optional value<🎜>
<🎜>Value<🎜><🎜>Response header sent<🎜>
<🎜><🎜>public<🎜><🎜> <🎜>
<🎜><🎜>private_no_expire<🎜><🎜> <🎜>
<🎜><🎜>private<🎜><🎜> <🎜>
<🎜><🎜>nocache<🎜><🎜> <🎜>
Return value: Returns the name of the currently used cache limiter. /* Set cache limiter to 'private' */
session_cache_limiter('private');
$cache_limiter = session_cache_limiter();
echo " The cache limiter is now set to $cache_limiter
";
?>
  • session_commit — alias of session_write_close
  • session_decode — Decode session data
session_decode() decodes the serialized session data in the $data parameter, and uses the decoded data to fill the $_SESSION super global variable. Parameters:
data

Encoded data

Return value: TRUE on success, or FALSE on failure.
  • session_destroy — Destroy all data in a session

session_destroy() destroys all data in the current session, but will not reset the global variables associated with the current session, nor will it reset the session cookie. If you need to use session variables again, you must call the session_start() function again.

In order to completely destroy the session, such as when the user logs out, the session ID must be reset at the same time. If the session ID is transmitted through a cookie, you also need to call the setcookie() function to delete the client's session cookie.

Return value: Returns TRUE on success, or FALSE on failure. // Initialize session.
// If you want to use a session, don’t forget to call now:
session_start();
// Reset all variables in the session
$_SESSION = array();
/ / If you want to clean it more thoroughly, delete the session cookie at the same time
// Note: This will not only destroy the data in the session, but also destroy the session itself
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session
session_destroy();
?>
  • session_encode — Encode the current session data into a string
session_encode() returns a serialized string containing the encoded current session data stored in the $_SESSION superglobal variable. Parameters:
Return value: Returns the encoded content of the current session.
  • session_get_cookie_params — Get session cookie parameters
Get the session cookie parameters.
Return value: Returns an array containing the current session cookie information:
  • "lifetime" - The lifetime of the cookie, in seconds.
  • "path" - the access path of the cookie.
  • "domain" - The domain of the cookie.
  • "secure" - only sends cookies when using a secure connection.
  • "httponly" - the cookie can only be accessed through the http protocol
  • session_id — Get/set the current session ID
session_id() can be used to get/set the current session ID. Parameters:
id

If the value of the id parameter is specified, use the specified value as the session ID. The session_id() function must be called before calling the session_start() function. Different session managers have different restrictions on the characters that can be used in session IDs. For example, File Session Manager only allows the following characters in session IDs: a-z A-Z 0-9 , (comma) and - (minus sign)

<p>Note: 如果使用 cookie 方式传送会话 ID,并且指定了 <code>id</code> 参数, 在调用 session_start() 之后都会向客户端发送新的 cookie, 无论当前的会话 ID 和新指定的会话 ID 是否相同。</p>

Copy after login
返回值:session_id() 返回当前会话ID。 如果当前没有会话,则返回空字符串("")。
  • session_is_registered — 检查变量是否在会话中已经注册
检查变量是否已经在会话中注册。参数:
name

变量名称。

返回值:session_is_registered() 返回 TRUE 则表示 name 变量已经在当前会话中注册使用,否则返回 FALSE
  • session_module_name — 获取/设置会话模块名称
session_module_name() 获取或设置会话模块名称。参数: module

如果指定 module 参数,则使用 指定值作为会话模块。

返回值:返回当前所用的会话模块名称。
  • session_name — 读取/设置会话名称
session_name() 函数返回当前会话名称。 如果指定 name 参数, session_name() 函数会更新会话名称, 并返回 原来的 会话名称。参数:
name

用在 cookie 或者 URL 中的会话名称, 例如:PHPSESSID。 只能使用字母和数字作为会话名称,建议尽可能的短一些, 并且是望文知意的名字(对于启用了 cookie 警告的用户来说,方便其判断是否要允许此 cookie)。 如果指定了 name 参数, 那么当前会话也会使用指定值作为名称。

会话名称至少需要一个字母,不能全部都使用数字, 否则,每次都会生成一个新的会话 ID。

返回值:返回当前会话名称。 /* 设置会话名称为 WebsiteID */
$previous_name = session_name("WebsiteID");
echo "The previous session name was $previous_name
";
?>
  • session_regenerate_id — 使用新生成的会话 ID 更新现有会话 ID
session_regenerate_id() 在不修改当前会话中数据的前提下使用新的 ID 替换原有会话 ID。参数:
delete_old_session

是否删除原 ID 所关联的会话存储文件。

返回值:成功时返回 TRUE, 或者在失败时返回 FALSE session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
echo "Old Session: $old_sessionid
";
echo "New Session: $new_sessionid
";
print_r($_SESSION);
?>
  • session_register_shutdown — 关闭会话
将 session_write_close() 函数注册为关闭会话的函数。参数:
此函数没有参数。
返回值:没有返回值。
  • session_register — Register one or more global variables with the current session
// 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 — 读取/设置当前会话的保存路径
session_save_path() 返回当前会话的保存路径。参数:
path

指定会话数据保存的路径。 必须在调用 session_start() 函数之前调用 session_save_path() 函数。

<p>Note:</p>

Copy after login
<p>在某些操作系统上,建议使用可以高效处理 大量小尺寸文件的文件系统上的路径来保存会话数据。 例如,在 Linux 平台上,对于会话数据保存的工作而言,reiserfs 文件系统会比 ext2fs 文件系统能够提供更好的性能。</p>

Copy after login
返回值:返回保存会话数据的路径。
  • session_set_cookie_params — 设置会话 cookie 参数

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 标记。

Return value: No return value.
  • session_set_save_handler — Set user-defined session storage function
session_set_save_handler() sets user-defined session storage function. If you want to use something other than PHP's built-in session storage mechanism, you can use this function. For example, you can customize the session storage function to store session data in a database.
Return value: Returns TRUE on success, or FALSE on failure.

The OOP prototype of the session_set_save_handler() function is used here and the second parameter is used to register the shutdown function. This approach is recommended when registering an object as a session save manager.

<?php<code><?php<br />class MySessionHandler implements SessionHandlerInterface{<br /> // 在这里实现接口<br />}<br />$handler = new MySessionHandler();<br />session_set_save_handler($handler, true);<br />session_start();<br />// 现在可以使用 $_SESSION 保存以及获取数据了class MySessionHandler implements SessionHandlerInterface{
    // Implement the interface here
  • }$handler = new MySessionHandler();session_set_save_handler($handler, true); session_start();// You can now use $_SESSION to save and get data
session_start — Start a new session or reuse an existing session
TRUEsession_start() will create a new session or reuse an existing session. If a session ID is submitted via GET or POST, or using a cookie, the existing session will be reused. FALSE
  • Return value: is returned if the session is successfully started, otherwise is returned
session_status — Returns the current session status
session_status() is used to return the current session status.
  • PHP_SESSION_DISABLEDReturn value:
  • PHP_SESSION_NONE if sessions are disabled.
  • PHP_SESSION_ACTIVE if sessions are enabled, but none exists.
  • if sessions are enabled, and one exists.
session_unregister — Unregister a global variable from the current sessionname
  • session_unregister() unregisters the global variable named from the current session.
session_unset — Free all session variables
The session_unset() function frees all session variables currently registered.
  • Return value: No return value.
session_write_close — Write session data and end session
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. Return value: No return value. -------------------------------------------------- -------------------------------------------------- ------------------------------------ -------------------------------------------------- -------------------------------------------------- ------------------------------------
  • Classes/Object function:
__autoload — Attempts to load undefined class
You can enable automatic loading of classes by defining this function. Parameters: class

<🎜><🎜> <🎜><🎜>The name of the class to be loaded. <🎜><🎜> 返回值:没有返回值。
  • call_user_method_array — 调用一个用户方法,同时传递参数数组(已废弃)
  • call_user_method — 对特定对象调用用户方法(已废弃)
  • class_alias — 为一个类创建别名
基于用户定义的类 original 创建别名 alias。 这个别名类和原有的类完全相同。参数:
original

原有的类。

alias

类的别名。

autoload

如果原始类没有加载,是否使用自动加载(autoload)。

返回值:成功时返回 TRUE, 或者在失败时返回 FALSE 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_exists — 检查类是否已定义
检查指定的类是否已定义。参数:
class_name

类名。名字的匹配是大小写不敏感的。

autoload

是否默认调用 __autoload。

返回值:如果由 class_name 所指的类已经定义,此函数返回 TRUE,否则返回 FALSE class_exists() 例子:
// 使用前检查类是否存在
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>
autoload parameter 例子:
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
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"
Copy after login
Copy after login
  • get_class_methods — 返回由类的方法名组成的数组
返回由类的方法名组成的数组。参数:
class_name

类名或者对象实例。

返回值:返回由 class_name 指定的类中定义的方法名所组成的数组。如果出错,则返回 NULL
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
Copy after login
  • get_class_vars — 返回由类的默认属性组成的数组
返回由类的默认公有属性组成的关联数组,此数组的元素以 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:
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
Copy after login
get_class_vars() and scoping behaviour:
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
Copy after login
  • get_class — 返回对象的类名
返回对象实例 obj 所属类的名字。如果 obj 不是一个对象则返回 FALSE
使用 get_class():
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
Copy after login
参数:<code>object</code>

The tested object. This parameter may be omitted when inside a class.

Using get_class() in superclass:
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"
Copy after login
Copy after login
  • get_declared_classes — 返回由已定义类的名字所组成的数组
返回值:返回由当前脚本中已定义类的名字组成的数组。 print_r(get_declared_classes());
?>
<span>Array
(
    [0] => stdClass
    [1] => __PHP_Incomplete_Class
    [2] => Directory
)</span>
Copy after login
  • get_declared_interfaces — 返回一个数组包含所有已声明的接口
返回值:本函数返回一个数组,其内容是当前脚本中所有已声明的接口的名字。 print_r(get_declared_interfaces());
?>
Array
(
    [0] => Traversable
    [1] => IteratorAggregate
    [2] => Iterator
    [3] => ArrayAccess
    [4] => reflector
    [5] => RecursiveIterator
    [6] => SeekableIterator
)
Copy after login
  • get_declared_traits — 返回所有已定义的 traits 的数组
参数:此函数没有参数 返回值:返回一个数组,其值包含了所有已定义的 traits 的名称。 在失败的情况下返回 NULL
  • get_object_vars — 返回由对象属性组成的关联数组
返回由 obj 指定的对象中定义的属性组成的关联数组。
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
 )
Copy after login
  • get_parent_class — 返回对象或类的父类名

如果 obj 是对象,则返回对象实例 obj 所属类的父类名。

如果 obj 是字符串,则返回以此字符串为名的类的父类名。此功能是在 PHP 4.0.5 中增加的。

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
Copy after login
参数:<code>object</code>
Copy after login

The tested object or class name

  • interface_exists — Check whether the interface has been defined
Check whether the interface has been defined. Parameters:
interface_name

Interface name.

autoload

Whether __autoload is called by default.

Return value: This function returns interface_name when the interface given by TRUE has been defined, otherwise it returns FALSE. // Check if the interface exists before trying to use it
if (interface_exists('MyInterface')) {
class MyClass implements MyInterface{
// Methods
}
}
?>
  • is_a — Returns TRUE if the object belongs to this class or this class is the parent class of this object
If object is the class or the class is the parent class of this object. Parameters:
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() Example:
// 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";
}
?>
Use the instanceof operator in PHP 5:
if ($WF instanceof WidgetFactory) {
echo 'Yes, $WF is a WidgetFactory';
}
?>
  • is_subclass_of — Returns TRUE if this object is a subclass of this class
If the class to which the object object belongs is a subclass of class class_name, then return TRUE, otherwise return FALSE. Parameters:
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, FALSEotherwise. // 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
Copy after login
  • method_exists — 检查类的方法是否存在
检查类的方法是否存在于指定的 object中。参数:
object

对象示例或者类名。

method_name

方法名。

返回值:如果 method_name 所指的方法在 object 所指的对象类中已定义,则返回 TRUE,否则返回 FALSE method_exists() 例子:
$directory = new Directory('.');
var_dump(method_exists($directory,'read')); //bool(true)
?>
Static method_exists() 例子:
var_dump(method_exists('Directory','read')); //bool(true)
?>
  • property_exists — 检查对象或类是否具有该属性
本函数检查给出的 property 是否存在于指定的类中(以及是否能在当前范围内访问)。参数:
class

字符串形式的类名或要检查的类的一个对象

property

属性的名字

Return value: If the attribute exists, it returns TRUE, if it does not exist, it returns FALSE, if an error occurs, it returns NULL. 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();
?>
  • trait_exists — Check whether the specified trait exists
Parameters: traitname

The name of the trait to be checked

autoload

Whether to use autoload if it has not been loaded yet.

Return value: TRUE is returned if the trait exists, FALSE is returned if it does not exist. Returns NULL when an error occurs.

-------------------------------------------------- -------------------------------------------------- ------------------------------------ -------------------------------------------------- -------------------------------------------------- ------------------------------------ MySQL function:
  • mysql_affected_rows — Get the number of record rows affected by the previous MySQL operation
Gets the number of record rows affected by the latest INSERT, UPDATE or DELETE query associated with link_identifier. Parameters:
link_identifier

MySQL connection. If no connection ID is specified, the connection most recently opened by mysql_connect() is used. If the connection is not found, it will try to create it by calling mysql_connect() without parameters. If a connection is not found or cannot be established, a E_WARNING level error will be generated.

mysql_affected_rows() 例子:
$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
Copy after login
使用事务处理的 mysql_affected_rows() 例子:
$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
Copy after login
  • mysql_client_encoding — 返回字符集的名称
从 MySQL 中取得 character_set 变量的值。参数:
link_identifier

MySQL 连接。如不指定连接标识,则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接,会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接,则会生成 E_WARNING 级别的错误。

返回值:返回当前连接的默认字符集名称。 $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
Copy after login
  • mysql_close — 关闭 MySQL 连接
mysql_close() 关闭指定的连接标识所关联的到 MySQL 服务器的非持久连接。如果没有指定 link_identifier,则关闭上一个打开的连接。参数:
link_identifier

MySQL 连接. 如果该连接标识符未给出, 将使用最近一次mysql_connect()建立的连接. 如果没有找到可使用的连接, 将产生一个 E_WARNING 错误.

返回值:成功时返回 TRUE, 或者在失败时返回 FALSE $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>
Connected successfully
Copy after login
  • mysql_connect — 打开一个到 MySQL 服务器的连接
打开或重复使用一个到 MySQL 服务器的连接。参数:
server

MySQL 服务器。可以包括端口号,例如 "hostname:port",或者到本地套接字的路径,例如对于 localhost 的 ":/path/to/socket"。

如果 PHP 指令 mysql.default_host 未定义(默认情况),则默认值是 'localhost:3306'。 在 SQL 安全模式 时,参数被忽略,总是使用 'localhost:3306'。

username

用户名。默认值由 mysql.default_user 定义。 在 SQL 安全模式 时,参数被忽略,总是使用服务器进程所有者的用户名。

password

Password. The default value is defined by mysql.default_password. In SQL safe mode, the parameter is ignored and an empty password is always used.

new_link

If mysql_connect() is called a second time with the same parameters, a new connection will not be established, but the already opened connection ID will be returned. Parameter new_link changes this behavior and makes mysql_connect() always open a new connection, even when mysql_connect() has been called previously with the same parameters.

client_flags The

client_flags parameter can be a combination of the following constants: MYSQL_CLIENT_SSL, MYSQL_CLIENT_COMPRESS, MYSQL_CLIENT_IGNORE_SPACE or MYSQL_CLIENT_INTERACTIVE. See MySQL Client Constants for further information.

Return value: Returns a MySQL connection ID if successful, or FALSE on failure. mysql_connect() example: $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error() );
}
echo 'Connected successfully';
mysql_close($link);
?> mysql_connect() example: use hostname:port syntax: // 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() example: use ":/path/to/socket" syntax: // 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 — Create a new MySQL database
mysql_create_db() attempts to create a new database on the server associated with the specified connection ID. Parameters:
database_name

The name of the database to be created.

link_identifier

MySQL connection. If no connection ID is specified, the connection most recently opened by mysql_connect() is used. If the connection is not found, it will try to create it by calling mysql_connect() without parameters. If a connection is not found or cannot be established, a E_WARNING level error will be generated.

返回值:成功时返回 TRUE, 或者在失败时返回 FALSE $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
Copy after login
  • mysql_data_seek — 移动内部结果的指针
mysql_data_seek() 将指定的结果标识所关联的 MySQL 结果内部的行指针移动到指定的行号。接着调用mysql_fetch_row() 将返回那一行。参数:
result

resource 型的结果集。此结果集来自对 mysql_query() 的调用。

row_number

想要设定的新的结果集指针的行数。

返回值:成功时返回 TRUE, 或者在失败时返回 FALSE $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'] . "
\n";
}
mysql_free_result($result);
?>
  • mysql_db_name — 取得结果数据
取得 mysql_list_dbs() 调用所返回的数据库名。参数:
result

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

row

结果集中的行号。

field

字段名。

返回值:如果成功则返回数据库名,失败返回 FALSE。如果返回了 FALSE,用 mysql_error() 来判断错误的种类。 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_db_query — 发送一条 MySQL 查询

根据查询结果返回一个正的 MySQL 结果资源号,出错时返回 FALSE。本函数会对 INSERT/UPDATE/DELETE 查询返回TRUE/FALSE 来指示成功或失败。

mysql_db_query() 选择一个数据库并在其上执行查询。如果没有提供可选的连接标识,本函数会去找一个到 MySQL 服务器的已打开的连接,如果找不到已打开连接则会尝试无参数调用 mysql_connect() 来建立一个。

注意此函数不会切换回先前连接到的数据库。换句话说,不能用此函数临时在另一个数据库上执行 sql 查询,只能手工切换回来。强烈建议用户在 sql 查询中使用 database.table 语法来替代此函数。

  • mysql_drop_db — 丢弃(删除)一个 MySQL 数据库

mysql_drop_db() 尝试丢弃(删除)指定连接标识所关联的服务器上的一整个数据库。

成功时返回 TRUE, 或者在失败时返回 FALSE

为向下兼容也可以用 mysql_dropdb(),但反对这样做。

<p>不提倡使用 mysql_drop_db() 函数最好用 mysql_query() 提交一条 <em>SQL DROP DATABASE</em> 语句来替代。</p>

Copy after login
<p> </p>

Copy after login
database_name    The name of the database that will be deleted.link_identifier    MySQL 连接。如不指定连接标识,则使用由 mysql_connect() 最近打开的连接。如果没有找到该连接,会尝试不带参数调用 mysql_connect() 来创建。如没有找到连接或无法建立连接,则会生成 E_WARNING 级别的错误。返回值:成功时返回 TRUE, 或者在失败时返回 FALSE $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 函数之前检查它的值。

    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&nb
Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template