EZSQL 中文手册

来源:互联网 发布:范伟 金马奖 知乎 编辑:程序博客网 时间:2024/04/30 02:33

ezSQL Overview download ez_sql.zip 
To email the creator: justin_at_jvmultimedia_dot_com

ezsql 概况

· ezSQL is a widget that makes it very fast and easy for you to use database(s) within your PHP scripts ( mySQL / Oracle8/9 / InterBase/FireBird / PostgreSQL / MS-SQL / SQLite / SQLite c++).

Ezsql是一个是你在PHP中能够更简便使用数据库( mySQL / Oracle8/9 / InterBase/FireBird / PostgreSQL / MS-SQL / SQLite / SQLite c++).的小工具。

· It is one php file that you include at the top of your script. Then, instead of using standard php database functions listed in the php manual, you use a much smaller (and easier) set of ezSQL functions.

你只需要将一个小小的PHP文件包含到你的脚本中,就可以替代你从手册中查到的PHP标准数据库函数,你将使用的是更加小巧和简单的ezsql函数。

· It automatically caches query results and allows you to use easy to understand functions to manipulate and extract them without causing extra server overhead

它可以自动缓存查询的结果并允许使用容易理解的函数去操作和提取其中的数据,而且不需要额外的服务器开销。

·It has excellent debug functions making it lightning-fast to see what’s going on in your SQL code

它有着优秀的调试函数可以让你立刻看到你的sql代码的运行结果。

·Most ezSQL functions can return results as Objects, Associative Arrays, or Numerical Arrays

大多数的ezsql函数可以返回对象或者关联数组或者数值数组。

·It can dramatically decrease development time and in most cases will streamline your code and make things run faster as well as making it very easy to debug and optimise your database queries.

它可以大幅减少开发所需要的时间,并且在多数情况下可以精简你的代码并使程序运行的更加快速,你还可以非常简便的调试和优化你的查询。

· It is a small class and will not add very much overhead to your website.

这是一个小类,并不会对你的网站造成很大的系统开销。

Note: It is assumed that you are familiar with PHP, basic Database concepts and basic SQL constructs. Even if you are a complete beginner ezSQL can help you once you have read and understood this tutorial.

本文假定你是一个熟悉PHP并且对数据库和SQL语法有着基本认识的人,如果你是一个完全想新手,你可以通过阅读我们教程获得帮助。

Quick Examples..Note: In all these examples no other code is required other than including ez_sql.php简单的例子:在这些例子中,我们不需要为ezsql输入额外的代码----------------------------------------------------Example 1---------------------------------------------------// Select multiple records from the database and print them out..//取出复数的行并输出结果$users = $db->get_results("SELECT name, email FROM users");foreach ( $users as $user ){// Access data using object syntax//用对象的方式取得结果echo $user->name;echo $user->email;}----------------------------------------------------Example 2----------------------------------------------------// Get one row from the database and print it out..//取出一行结果并输出$user = $db->get_row("SELECT name,email FROM users WHERE id = 2");echo $user->name;echo $user->email;----------------------------------------------------Example 3----------------------------------------------------// Get one variable from the database and print it out..//从数据库取出一个变量并输出$var = $db->get_var("SELECT count(*) FROM users");echo $var;----------------------------------------------------Example 4----------------------------------------------------// Insert into the database//向数据库插入数据$db->query("INSERT INTO users (id, name, email) VALUES (NULL,'justin','jv@foo.com')");----------------------------------------------------Example 5----------------------------------------------------// Update the database//更新数据$db->query("UPDATE users SET name = 'Justin' WHERE id = 2)");--------------------------------------------------Example 6----------------------------------------------------// Display last query and all associated results//输出之前的查询及其关联的结果$db->debug();----------------------------------------------------Example 7----------------------------------------------------// Display the structure and contents of any result(s) .. or any variable//输出所有取得的结果及变量的结构和内容$results = $db->get_results("SELECT name, email FROM users");$db->vardump($results);----------------------------------------------------Example 8----------------------------------------------------// Get 'one column' (based on column index) and print it out..//取出一列(索引中存在的)并输出结果。$names = $db->get_col("SELECT name,email FROM users",0)foreach ( $names as $name ){echo $name;}----------------------------------------------------Example 9----------------------------------------------------// Same as above ‘but quicker’与上一个例子作用相同,但是更快foreach ( $db->get_col("SELECT name,email FROM users",0) as $name ){echo $name;}----------------------------------------------------Example 10----------------------------------------------------// Map out the full schema of any given database and print it out..//显示任何被给出的数据库的结构并输出$db->select("my_database");foreach ( $db->get_col("SHOW TABLES",0) as $table_name ){$db->debug();$db->get_results("DESC $table_name");}$db->debug();
Introduction介绍When working with databases most of the time you will want to do one of four types of basic operations.当进行数据库操作的时候,你可能会进行以下四种类型的基本操作。1.      Perform a query such as Insert or Update (without results)1.执行一个查询进行插入或更新操作(不需要返回结果)2.      Get a single variable from the database2.从数据库中获取一个变量3.      Get a single row from the database3.从数据库中取出一行4.      Get a list of results from the database4.从数据库中得到一个结果集ezSQL wraps up these four basic actions into four very easy to use functions.EZsql将以上四种操作封装到四个非常简单的函数中去:bool     $db->query(query)返回布尔值:$db->query(query)var       $db->get_var(query)返回变量 $db->get_var(query)mixed $db->get_row(query)输出布尔值和变量 $db->get_row(query)mixed $db->get_results(query)输出布尔值和变量 $db->get_results(query)With ezSQL these four functions are all you will need 99.9% of the time. Of course there are also some other useful functions but we will get into those later.你在大多数情况下所需要的就是ezsql的这四个函数,当然,我们还有许多有用的函数可以使用,我们将在以后介绍他们。Important Note: If you use ezSQL inside a function you write, you will need to put global $db; at the top.注意:如果你需要使用ezsql的函数,你需要首先将它放到global中并初始化。

Installation

安装

To install ezSQL download, unzip and install the contents of ez_sql.zip into the same directory within your web server.

在安装ezsql之前,你需要从网上下载ez_sql.zip到所需要使用这个类的服务器路径下。

Put the following at the top of your script:

在代码的开始添加如下内容

            // Include ezSQL core

//包含ezsql的代码核心

           include_once "ez_sql_core.php";

            // Include ezSQL database specific component (in this case mySQL)

//包含对应的数据库组件(比如mysql

            include_once "ez_sql_mysql.php";

//包含ez_sql_mysql.php

            // Initialise database object and establish a connection

//初始化数据库对象并创建连接

            // at the same time - db_user / db_password / db_name / db_host

//同时需要输入以下变量 (数据库用户、密码、数据库名、主机名称(或IP))

            $db = new ezSQL_mysql('db_user','db_password','db_name','db_host');

Note: On most systems localhost will be fine for the dbhost value. If you are unsure about any of the above settings you should contact your provider or look through your providers documentation.

注意:在大多数的系统中,localhost这个主机名称是最直接有效的名字,如果你不确定你所需要设置的参数,请咨询服务提供商或查询提供商的文档。

If you are running on a local machine and have just installed mySQL for the first time, you can probably leave the user name and password empty ( i.e. = “”) until you set up a mySQL user account.

如果你是第一次在机器上安装ezsql,在你配置好一个可用的mysql账号之前。请留空用户名和密码。


Running the ezSQL demo 
运行ezSQL演示

Once you have installed ezSQL as described above you can see it in action by running ez_demo.php via

your web browser. To do this simply go to.. 
当你已经安装好ezsql之后,你可以运行ez_demo.php来看它是如何工作的,输入此路径以运行该文件:
http://yourserver.com/install_path/mysql/demo.php 
http://你的域名/安装路径/mysql/demo.php
If you are running your web server on your local machine this will be..
如果你是在本地调试该程序,则输入此路径
http://127.0.0.1/install_path/mysql/demo.php 
http://127.0.0.1/安装路径/mysql/demo.php
What the demo does… is use ezSQL functions to map out the table structure of your database (i.e the

database you specified at the top of ez_sql.php). You will be surprised how little code is required

to do this when using ezSQL. I have included it here so you can get a quick feel for the compactness

and speed of ezSQL. 
这个演示文件能为我们做什么呢?他可以通过ezsql的内置函数将你在文件开始所选定的数据库结构输出出来,你可能会

被他简短的代码所震惊,我将这段代码放在这里,你可以通过阅读它认识ezsql的简洁和效率

<?php
            // Include ezSQL core
//包含ezsql的数据核心
             include_once "ez_sql_core.php";
             // Include ezSQL database specific component
//包含对应数据库的操作文件
             include_once "ez_sql_mysql.php";
             // Initialise database object and establish a connection
//初始数据库对象并创建连接
             // at the same time - db_user / db_password / db_name / db_host

             $db = new ezSQL_mysql('db_user','db_password','db_name','db_host');
            $my_tables = $db->get_results("SHOW TABLES",ARRAY_N);
            $db->debug();
            foreach ( $my_tables as $table )
            {
                        $db->get_results("DESC $table[0]");

                        $db->debug();
            }       
?>


The ezSQL demo explained
对EZSQL演示文件的解释 
<?php
This is the standard way to start php executing within your web page.
这是执行PHP语言的开始标记 
include_once “ez_sql.php”;
This is how you include ezSQL in your script. Normally you include it at the top of your script and from that point forward you have access to any ezSQL function.
这就是如何在PHP文件中包含ezsql的方法,一般都在代码的开始,然后之后才能使用ezsql的函数。 
$my_tables = $db->get_results(“SHOW TABLES”,ARRAY_N);
get_results() is how you get ‘a list’ of things from the database using ezSQL. The list is returned as an array. In this case the std mySQL command of ‘SHOW TABLES’ is called and the resulting list is stored in a newly created array $my_tables. When using $db->get_results(), if there are any results, they are always returned as multi-dimensional array. The first dimension is a numbered index. Each of the numbered indexes is either an object, associative array or numerical array containing all the values for ‘one row’.
get_results()是ezsql的一个从数据库中输出一个集合的函数,输出的集合是一个数组,在这里,调用了标准的mysql函数“show table”然后将结果集存储在一个新的数组里面,当使用$db->get_results(),的时候,它可以将取得的结果存储到一个多维数组中,第一维的数组中存储的是索引,每一个索引指向一个对象,关联数组或数值数组并将所有值存储在一行中。

For example using the switch ARRAY_A would produce an array that looked something like this.
例如,使用开关变量ARRAY_A可以输出一个这样的数组 
$users = $db->get_results(“SELECT id,name FROM users”,ARRAY_A);
$users[0] = array (“id” => “1”, “name” => “Amy”);
$users[1] = array (“id” => “2”, “name” => “Tyson”);
If you wanted a numerical array use the switch ARRAY_N.

如果你需要一个数值数组,你可以使用开关变量ARRAY_N.
$users = $db->get_results(“SELECT id,name FROM users”,ARRAY_N);
$users[0] = array (0 => “1”, 1 => “Amy”);
$users[1] = array (0 => “2”, 1 => “Tyson”);

If you wanted an object (which is the default option) you don’t need a switch..
如果你需要输出一个对象(默认输出),你可以不使用开关变量。 
$users = $db->get_results(“SELECT id,name FROM users”);
$users[0]->id = “1”;
$users[0]->name = “Amy”;
$users[1]->id = “2”;
$users[1]->name = “Tyson”;

Results returned as an object make it very easy to work with database results using the numerous array functions that php offers. For example, to loop through results returned as an object all one needs to do is..
从数据库中返回数值数组的对象对于PHP的处理非常简单,例如循环输出一个对象结果只需要这么做: 
$users = $db->get_results(“SELECT id,name FROM users”);
foreach( $users as $user )
echo $user->id;
echo $user->name;

If you are 100% sure that there will be results you can skip a step and do this..
如果你确定有输出结果你可以跳过一步: 
foreach( $db->get_results(“SELECT id,name FROM users”) as $user )
echo $user->id;
echo $user->name;

If you don’t know whether there will be results or not you can do this..
如果你不能确定有没有返回结果你可以这么写: 
If ( $users= $db->get_results(“SELECT id,name FROM users”) )
foreach( $users as $user )
echo $user->id;
echo $user->name;
else
echo “No results”;
$db->debug();

This function prints the most recently called sql query along with a well formatted table containing any results that the query generated (if any) and the column info.
这个函数可以输出最近的一个查询并包含一个已经排好版的表格包含有该查询所产生的所有结果和列的信息。 
foreach ( $my_tables as $table)
This is the standard way to easily loop through an array in php. In this case the array $my_tables was created with the ezSQL command $db->get_results(“SHOW TABLES”,ARRAY_N). Because of the ARRAY_N switch the results are returned as a numerical array.
The resulting array will look something like..
这是PHP中使用的一个非常简单的遍历数组的方法,在这个过程中,数组$my_tables将通过运行ezsql的命令$db->get_results(“SHOW TABLES”,ARRAY_N)创建,其中,开关变量ARRAY_N将使得该返回结果为一个数值数组。
输出的结果将是这样的:
 
$my_tables[0] = array (0 => “users”);
$my_tables[1] = array (0 => “products”);
$my_tables[2] = array (0 => “guestbook”);

The foreach is looping through each primary element of $my_tables[n] which are in turn numerical arrays, with the format like so..
这个foreach的循环将遍历所有在$my_tables[n]中的元素并将他们转换到数值数组中,结构如下: 
array(0 => “value”, 1 => “value”, etc.);
Thus, during the foreach loop of $my_tables we have access to the value of the first column like so:
从而通过遍历$my_tables我们可以取得所有的值: 
foreach ($my_tables as $table)
echo $table[0];

If we did the same thing using an associative array it might look like this..
如果我们生成一个关联数组将是这个样子: 
$users = $db->get_results(“SELECT id,name FROM users”,ARRAY_A);
foreach ( $users as $user )
echo $user[‘id’];
echo $user[‘name’];

But if there were no results foreach might generate a warning. So a safer way to do the above is..
但是如果我们没有返回值的话,遍历将返回一个警告,所以,安全起见,我们应当这么写: 
if ( $users = $db->get_results(“SELECT id,name FROM users”,ARRAY_A))
foreach ( $users as $user )
echo $user[‘id’];
echo $user[‘name’];
else
echo “No Users”:

This works because if no results are returned then get_results() returns false.
当没有任何结果的时候,将返回false; 
$db->get_results(“DESC $table[0]”);
This database query is nested within the foreach loop. Note that we are using the results of the previous call to make a new call. Traditionally you would have to be concerned about using different db_resource identifiers in a case like this but ezSQL takes care of that for you, making it very easy to nest database queries.
在这个查询中我们嵌套了一个遍历循环,注意我们将前一个函数用到了新的函数中,从习惯上来说,你可能需要使用不同的数据库资源标示,但是在ezsql中,我们可以使这个过程变的简单,以嵌套在查询中。 
You may be wondering why I have used a numerical array output and not object or associative array. 
你可能会对我为什么使用数值数组来输出结果而不是通过对象或关联数组呢? 
The reason is because in this case I do not know what the name of the first column will be. So I can make sure that I can always get its value by using numerical array output and targeting the first column by element [0].
原因是,我并不能确定所取得结果的第一列的名字,而我能够确定的是通过数值数组的话,我可以将结果以元素[0]将第一列输出出来 
FYI: The SQL command SHOW TABLES always names the first column a different value depending on the database being used. If the database was named users the column would be called Tables_in_users if the database was called customers the column would be called Tables_in_customers and so on.
参考:sql命令show tables可以依靠数据库中使用的名字命名第一个列。如果你的数据库命名为users,这个列将被命名为Tables_in_users,你的数据库命名为customers,这个列将被命名为Tables_in_ customers等。 
$db->debug();
This function will always print the last query and its results (if any) to the browser. In this case 
it will be for the above query.. 
这个函数将输出上一个查询的所有结果,在这里将输出上面的查询结果。 
$db->get_results(“DESC $table[0]”);

You may have noticed that the above get_results function is not assigning a value. (i.e. $var = val). This is because even if you do not assign the output value of any ezSQL function the query results are always stored and made ready for any ezSQL function to use. In this case $db->debug() is displaying the stored results. Then, by calling any ezSQL function using a null query you will be accessing the stored results from the last query. Here is a more detailed example. 
Users Table..
你可能会注意到,get_results这个函数并没有分配值,(比如一个变量)这是因为如果你不分配ezsql函数的查询结果的话,这个结果将被缓存并可以被任何的ezsql的函数所调用,比如$db->debug()可以显示出这个被存储的结果,然后使用空值访问任何一个ezsql的查询的话将可以访问到之前所存储的查询结果,下面是一个更直接的结果 
amy, 
amy@foo.com
tyson, tyson@foo.com
// Any ezSQL function will store query results..
//结果将被缓存 
$users = $db->get_results(“SELECT name,email FROM users”);
// This gets a variable from the above results (offset by $x = 1, $y = 1).
/这里将从上一个结果中获取变量。 
echo $db->get_var(null,1,1);
// Note: Because a null query is passed to get_var it uses results from the previous query.
//这里将把空查询传递给get_var然后取出之前的查询结果。 
Output: 
tyson@foo.com 
This closes the foreach loop
//关闭循环
?>
This stops php executing code
PHP代码关闭


ezSQL functions
ezsql函数
$db->get_results -- get multiple row result set from the database (or previously cached results)
从数据库(或之前缓存的结果)中取出复数的行
$db->get_row -- get one row from the database (or previously cached results)
从数据库(或之前缓存的结果)中取出一行
$db->get_col -- get one column from query (or previously cached results) based on column offset 
从数据库(或之前缓存的结果)中取出预先设定的一列 
$db->get_var -- get one variable, from one row, from the database (or previously cached results)
从数据库(或之前缓存的结果以及一行)一个变量 
$db->query -- send a query to the database (and if any results, cache them)
对数据库进行一次查询并缓存任何返回结果
$db->debug -- print last sql query and returned results (if any)
输出之前的查询的结果并返回其结果
$db->vardump -- print the contents and structure of any variable
返回任何指定变量的结构和内容
$db->select -- select a new database to work with
选定一个新数据库供接下来的使用
$db->get_col_info -- get information about one or all columns such as column name or type
获得一列的信息(例如:名字和类型)
$db->hide_errors -- turn ezSQL error output to browser off
关闭ezsql的错误输出
$db->show_errors -- turn ezSQL error output to browser on
打开ezsql的错误输出
$db->escape -- Format a string correctly to stop accidental mal formed queries under all PHP conditions
格式化任何非标准PHP查询
$db = new db -- Initiate new db object.
初始化数据库对象

ezSQL variables
ezsql的变量

$db->num_rows – Number of rows that were returned (by the database) for the last query (if any)
输出之前对数据库进行查询的影响行数。
$db->insert_id -- ID generated from the AUTO_INCRIMENT of the previous INSERT operation (if any)
从之前的insert查询中获取所生成的自增ID
$db->rows_affected -- Number of rows affected (in the database) by the last INSERT, UPDATE or DELETE (if any)
获取之前所生效的INSERT,UPDATE,以及DELETE所影响的行数。
$db->num_queries -- Keeps track of exactly how many 'real' (not cached) queries were executed during the lifetime of the current script
对当前代码所生效的查询进行追踪
$db->debug_all – If set to true (i.e. $db->debug_all = true;) Then it will print out ALL queries and ALL results of your script.
如果将这个变量设置为true,它将输出代码中所有的查询和结果。
$db->cache_dir – Path to mySQL caching dir.
设置mysql结果的缓存路径
$db->cache_queries – Boolean flag (see mysql/disk_cache_example.php)
布尔型标示,(详见mysql/disk_cache_example.php)
$db->cache_inserts – Boolean flag (see mysql/disk_cache_example.php)
布尔型标示,(详见mysql/disk_cache_example.php)
$db->use_disk_cache – Boolean flag (see mysql/disk_cache_example.php)
布尔型标示,(详见mysql/disk_cache_example.php)
$db->cache_timeout – Number in hours (see mysql/disk_cache_example.php)
以小时为单位计算 (详见mysql/disk_cache_example.php)


命令详解

$db = new db

-------------------------------------------------------------

$db = new db -- Initiate new db object. Connect to a database server. Select a database.

初始化一个数据库对象,链接数据库服务器,选择数据库

Description

说明

$db = new db(string username, string password, string database name, string database host)

$db = new db(字符串用户名字符串密码字符串数据库名称字符串主机名)

Does three things. (1) Initiates a new db object. (2) Connects to a database server. (3) Selects a database. You can also re-submit this command if you would like to initiate a second db object. This is interesting because you can run two concurrent database connections at the same time. You can even connect to two different servers at the same time if you want to.

这个函数完成3件事:1.初始化一个数据库对象2.链接数据库服务器3.选择数据库。你可以再次初始化这个函数为新的数据库对象,这意味着你可以同时进行两个并发的数据库连接,另外,你也可以在同时连接两个完全不同的数据服务器。

Note: For the sake of efficiency it is recommended that you only run one instance of the db object and use $db->select to switch between different databases on the same server connection.

建议:为了提高效率,建议初始化一个数据库对象然后使用$db->select对一个服务器的两个数据库分别进行操作。

Example

例子

// Initiate new database object..

初始化数据库对象

$db2 = new db(”user_name”, ”user_password”, ”database_name”, “database_host”);

// Perform some kind of query..

使用查询

$other_db_tables = $db2->get_results(“SHOW TABLES”);

// You can still query the database you were already connected to..

你可以对将要连接的数据库进行查询

$existing_connection_tables = $db->get_results(“SHOW TABLES”);

// Print the results from both of these queries..

输出之前的所有查询结果

$db->debug();

$db2->debug();


$db->select

-------------------------------------------------------------

$db->select -- select a new database to work with

选择一个将使用的数据库

Description

说明

bool $db->select(string database name)

布尔型 $db->select(字符串数据库名称)

$db->select() selects a new database to work with using the current database connection as created with $db = new db.

使用当前的数据库连接设置,选择一个将使用的数据库

Example

例子

// Get a users name from the user’s database (as initiated with $db = new db)..

//从用户的其他数据库中取出一个用户的名字(需要初始化数据库)

$user_name = $db->get_var(“SELECT name FROM users WHERE id = 22”) ;

// Select the database stats..

//选择stats这个数据库(注意,切换数据库了)

$db->select(“stats”);

// Get a users name from the user’s database..

//从用户的其他数据库中取出一个用户的名字

$total_hours = $db->get_var(“SELECT sum(time_logged_in) FROM user_stats WHERE user = ‘$user_name’”) ;

// Re-select the ‘users’ database to continue working as normal..

//重新返回当前数据库并继续当前的工作

$db->select(“users”);


$db->query

-------------------------------------------------------------

$db->query -- send a query to the database (and if any results, cache them)

对数据库进行一次查询并缓存任何返回结果

Description

说明

bool $db->query(string query)

布尔型 $db->query(字符串 查询)

$db->query() sends a query to the currently selected database. It should be noted that you can send any type of query to the database using this command. If there are any results generated they will be stored and can be accessed by any ezSQL function as long as you use a null query. If there are results returned the function will return true if no results the return will be false

$db->query()向当前选择的数据库执行一个查询,要注意的是,你可以通过这个命令执行任何查询命令,任何的返回结果都将被缓存并可以在你执行一个空查询之前所调用,如果有返回结果,该函数的值为true,若无结果,返回false

Example 1

例子1

// Insert a new user into the database..

向数据库中加入新用户

$db->query(“INSERT INTO users (id,name) VALUES (1,’Amy’)”) ;

Example 2

例子2

// Update user into the database..

更新数据库中的用户

$db->query(“UPDATE users SET name = ‘Tyson’ WHERE id = 1”) ;

Example 3

例子三

// Query to get full user list..

查询整个用户列表

$db->query(“SELECT name,email FROM users”) ;

// Get the second row from the cached results by using a null query..

使用空查询取出之前缓存的结果的第二行

$user_details = $db->get_row(null, OBJECT,1);

// Display the contents and structure of the variable $user_details..

显示出变量$user_details的结构和内容

$db->vardump($user_details);


$db->get_var

-------------------------------------------------------------

$db->get_var -- get one variable, from one row, from the database (or previously cached results)

从数据库的一行(或之前缓存的结果)中取得一个变量

Description

说明

var $db->get_var(string query / null [,int column offset[, int row offset])

返回变量 $db->get_var(字符串查询/空值)

$db->get_var() gets one single variable from the database or previously cached results. This function is very useful for evaluating query results within logic statements such as if or switch. If the query generates more than one row the first row will always be used by default. If the query generates more than one column the leftmost column will always be used by default. Even so, the full results set will be available within the array $db->last_results should you wish to use them.

$db->get_var()从数据库的一行(或之前缓存的结果)中取得一个变量,这个函数配合switchif来判断查询结果是非常有效的,如果查询返回了复数的行,那么将默认返回第一行,如果返回了复数的列,那么将默认返回最左边的列,另外,该查询的结果将可以被$db->last_results以数组的方式取得

Example 1

例子1

// Get total number of users from the database..

//取出数据库中的用户总数

$num_users = $db->get_var(“SELECT count(*) FROM users”) ;

Example 2

例子2

// Get a users email from the second row of results (note: col 1, row 1 [starts at 0])..

//从第二行中取出一个用户的email地址(说明,第一行,第一列,默认起始值为0

$user_email = $db->get_var(“SELECT name, email FROM users”,1,1) ;

// Get the full second row from the cached results (row = 1 [starts at 0])..

//取出之前缓存的整个第二行

$user = $db->get_row(null,OBJECT,1);

// Both are the same value..

//结果一样

echo $user_email;

echo $user->email;

Example 3

例子3

// Find out how many users there are called Amy..

//找出有多少个名叫amy的用户

if ( $n = $db->get_var(“SELECT count(*) FROM users WHERE name = ‘Amy’”) )

{

// If there are users then the if clause will evaluate to true. This is useful because

// we can extract a value from the DB and test it at the same time.

//如果有用户被返回的话,将输出一个true这在判断中是非常有利的,因为我们可以在这个时候对取出的值进行判断。

echo “There are $n users called Amy!”;

}

else

{

// If there are no users then the if will evaluate to false..

//如果没有用户返回,这里将判断为false

echo “There are no users called Amy.”;

}

Example 4

例子4

// Match a password from a submitted from a form with a password stored in the DB

与数据库中存储的密码比对一个从submit事件中得到的密码,

if ( $pwd_from_form == $db->get_var(“SELECT pwd FROM users WHERE name = ‘$name_from_form’”) )

{

// Once again we have extracted and evaluated a result at the same time..

//又一次我们在取出数据的同时进行了比较

echo “Congratulations you have logged in.”;

}

else

{

// If has evaluated to false..

//如果判断为false

echo “Bad password or Bad user ID”;

}


$db->get_row

--------------------------------------------------------------------------------------

$db->get_row -- get one row from the database (or previously cached results)

从数据库(或之前缓存的结果)中取出一行

Description

说明

object $db->get_ row(string query / null [, OBJECT / ARRAY_A / ARRAY_N [, int row offset]])

返回对象$db->get_ row(字符串查询/空值(OBJECT / ARRAY_A / ARRAY_N三个可选参数)

$db->get_row() gets a single row from the database or cached results. If the query returns more than one row and no row offset is supplied the first row within the results set will be returned by default. Even so, the full results will be cached should you wish to use them with another ezSQL query.

$db->get_row()从数据库(或之前缓存的结果)中取出一行,如果查询得到的结果多于一行,将默认输出第一行,同时该查询的结果将被缓存以备其他 ezsql 查询使用。

Example 1

例子1

// Get a users name and email from the database and extract it into an object called user..

从数据库中获取用户名和邮件地址,并将它放入一个叫USER的对象。

$user = $db->get_row(“SELECT name,email FROM users WHERE id = 22”) ;

// Output the values..

输出值

echo “$user->name has the email of $user->email”;

Output:

输出值

Amy has the email of amy@foo.com

Example 2

例子2

// Get users name and date joined as associative array

从数据库中取出用户名和时间并放入关联数组

// (Note: we must specify the row offset index in order to use the third argument)

注意,我们需要设置行的索引值以使用该参数

$user = $db->get_row(“SELECT name, UNIX_TIMESTAMP(my_date_joined) as date_joined FROM users WHERE id = 22”,ARRAY_A) ;

// Note how the unix_timestamp command is used with as this will ensure that the resulting data will be easily

注意他可以非常简单的使用uxix时间戳确保结果

// accessible via the created object or associative array. In this case $user[‘date_joined’] (object would be $user->date_joined)

创建可访问的对象或关联数组,在这个例子中,$user[‘date_joined’]是对象would be $user->date_joined。

echo $user[‘name’] . “ joined us on ” . date(“m/d/y”,$user[‘date_joined’]);

Output:

输出

Amy joined us on 05/02/01

Example 3

例子三

// Get second row of cached results.

从缓存中取出第二行

$user = $db->get_row(null,OBJECT,1) ;

// Note: Row offset starts at 0

注意:默认值为0

echo “$user->name joined us on ” . date(“m/d/y”,$user->date_joined);

Output:

输出

Tyson joined us on 05/02/02

Example 4

结果4

// Get one row as a numerical array..

以数值数组方式取值

$user = $db->get_row(“SELECT name,email,address FROM users WHERE id = 1”,ARRAY_N);

// Output the results as a table..

以表的方式输出结果

echo “<table>”;

for ( $i=1; $i <= count($user); $i++ )

{

echo “<tr><td>$i</td><td>$user[$I]</td></tr>”;

}

echo “</table>”;

Output:

1        amy

2        amy@foo.com

3        123 Foo Road


$db->get_results

-------------------------------------------------------------------------------------------------------------------------------

$db->get_results – get multiple row result set from the database (or previously cached results)

从数据库(或之前缓存的结果)中取出复数的行

Description

说明             

array $db->get_results(string query / null [, OBJECT / ARRAY_A / ARRAY_N ] )

返回数组(对象),可选参数OBJECT / ARRAY_A / ARRAY_N

$db->get_row() gets multiple rows of results from the database based on query and returns them as a multi dimensional array. Each element of the array contains one row of results and can be specified to be either an object, associative array or numerical array. If no results are found then the function returns false enabling you to use the function within logic statements such as if.

$db->get_row()用查询从数据库中取出复数的行并转存为多维数组,数组中的每个元素包含一行结果,且可以以对象,数值数组,关联数组的方式调用,如果没有查询结果,该函数可以返回false供逻辑判断。

Example 1 – Return results as objects (default)

例子1,以对象方式返回结果

Returning results as an object is the quickest way to get and display results. It is also useful that you are able to put $object->var syntax directly inside print statements without having to worry about causing php parsing errors.

以对象方式返回查询结果是最快的取得结果的方法,同时他也可以用$object->var这个方法非常快速的取到结果而且不用担心PHP的解析错误。

// Extract results into the array $users

将结果放入数组$users

(and evaluate if there are any results at the same time)..

同时判断其中的任何结果

if ( $users = $db->get_results(“SELECT name, email FROM users”) )

{

// Loop through the resulting array on the index $users[n]

通过索引$users[n]循环整个数组

foreach ( $users as $user )

{

// Access data using column names as associative array keys

依靠列名取得数据并保存到关联数组的键值中

echo “$user->name - $user->email<br>”;

}

}

else

{

// If no users were found then if evaluates to false..

如果没有用户返回则输出false

    echo “No users found.”;

}

Output:

Amy - amy@hotmail.com     

Tyson - tyson@hotmail.com

Example 2 – Return results as associative array

例子2,以关联数组方式返回结果

Returning results as an associative array is useful if you would like dynamic access to column names.

以关联数组方式返回数据有助于你动态获取结果。

Here is an example.

这里是例子

// Extract results into the array $dogs

将数据存入数组$dogs

(and evaluate if there are any results at the same time)..

同时可以进行判断

if ( $dogs = $db->get_results(“SELECT breed, owner, name FROM dogs”, ARRAY_A) )

{

// Loop through the resulting array on the index $dogs[n]

$dogs[n]为索引循环数组

    foreach ( $dogs as $dog_detail )

    {

// Loop through the resulting array

循环赋值给数组

      foreach ( $dogs_detail as $key => $val )

      {

// Access and format data using $key and $val pairs..

以键名和键值的方式取得数据

        echo“<b>” . ucfirst($key) . “</b>: $val<br>”;

      }

// Do a P between dogs..

输出P

      echo “<p>”;

    }

}

else

{

// If no users were found then if evaluates to false..

如果没有任何结果输出将得到false

   echo “No dogs found.”;

}

Output:

Breed: Boxer

Owner: Amy

Name: Tyson

Breed: Labrador

Owner: Lee

Name: Henry

Breed: Dachshund

Owner: Mary

Name: Jasmine

Example 3 – Return results as numerical array

以数值数组方式返回结果

Returning results as a numerical array is useful if you are using completely dynamic queries with varying column names but still need a way to get a handle on the results. Here is an example of this concept in use. Imagine that this script was responding to a form with $type being submitted as either ‘fish’ or ‘dog’.

将结果以数值数组方式输出有利于使用动态方式查询结果并取出变量的列名(0,1,2,3…)但依然需要手段使我们取得结果,这里是一个例子讲告诉我们如何使用它,想象这是一个能够响应类别的函数,以fish或者dog的方式。

// Create an associative array for animal types..

创建一个保存动物类别的关联数组

$animal = array ( “fish” => “num_fins”, “dog” => “num_legs” );

// Create a dynamic query on the fly..

创建一个动态查询供使用

if ( $results = $db-> get_results (“SELECT $animal[$type] FROM $type”,ARRAY_N))

    {

      foreach ( $results as $result )

      {

        echo “$result[0]<br>”;

      }

    }

    else

    {

      echo “No $animal\s!”;

    }

      Output:

        4

        4

        4

    Note: The dynamic query would be look like one of the following...

动态查询其实是这个样子的

·         SELECT num_fins FROM fish

·         SELECT num_legs FROM dogs

    It would be easy to see which it was by using $db->debug(); after the dynamic query call.

当动态的查询被执行之后,它将非常简单的被$db->debug()查看。


$db->debug

-------------------------------------------------------------------------------------------------------------------------

$db->debug – print last sql query and returned results (if any)

输出前一个sql查询并返回任何存在的结果

Description

说明

$db->debug(void)

$db->debug() prints last sql query and its results (if any)

输出前一个sql查询并返回任何存在的结果

Example 1

If you need to know what your last query was and what the returned results are here is how you do it.

如果你需要知道你上一个查询得到了什么,你可以这么做。

// Extract results into the array $users..

将结果存入数组$users

$users = $db->get_results(“SELECT name, email FROM users”);

// See what just happened!

查看它是如何执行的。

$db->debug();


$db->vardump

-----------------------------------------------------------------------------------------------------------------------------------------------------

$db->vardump – print the contents and structure of any variable

输出变量的结构和内容

Description

说明

$db->vardump(void)

$db->vardump() prints the contents and structure of any variable. It does not matter what the structure is be it an object, associative array or numerical array.

输出变量的结构和内容,可以无视所输出的变量的类型(对象,关联数组,或数值数组)

Example 1

例子1

If you need to know what value and structure any of your results variables are here is how you do it.

如果你想知道这个变量的结构和值,你可以这么做

// Extract results into the array $users..

将结果放入数组$users.

$users = $db->get_results(“SELECT name, email FROM users”);

// View the contents and structure of $users

输出数组$users.的结构和内容。

$db->vardump($users);

$db->get_col

---------------------------------------------------------------------------------------------------------------------

$db->get_col – get one column from query (or previously cached results) based on column offset

按照列设置从查询中取出一列

Description

说明

$db->get_col( string query / null [, int column offset] )

$db->get_col(字符串查询/参数)

$db->get_col() extracts one column as one dimensional array based on a column offset. If no offset is supplied the offset will defualt to column 0.

I.E the first column. If a null query is supplied the previous query results are used.

$db->get_col()将设定的一列的值取出并放入一个一维数组中,如果没有参数,将返回第1列(数组下界从0开始,原文column 0.)

注意,如果当前查询为空将提取前一个查询的第一列作为结果

Example 1

例子1

// Extract list of products and print them out at the same time..

将产品表存入数组并输出来,

foreach ( $db->get_col(“SELECT product FROM product_list”) as $product)

{

            echo $product;

}

Example 2 – Working with cached results

使用之前缓存的结果

// Extract results into the array $users..

将结果存入数组$users

$users = $db->get_results(“SELECT * FROM users”);

// Work out how many columns have been selected..

计算其中的列数

$last_col_num = $db->num_cols - 1;

// Print the last column of the query using cached results..

从缓存结果中输出最后一列

foreach ( $db->get_col(null, $last_col_num) as $last_col )

{

            echo $last_col;

}


$db->get_col_info

------------------------------------------------------------------------------------------------------------

$db->get_col_info - get information about one or all columns such as column name or type

依据列名或类型取得一列或多列的信息

Description

说明

$db->get_col_info(string info-type[, int column offset])

$db->get_col_info(字符串,信息类型/参数])

$db->get_col_info()returns meta information about one or all columns such as column name or type. If no information type is supplied then the default information type of name is used. If no column offset is supplied then a one dimensional array is returned with the information type for ‘all columns’. For access to the full meta information for all columns you can use the cached variable $db->col_info

$db->get_col_info()依据列名或类型返回目标的一列或多列的信息,如果没有指定所要获取的信息类别,将输出默认的类别name ,如果没有没有列参数设定将默认输出所有列信息,如需要访问所有的目标信息,你可以使用这个调用缓存的方式$db->col_info。

Available Info-Types

可用的信息类别

mySQL

·         name - column name 列名称

·         table - name of the table the column belongs to 该列所在的表名称

·         max_length - maximum length of the column 该列的最大长度

·         not_null - 1 if the column cannot be NULL    判断该列不能为空

·         primary_key - 1 if the column is a primary key 判断该列是否为主键

·         unique_key - 1 if the column is a unique key 判断该列是否为唯一键(unique_key)

·         multiple_key - 1 if the column is a non-unique key判断该列是否为唯一键,输出结果与上一个相反

·         numeric - 1 if the column is numeric 判断该列是否为数值

·         blob - 1 if the column is a BLOB 判断该列是否为(binary large object),二进制大对象(百科)

·         type - the type of the column   列的类型

·         unsigned - 1 if the column is unsigned 判断列是否为无符号类型(百科)

·         zerofill - 1 if the column is zero-filled 判断列是否为zerofill类型(可能是得到之前的无符号结果(百度说的+_+))

ibase

·         name - column name 列名称

·         type - the type of the column   列的类型

·         length - size of column 该列的长度

·         alias – undocumented   (这个不认识,百度说是“无证明的”,+_+。。。)

·         relation – undocumented   (这个不认识,百度说是“无证明的”,+_+。。。)

MS-SQL / Oracle / Postgress

·         name - column name 列名称

·         type - the type of the column 列的类型

·         length - size of column该列的长度

SQLite

·         name - column name 列名称

Example 1

例子1

// Extract results into the array $users..

将结果存入数组$users

$users = $db->get_results(“SELECT id, name, email FROM users”);

// Output the name for each column type

按照列的类别输出列名

foreach ( $db->get_col_info(“name”) as $name )

{

            echo “$name<br>”;

}

            Output:

                        id

                        name

                        email

Example 2

// Extract results into the array $users..

将结果存入数组$users

$users = $db->get_results(“SELECT id, name, email FROM users”);

// View all meta information for all columns..

查看所有目标列的信息

$db->vardump($db->col_info);


$db->hide_errors

-----------------------------------------------------------------------------------------------------------------------

$db->hide_errors – turn ezSQL error output to browser off

关闭ezsql的错误输出

Description

说明

$db->hide_errors( void )

$db->hide_errors() stops error output from being printed to the web client. If you would like to stop error output but still be able to trap errors for debugging or for your own error output function you can make use of the global error array $EZSQL_ERROR.

$db->hide_errors()停止向客户端输出ezsql的错误提示,如果你希望在关闭错误提示后依然能够得到调试的错误信息或你自己的错误提示函数,你可以使用全局数组$EZSQL_ERROR得到错误提示。

Note: If there were no errors then the global error array $EZSQL_ERROR will evaluate to false. If there were one or more errors then it will have the following structure. Errors are added to the array in order of being called.

注意:如果没有任何错误的话,全局数组$EZSQL_ERROR将置为false,如果有任何错误的话,将被以如下方式存入数组以备调用。

(以下为ez内部函数区,翻译了也用不了,所以不翻译了,反正大家都知道+_+

$EZSQL_ERROR[0] = Array

(

[query] => SOME BAD QUERY

[error_str] => You have an error in your SQL syntax near ‘SOME BAD QUERY' at line 1

)

$EZSQL_ERROR[1] = Array

(

[query] => ANOTHER BAD QUERY

[error_str] => You have an error in your SQL syntax near ‘ANOTHER BAD QUERY' at line 1

)

$EZSQL_ERROR[2] = Array

(

[query] => THIRD BAD QUERY

[error_str] => You have an error in your SQL syntax near ‘THIRD BAD QUERY' at line 1

)

Example 1

例子

// Using a custom error function

使用一个常规的错误函数

$db->hide_errors();

// Make a silly query that will produce an error

使用一个错误的查询来制造一个错误信息。

$db->query(“INSERT INTO my_table A BAD QUERY THAT GENERATES AN ERROR”);

// And another one, for good measure

$db->query(“ANOTHER BAD QUERY THAT GENERATES AN ERROR”);

用另一个来做对照

// If the global error array exists at all then we know there was 1 or more ezSQL errors..

如果全局错误数组存在,我们将得到这里存在一个或多个ezsql的错误。

if ( $EZSQL_ERROR )

{

            // View the errors

            $db->vardump($EZSQL_ERROR);

}

else

{

            echo “No Errors”;

}


$db->show_errors

------------------------------------------------------------------------------------------------------------------

$db->show_errors – turn ezSQL error output to browser on

打开ezsql的错误输出

Description

说明

$db->show_errors( void )

$db->show_errors() turns ezSQL error output to the browser on. If you have not used the function $db->hide_errors this function (show_errors) will have no effect.

打开ezsql的错误输出,在未使用函数$db->hide_errors之前,此函数无效。

$db->escape

$db->escape – Format a string correctly in order to stop accidental mal formed queries under all PHP conditions.

格式化任何非标准PHP查询

Description

说明

$db->escape( string )

$db->escape() makes any string safe to use as a value in a query under all PHP conditions.

格式化任何非标准PHP查询使之适用于PHP环境

I.E. if magic quotes are turned on or off.

附加:无视magic quotes(自动转义)

Note: Should not be used by itself to guard against SQL injection attacks. The purpose of this function is to stop accidental mal formed queries.

注意:不可用于防范sql注入攻击,该函数仅用于格式化非标准查询。

Example 1

例子1

// Escape and assign the value..

格式化值

$title = $db->escape(“Justin’s and Amy’s Home Page”);

// Insert in to the DB..

插入数据库

$db->query(“INSERT INTO pages (title) VALUES (’$title’)”) ;

Example 2

例子2

// Assign the value..

分配值

$title = “Justin’s and Amy’s Home Page”;

// Insert in to the DB and escape at the same time..

在插入数据库的时候格式化它

$db->query(“INSERT INTO pages (title) VALUES (’”. $db->escape($title).”’)”) ;


Disk Caching

-------------------------------------------------------------------------------------------------------------

ezSQL has the ability to cache your queries which can make dynamic sites run much faster.

Ezsql可以缓存你的查询使动态网站能运行的更快

If you want to cache EVERYTHING just do..如果你希望缓存所有结果,可以这么做

            $db->use_disk_cache = true;

            $db->cache_queries = true;

            $db->cache_timeout = 24;

For full details and more specific options please see:

你可以查看以下文件来得到该参数的进一步信息

·mysql/disk_cache_example.php

·oracle8_9/disk_cache_example.php

原创粉丝点击