| ВС | ПН | ВТ | СР | ЧТ | ПТ | СБ |
|---|---|---|---|---|---|---|
| 30 | 31 | 1 | 2 | 3 | 4 | 5 |
| 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 27 | 28 | 29 | 30 | 1 | 2 | 3 |
Скрипт представляет собой набор двух классов PHP, которые совместно формируют абстрактный интерфейс для всех существующих баз данных, поддерживающих стандарт PHP.Имеется множество баз данных, которые поддерживают этот стандарт, но к сожалению не существует единственного понятного интерфейса для всех, а для каждой базы данных имеется собственный набор функций. Данный скрипт исправляет в некотором роде сложившуюся ситуацию, используя эту программу Вы сможете использовать функциональные возможности любой базы данных, при этом Ваши приложения будут восприимчивы к разнообразию свойств и функций различных баз данных.
<?php
/*****************************************************************************
Abstract DB , MySQL module, version 2.0b3
Copyright (C) 1998 Muze
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*****************************************************************************
for information,comments or bugreports, mail abstractdb@muze.nl
Changelog:
v2.0 mar. 2000
- added query->fieldname()
v2.0b3 22 jan. 1998
- db->db() constructor now sets a type variable (db->type) with the
default value of 'database_type'.
- new function query->error() which returns a description of the last
mysql error.
- changed db->nextid() to use autoincrement capabilities of mysql, code
contributed by Brian Moon.
- added check $this->result!=0 in query->getrow
- added @ on mysql_data_seek in query->firstrow
v2.0b2 1 dec. 1998
- fixed 2 small bugs in db->nextid() when db_sequence doesn't exist yet.
v2.0b1 first version with the new interface.
*****************************************************************************/
class db {
var $connect_id;
var $type;
function db($database_type="mysql") {
$this->type="mysql";
// dl("mysql");
}
function open($database="{database}", $host="{host}", $user="{user}", $password="{password}") {
$this->connect_id=mysql_pconnect($host, $user, $password);
if ($this->connect_id) {
$result=mysql_select_db($database);
if (!$result) {
mysql_close($this->connect_id);
$this->connect_id=$result;
}
}
return $this->connect_id;
}
function lock($table, $mode="write") {
// mode maybe 'read' or 'write'
$query=new query($this, "lock tables $table $mode");
$result=$query->result;
return $result;
}
function unlock() {
// unlocks any and all tables which this process locked
$query=new query($this, "unlock tables");
$result=$query->result;
return $result;
}
function nextid($sequence) {
// Function returns the next available id for $sequence, if it's not
// already defined, the first id will start at 1.
// This function will create a table for each sequence called
// '{sequence_name}_seq' in the current database.
// Based on code by Brian Moon.
$esequence=ereg_replace("'","''",$sequence)."_seq";
$query=new query($this, "REPLACE INTO $esequence values ('', nextval+1)");
if ($query->result) {
$nextid=mysql_insert_id($this->connect_id);
} else {
$query->query($this, "CREATE TABLE $esequence ( seq char(1)
DEFAULT '' NOT NULL, nextval bigint(20) unsigned DEFAULT '0' NOT NULL auto_increment,
PRIMARY KEY (seq), KEY nextval (nextval) )");
// there's no way to check if a create table has succeeded except by trying to insert
// a new value. Since you don't want an endless loop, a recursive call to
// nextid should not be made:
$query->query($this, "REPLACE INTO $esequence VALUES ( '', nextval+1 )");
if ($query->result) {
$nextid=mysql_insert_id($this->connect_id);
} else {
$nextid=0;
}
}
return $nextid;
}
function error() {
return mysql_errno($this->connect_id).": ".mysql_error($this->connect_id);
}
function close() {
// Closes the database connection and frees any query results left.
if ($this->query_id && is_array($this->query_id)) {
while (list($key,$val)=each($this->query_id)) {
@mysql_free_result($val);
}
}
$result=@mysql_close($this->connect_id);
return $result;
}
function addquery($query_id) {
// Function used by the constructor of query. Notifies the
// this object of the existance of a query_result for later cleanup
// internal function, don't use it yourself.
$this->query_id[]=$query_id;
}
};
/************************************** QUERY ***************************/
class query {
var $result;
var $row;
function query(&$db, $query="") {
// Constructor of the query object.
// executes the query, notifies the db object of the query result to clean
// up later
if ($query) {
if ($this->result) {
$this->free(); // query not called as constructor therefore there may
// be something to clean up.
}
$this->result=mysql_query($query, $db->connect_id);
$db->addquery($this->result);
}
}
function getrow() {
// Gets the next row for processing with $this->field function later.
if ($this->result) {
$this->row=mysql_fetch_array($this->result);
} else {
$this->row=0;
}
return $this->row;
}
function field($field) {
// get the value of the field with name $field
// in the current row
$result=$this->row[$field];
return $result;
}
function fieldname($fieldnum) {
// return the name of field number $fieldnum
// only call this after query->getrow() has been called at least once
return mysql_field_name( $this->result, $fieldnum );
}
function firstrow() {
// return the current row pointer to the first row
// (CAUTION: other versions may execute the query again!! (e.g. for oracle))
$result=@mysql_data_seek($this->result,0);
if ($result) {
$result=$this->getrow();
}
return $this->row;
}
function free() {
// free the mysql result tables
return @mysql_free_result($this->result);
}
};
?>
Было раннее утро, когда Бахыш-киши, опираясь на палку, похожую на пастушеский посох, неторопливо шагал по тропинке между зелеными эльдарскими соснами. Веял легкий рассветный ветер, но гудение стрекоз предвещало, что скоро он стихнет и день будет знойный.
Статный, кряжистый, с густой шапкой седых волос, Бахыш-киши чем-то напоминал могучий дуб, поднявшийся среди молодых сосенок. И то сказать - по всему было заметно, что он этой молодой роще сродни. Не он ли вот уже который год ухаживал за деревьями, щедро поил их водой, окапывал... Он чувствовал себя не хозяином, а скорее частью этой рощи. Он заботился о ней, как в семье заботятся о ребенке. И вот он шел, отбрасывая посохом с тропинки сухие ветки, внимательно оглядывая деревья - все ли в порядке, не произошло ли чего за время его отсутствия.
Собственно, отлучка-то была недолгой - всего недели две, но Бахыш-киши был домоседом, никуда из родных мест выезжать не любил, даже отпуска свои вот уже который год подряд проводил здесь, в зеленой сосновой роще. А когда кто-нибудь из родных принимался укорять его: "Давно тебе, Бахыш, пора уехать отсюда и отдохнуть хорошенько!"-старый садовник не на шутку сердился: "Ты понимаешь или нет, что для меня здесь - лучший отдых!"
И это была сущая правда. Цель в жизни, смысл ее, призвание Бахыш-киши обрел по-настоящему здесь, в этом знойном уголке Апшерона, в сосновой роще, которую своими руками сажал, холил, пестовал. Без этих сосенок он, кажется, не мог и не хотел дня прожить. Наверняка оп сейчас бы отказался от поездки, но письмо, позвавшее в дорогу, растревожило душу. Писали его боевые друзья из Белоруссии, те, с кем он делился в годы войны хлебом, те, с кем вместе он воевал в болотистых чащобах Полесья. Сейчас они звали его на встречу ветеранов - мог ли он не откликнуться? В тот же день Бахыш-киши отбил в почтовом отделении телеграмму: "Ждите, еду", и в назначенный срок вылетел утренним рейсом в Минск.
И теперь, шагая по участку, где сосны уже подросли, сомкнули ветви, /Бахыш-киши вспоминал густую тень белорусского леса, поляну, на которой зажгли старые бойцы костер, как в те давние военные годы, как звучали фронтовые песни... Радостной была встреча старых партизан, радостной и грустной. Большое счастье - увидеть товарищей по оружию, с которыми судьба надолго разлучила. И очень трудно вспоминать о тех, кого унесла война, кто на фронте погиб, кто после - от ран. И то сказать - сорок лет прошло. Было в войну Бахышу двадцать три года, в отряде он был одним из самых молодых.