Софт-Архив

Database img-1

Database

Рейтинг: 4.2/5.0 (1830 проголосовавших)

Категория: Windows: Базы данных

Описание

Database - это

database это:

вчт. многоцелевая база данных corporate

вчт. база данных фирмы database вчт. база данных

of code вчт. программная база данных

вчт. коммутируемая база данных extensional

вчт. несвязнная база данных normalized

Смотреть что такое "database" в других словарях:

database — da?ta?base [?de?t??be?s] noun [countable] COMPUTING a large amount of information on a particular subject that is stored on a computer in an organized way so that you can find and use it easily: • a database of all the UK clearing houses •… … Financial and business terms

database — noun catalogue, computer base of information, computer file, computer storage, memory Generally:<<>>cyberspace, record, records, registry Burton s Legal Thesaurus. William C. Burton. 2006 … Law dictionary

database — n. an organized body of related information. [WordNet 1.5] … The Collaborative International Dictionary of English

Database —   [engl.], Datenbank … Universal-Lexikon

database — (izg. dejtabejz) m DEFINICIJA inform. strogo organiziran skup podataka s mogucnoscu brzog pristupa i efikasne manipulacije; baza podataka ETIMOLOGIJA engl … Hrvatski jezicni portal

database — > NOUN ? a structured set of data held in a computer … English terms dictionary

database — [dat??bas?, dat??bas?; ] Brit also [, dat?t?bas?] n. 1. a large collection of data in a computer, organized so that it can be expanded, updated, and retrieved rapidly for various uses 2. any large or extensive collection of information: Also data … English World dictionary

Database — A database is an organized collection of data for one or more purposes, usually in digital form. The data are typically organized to model relevant aspects of reality (for example, the availability of rooms in hotels), in a way that supports… … Wikipedia

database — /day teuh bays /, n. 1. a comprehensive collection of related data organized for convenient access, generally in a computer. 2. See data bank. Also, data base, data base. [1965 70; DATA + BASE1] * * * Collection of data or information organized… … Universalium

database — noun ADJECTIVE ? large ? comprehensive ? central, national, public ? computer, computerized, electronic … Collocations dictionary

database —    A collection of related objects, including tables, forms, reports, queries, and scripts, created and organized by a database management system (DBMS). A database can contain information of almost any type, such as a list of magazine… … Dictionary of networking

  • Oracle Database 11g. Руководство администратора баз данных. Алапати Сэм Р. Книга Oracle Database 11g: Руководство администратора баз данных для профессионалов - энциклопедический справочник по СУБД Oracle 11g, описывающий все инструменты и технологиидля построения и… Подробнее Купить за 5870 руб
  • Oracle Database 11g. Руководство администратора баз данных. Сэм Алапати. Книга Oracle Database 11g: Руководство администратора баз данных для профессионалов - энциклопедический справочник по СУБД Oracle 11g, описывающий все инструменты и технологиидля построения и… Подробнее Купить за 3030 руб
  • Oracle Database 11g. Руководство администратора баз данных. Алапати С.Р. Многие люди, попадающие в мир администрирования баз данных, находят его захватывающим, однако необъятным в смысле разнообразия и границ. Эта книга - результат моегоглубокого убеждения в том,… Подробнее Купить за 3003 руб
Другие книги по запросу «database» >>

Другие статьи, обзоры программ, новости

Database

Обратите внимание

лучшие обновления для Windows

Наибольшая русскоязычная база с чит кодами, трейнерами и прохождениями для компьютерных игр. Все чит коды переведены и проверены лично нами. Количество игр представленных в текущей версии - 11161.

  • БЕСПЛАТНО -
  • ОС: Windows
  • CheMax Team | 2016-01-04

Эта программа представляет собой бесплатный аналог Adobe Photoshop. Она точно также включает в себя множество инструментов для работы с растровой графикой, и даже имеет ряд инструментов для векторной графики. GIMP это полноценная замена Photoshop.

  • БЕСПЛАТНО -
  • ОС: Windows
  • The GIMP Team | 2016-01-04

Мощная и бесплатная антивирусная программа, которая защитить ваш компьютер от всяческих угроз, включая вирусы, трояны, и т.д. AVG Anti-Virus Free также защитить вас в Интернете от потенциально опасных веб-сайтов и других видов угроз.

  • БЕСПЛАТНО -
  • ОС: Windows
  • AVG | 2016-01-04

Connect to database - MATLAB database

There are three ways to connect to a database. For ODBC drivers, connect to a database using the native ODBC interface or the JDBC/ODBC bridge. For JDBC drivers, connect to a database using a JDBC driver. For details about deciding which connection option is best in your situation, see Choosing Between ODBC and JDBC Drivers. For details about the native ODBC interface, see Connecting to a Database Using the Native ODBC Interface .

Description

conn = database( instance , username , password ) returns a database connection object for the connection to the ODBC data source setup instance using the JDBC/ODBC bridge.

Connect to Microsoft Access Using the Native ODBC Interface Connect to Microsoft SQL Server Using Windows Authentication Connect to Oracle Using a JDBC Driver Connect to MySQL Using a JDBC Driver Connect to PostgreSQL Using a JDBC Driver instance — Data source setup or database name string username — User name string password — Password string driver — JDBC driver name string databaseurl — Database connection URL string

Database connection URL, specified as a string for the vendor-specific URL. This URL is typically constructed using connection properties such as server name, port number, and database name. For details, see JDBC driver name and database connection URL. If you do not know the driver name or the URL, you can use name-value pair arguments to specify individual connection properties.

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside single quotes ( ' ' ). You can specify several name and value pair arguments in any order as Name1,Value1. NameN,ValueN .

Example: 'Vendor','MySQL','Server','remotehost' connects to a MySQL database on a machine named remotehost.

'Vendor' — Database vendor 'MySQL' | 'Oracle' | 'Microsoft SQL Server' | 'PostgreSQL'

Database vendor, specified as the comma-separated pair consisting of 'Vendor' and one of the following strings:

Database

A database is an organized collection of data for one or more purposes, usually in digital form. The data are typically organized to model relevant aspects of reality (for example, the availability of rooms in hotels), in a way that supports processes requiring this information (for example, finding a hotel with vacancies). This definition is very general, and is independent of the technology used.

The term "database" may be narrowed to specify particular aspects of organized collection of data and may refer to the logical database, to physical database as data content in computer data storage or to many other database sub-definitions.

The term database is correctly applied to the data and their supporting data structures, and not to the database management system (referred to by the acronym DBMS). The database data collection with DBMS is called a database system .

The term database system implies that the data is managed to some level of quality (measured in terms of accuracy, availability, usability, and resilience) and this in turn often implies the use of a general-purpose database management system (DBMS). [ 1 ] A general-purpose DBMS is typically a complex software system that meets many usage requirements, and the databases that it maintains are often large and complex. The utilization of databases is now spread to such a wide degree that virtually every technology and product relies on databases and DBMSs for its development and commercialization, or even may have such embedded in it. Also, organizations and companies, from small to large, heavily depend on databases for their operations.

Well known DBMSs include Oracle. IBM DB2. Microsoft SQL Server. PostgreSQL. MySQL and SQLite. A database is not generally portable across different DBMS, but different DBMSs can inter-operate to some degree by using standards like SQL and ODBC to support together a single application. A DBMS also needs to provide effective run-time execution to properly support (e.g. in terms of performance, availability. and security ) as many end-users as needed.

The design, construction, and maintenance of a complex database requires specialist skills: the staff performing these functions are referred to as database application programmers and database administrators. Their tasks are supported by tools provided either as part of the DBMS or as stand-alone software products. These tools include specialized database languages including data definition languages (DDL), data manipulation languages (DML), and query languages. These can be seen as special-purpose programming languages. tailored specifically to manipulate databases; sometimes they are provided as extensions of existing programming languages, with added database commands. Database languages are generally specific to one data model. and in many cases they are specific to one DBMS type. The most widely supported database language is SQL. which has been developed for the relational data model and combines the roles of both DDL, DML, and a query language.

A way to classify databases involves the type of their contents, for example: bibliographic, document-text, statistical, or multimedia objects. Another way is by their application area, for example: accounting, music compositions, movies, banking, manufacturing, or insurance.

The database concept

The database concept has evolved since the 1960s to ease increasing difficulties in designing, building, and maintaining complex information systems (typically with many concurrent end-users, and with a diverse large amount of data). It has evolved together with database management systems which enable the effective handling of databases. Though the terms database and DBMS define different entities, they are inseparable: a database's properties are determined by its supporting DBMS and vice-versa. The Oxford English dictionary cites [ citation needed ] a 1962 technical report as the first to use the term "data-base." With the progress in technology in the areas of processors, computer memory. computer storage. and computer networks, the sizes, capabilities, and performance of databases and their respective DBMSs have grown in orders of magnitudes. For decades it has been unlikely that a complex information system can be built effectively without a proper database supported by a DBMS. The utilization of databases is now spread to such a wide degree that virtually every technology and product relies on databases and DBMSs for its development and commercialization, or even may have such embedded in it. Also, organizations and companies, from small to large, heavily depend on databases for their operations.

No widely accepted exact definition exists for DBMS. However, a system needs to provide considerable functionality to qualify as a DBMS. Accordingly its supported data collection needs to meet respective usability requirements (broadly defined by the requirements below ) to qualify as a database. Thus, a database and its supporting DBMS are defined here by a set of general requirements listed below. Virtually all existing mature DBMS products meet these requirements to a great extent, while less mature either meet them or converge to meet them.

Evolution of database and DBMS technology

The introduction of the term database coincided with the availability of direct-access storage (disks and drums) from the mid-1960s onwards. The term represented a contrast with the tape-based systems of the past, allowing shared interactive use rather than daily batch processing.

In the earliest database systems, efficiency was perhaps the primary concern, but it was already recognized that there were other important objectives. One of the key aims was to make the data independent of the logic of application programs, so that the same data could be made available to different applications.

The first generation of database systems were navigational . [ 2 ] applications typically accessed data by following pointers from one record to another. The two main data models at this time were the hierarchical model, epitomized by IBM's IMS system, and the Codasyl model (Network model ), implemented in a number of products such as IDMS .

The Relational model. first proposed in 1970 by Edgar F. Codd. departed from this tradition by insisting that applications should search for data by content, rather than by following links. This was considered necessary to allow the content of the database to evolve without constant rewriting of applications. Relational systems placed heavy demands on processing resources, and it was not until the mid 1980s that computing hardware became powerful enough to allow them to be widely deployed. By the early 1990s, however, relational systems were dominant for all large-scale data processing applications, and they remain dominant today (2011) except in niche areas. The dominant database language is the standard SQL for the Relational model, which has influenced database languages also for other data models.

Because the relational model emphasizes search rather than navigation, it does not make relationships between different entities explicit in the form of pointers, but represents them rather using primary keys and foreign keys. While this is a good basis for a query language, it is less well suited as a modeling language. For this reason a different model, the Entity-relationship model which emerged shortly later (1976), gained popularity for database design .

In the period since the 1970s database technology has kept pace with the increasing resources becoming available from the computing platform: notably the rapid increase in the capacity and speed (and reduction in price) of disk storage, and the increasing capacity of main memory. This has enabled ever larger databases and higher throughputs to be achieved.

The rigidity of the relational model, in which all data is held in tables with a fixed structure of rows and columns, has increasingly been seen as a limitation when handling information that is richer or more varied in structure than the traditional 'ledger-book' data of corporate information systems: for example, document databases, engineering databases, multimedia databases, or databases used in the molecular sciences. Various attempts have been made to address this problem, many of them gathering under banners such as post-relational or NoSQL. Two developments of note are the Object database and the XML database. The vendors of relational databases have fought off competition from these newer models by extending the capabilities of their own products to support a wider variety of data types.

General-purpose DBMS

A DBMS has evolved into a complex software system and its development typically requires thousands of person-years of development effort. Some general-purpose DBMSs, like Oracle, Microsoft SQL server. and IBM DB2, have been in on-going development and enhancement for thirty years or more. General-purpose DBMSs aim to satisfy as many applications as possible, which typically makes them even more complex than special-purpose databases. However, the fact that they can be used "off the shelf", as well as their amortized cost over many applications and instances, makes them an attractive alternative (Vs. one-time development) whenever they meet an application's requirements.

Though attractive in many cases, a general-purpose DBMS is not always the optimal solution: When certain applications are pervasive with many operating instances, each with many users, a general-purpose DBMS may introduce unnecessary overhead and too large "footprint" (too large amount of unnecessary, unutilized software code). Such applications usually justify dedicated development. Typical examples are email systems, though they need to possess certain DBMS properties: email systems are built in a way that optimizes email messages handling and managing, and do not need significant portions of a general-purpose DBMS functionality.

Types of people involved

Three types of people are involved with a general-purpose DBMS:

  1. DBMS developers - These are the people that design and build the DBMS product, and the only ones who touch its code. They are typically the employees of a DBMS vendor (e.g. Oracle. IBM. Microsoft. Sybase ), or, in the case of Open source DBMSs (e.g. MySQL), volunteers or people supported by interested companies and organizations. They are typically skilled systems programmers. DBMS development is a complicated task, and some of the popular DBMSs have been under development and enhancement (also to follow progress in technology) for decades.
  2. Application developers and Database administrators - These are the people that design and build a database-based application that uses the DBMS. The latter group members design the needed database and maintain it. The first group members write the needed application programs which the application comprises. Both are well familiar with the DBMS product and use its user interfaces (as well as usually other tools) for their work. Sometimes the application itself is packaged and sold as a separate product, which may include the DBMS inside (see Embedded database ; subject to proper DBMS licensing), or sold separately as an add-on to the DBMS.
  3. Application's end-users (e.g. accountants, insurance people, medical doctors, etc.) - These people know the application and its end-user interfaces, but need not know nor understand the underlying DBMS. Thus, though they are the intended and main beneficiaries of a DBMS, they are only indirectly involved with it.
Database machines and appliances

In the 1970s and 1980s attempts were made to build database systems with integrated hardware and software. The underlying philosophy was that such integration would provide higher performance at lower cost. Examples were IBM System/38, the early offering of Teradata. and the Britton Lee, Inc. database machine. Another approach to hardware support for database management was ICL 's CAFS accelerator, a hardware disk controller with programmable search capabilities. In the long term these efforts were generally unsuccessful because specialized database machines could not keep pace with the rapid development and progress of general-purpose computers. Thus most database systems nowadays are software systems running on general-purpose hardware, using general-purpose computer data storage. However this idea is still pursued for certain applications by some companies like Netezza and Oracle (Exadata).

Database research

Database research has been an active and diverse area, with many specializations, carried out since the early days of dealing with the database concept in the 1960s. It has strong ties with database technology and DBMS products. Database research has taken place at research and development groups of companies (e.g. notably at IBM Research. who contributed technologies and ideas virtually to any DBMS existing today), research institutes. and Academia. Research has been done both through Theory and Prototypes. The interaction between research and database related product development has been very productive to the database area, and many related key concepts and technologies emerged from it. Notable are the Relational and the Entity-relationship models. the Atomic transaction concept and related Concurrency control techniques, Query languages and Query optimization methods, RAID. and more. Research has provided deep insight to virtually all aspects of databases, though not always has been pragmatic, effective (and cannot and should not always be: research is exploratory in nature, and not always leads to accepted or useful ideas). Ultimately market forces and real needs determine the selection of problem solutions and related technologies, also among those proposed by research. However, occasionally, not the best and most elegant solution wins (e.g. SQL). Along their history DBMSs and respective databases, to a great extent, have been the outcome of such research, while real product requirements and challenges triggered database research directions and sub-areas.

The database research area has several notable dedicated academic journals (e.g. ACM Transactions on Database Systems-TODS, Data and Knowledge Engineering -DKE, and more) and annual conferences (e.g. ACM SIGMOD. ACM PODS, VLDB, IEEE ICDE, and more), as well as an active and quite heterogeneous (subject-wise) research community all over the world.

Database type examples

The following are examples of various database types. Some of them are not main-stream types, but most of them have received special attention (e.g. in research) due to end-user requirements. Some exist as specialized DBMS products, and some have their functionality types incorporated in existing general-purpose DBMSs.

Active database

An active database is a database that includes an event-driven architecture which can respond to conditions both inside and outside the database. Possible uses include security monitoring, alerting, statistics gathering and authorization.

Cloud database

A Cloud database is a database that relies on cloud technology. Both the database and most of its DBMS reside remotely, "in the cloud," while its applications are both developed by programmers and later maintained and utilized by (application's) end-users through a Web browser and Open APIs. More and more such database products are emerging, both of new vendors and by virtually all established database vendors.

Data warehouse

Data warehouses archive data from operational databases and often from external sources such as market research firms. Often operational data undergoes transformation on its way into the warehouse, getting summarized, anonymized, reclassified, etc. The warehouse becomes the central source of data for use by managers and other end-users who may not have access to operational data. For example, sales data might be aggregated to weekly totals and converted from internal product codes to use UPCs so that it can be compared with ACNielsen data. Some basic and essential components of data warehousing include retrieving, analyzing, and mining data, transforming,loading and managing data so as to make it available for further use.

Operations in a data warehouse are typically concerned with bulk data manipulation, and as such, it is unusual and inefficient to target individual rows for update, insert or delete. Bulk native loaders for input data and bulk SQL passes for aggregation are the norm.

Distributed database

The definition of a distributed database is broad, and may be utilized in different meanings. In general it typically refers to a modular DBMS architecture that allows distinct DBMS instances to cooperate as a single DBMS over processes, computers, and sites, while managing a single database distributed itself over multiple computers, and different sites.

Examples are databases of local work-groups and departments at regional offices, branch offices, manufacturing plants and other work sites. These databases can include both segments shared by multiple sites, and segments specific to one site and used only locally in that site.

Embedded database

An embedded database system is a DBMS which is tightly integrated with an application software that requires access to stored data in a way that the DBMS is “hidden” from the application’s end-user and requires little or no ongoing maintenance. It is actually a broad technology category that includes DBMSs with differing properties and target markets. The term "embedded database" can be confusing because only a small subset of embedded database products is used in real-time embedded systems such as telecommunications switches and consumer electronics devices. [ 3 ]

End-user database

These databases consist of data developed by individual end-users. Examples of these are collections of documents, spreadsheets, presentations, multimedia, and other files. Several products exist to support such databases. Some of them are much simpler than full fledged DBMSs, with more elementary DBMS functionality (e.g. not supporting multiple concurrent end-users on a same database), with basic programming interfaces, and a relatively small "foot-print" (not much code to run as in "regular" general-purpose databases). However, also available general-purpose DBMSs can often be used for such purpose, if they provide basic user-interfaces for straightforward database applications (limited query and data display; no real programming needed), while still enjoying the database qualities and protections that these DBMSs can provide.

Federated database and multi-database

A federated database is an integrated database that comprises several distinct databases, each with its own DBMS. It is handled as a single database by a federated database management system (FDBMS), which transparently integrates multiple autonomous DBMSs, possibly of different types (which makes it a heterogeneous database ), and provides them with an integrated conceptual view. The constituent databases are interconnected via computer network. and may be geographically decentralized.

Sometime the term multi-database is used as a synonym to federated database, though it may refer to a less integrated (e.g. without an FDBMS and a managed integrated schema) group of databases that cooperate in a single application. In this case typically middleware for distribution is used which typically includes an atomic commit protocol (ACP), e.g. the two-phase commit protocol. to allow distributed (global) transactions (vs. local transactions confined to a single DBMS) across the participating databases.

Graph database

A graph database is a kind of NoSQL database that uses graph structures with nodes, edges, and properties to represent and store information. General graph databases that can store any graph are distinct from specialized graph databases such as triplestores and network databases.

Hypermedia databases Knowledge base Operational database

These databases store detailed data about the operations of an organization. They are typically organized by subject matter, process relatively high volumes of updates using transactions. Essentially every major organization on earth uses such databases. Examples include customer databases that record contact, credit, and demographic information about a business' customers, personnel databases that hold information such as salary, benefits, skills data about employees, Enterprise resource planning that record details about product components, parts inventory, and financial databases that keep track of the organization's money, accounting and financial dealings.

Parallel database

A parallel database. run by a parallel DBMS, seeks to improve performance through parallelization for tasks such as loading data, building indexes and evaluating queries. Parallel databases improve processing and input/output speeds by using multiple central processing units (CPUs) (including multi-core processors ) and storage in parallel. In parallel processing, many operations are performed simultaneously, as opposed to serial, sequential processing, where operations are performed with no time overlap.

  • Shared memory architecture . where multiple processors share the main memory space, as well as other data storage.
  • Shared disk architecture. where each processing unit (typically consisting of multiple processors) has its own main memory, but all units share the other storage.
  • Shared nothing architecture . where each processing unit has its own main memory and other storage.

Database

The main database is a key component of OpenStreetMap, because obviously it's where we keep all our data.

Please note that this is not the only database used to generate maps. Have a look at Component overview to see what other databases exist.

The main database is accessed for editing via the API. If you want to get data see APIs for multiple available options.

Data model

The database contains tables for each Element type (nodes, ways, relations). In fact for each of these there are several database tables: current, history, current_tags, history_tags. In addition there are database tables for storing changeset, gpx_files, users, diary entries, sessions, oauth etc.

You can get a detailed look at the SQL statements at Rails port/Database schema.

Databases elsewhere will be structured differently. For example most applications only need the current map data. Different OSM tools use different database setups (See Databases#Database_Schemas ).

Postgres server instance

OpenStreetMap switched from MySQL to a PostgreSQL server for its main site on April 19 2009 [1] that is part of the rails port. This is running on a separate machine Servers/smaug. On April 1 2012 a process of moving to a new server commenced. For problems see Platform Status.

What is Database (DB)? Webopedia

Related Terms

(1) Often abbreviated DB, a database is basically a collection of information organized in such a way that a computer program can quickly select desired pieces of data. You can think of a database as an electronic filing system .

Traditional databases are organized by fields . records . and files . A field is a single piece of information; a record is one complete set of fields; and a file is a collection of records. For example, a telephone book is analogous to a file. It contains a list of records, each of which consists of three fields: name, address, and telephone number.

An alternative concept in database design is known as Hypertext . In a Hypertext database, any object. whether it be a piece of text. a picture, or a film, can be linked to any other object. Hypertext databases are particularly useful for organizing large amounts of disparate information, but they are not designed for numerical analysis.

To access information from a database, you need a database management system (DBMS) . This is a collection of programs that enables you to enter, organize, and select data in a database.

(2) Increasingly, the term database is used as shorthand for database management system. There are many different types of DBMSs, ranging from small systems that run on personal computers to huge systems that run on mainframes .

Database

Connecting to a Database Engine

Fat-Free is designed to make the job of interfacing with SQL databases a breeze. If you're not the type to immerse yourself in details about SQL, but lean more towards object-oriented data handling, you can go directly to the next section of this tutorial. However, if you need to do some complex data-handling and database performance optimization tasks, SQL is the way to go.

Establishing communication with a SQL engine like MySQL, SQLite, PostgreSQL, SQL Server, Sybase, and Oracle is done using the familiar $f3->set() command. Connecting to a SQLite database would be:

You can now work with database object from anywhere in your application with $f3->get('DB')->exec('…'); .

Another example, this time with MySQL:

Querying the Database

OK. That was easy, wasn't it? That's pretty much how you would do the same thing in ordinary PHP. You just need to know the DSN format of the database you're connecting to. See the PDO section of the PHP manual .

Let's continue our PHP code:

Huh, what's going on here? Shouldn't we be setting up things like PDOs, statements, cursors, etc. The simple answer is: you don't have to. F3 simplifies everything by taking care of all the hard work in the backend.

This time we create an HTML template like abc.htm that has at a minimum the following:

In most instances, the SQL command set should be enough to generate a Web-ready result so you can use the result array variable in your template directly. Be that as it may, Fat-Free will not stop you from getting into its SQL handler internals. In fact, F3's DB\SQL class derives directly from PHP's PDO class, so you still have access to the underlying PDO components and primitives involved in each process, if you need some fine-grain control.

Transactions

Here's another example. Instead of a single statement provided as an argument to the $db->exec() command, you can also pass an array of SQL statements:

F3 is smart enough to know that if you're passing an array of SQL instructions, this indicates a SQL batch transaction. You don't have to worry about SQL rollbacks and commits because the framework will automatically revert to the initial state of the database if any error occurs during the transaction. If successful, F3 commits all changes made to the database.

You can also start and end a transaction programmatically:

A rollback will occur if any of the statements encounter an error.

To get a list of all database instructions issued:

Parameterized Queries

Passing string arguments to SQL statements is fraught with danger. Consider this:

If the POST variable userID does not go through any data sanitation process, a malicious user can pass the following string and damage your database irreversibly:

Luckily, parameterized queries help you mitigate these risks:

If F3 detects that the value of the query parameter/token is a string, the underlying data access layer escapes the string and adds quotes as necessary.

Our example in the previous section will be a lot safer from SQL injection if written this way:

CRUD (But With a Lot of Style)

F3 is packed with easy-to-use object-relational mappers (ORMs) that sit between your application and your data - making it a lot easier and faster for you to write programs that handle common data operations - like creating, retrieving, updating, and deleting (CRUD) information from SQL and NoSQL databases. Data mappers do most of the work by mapping PHP object interactions to the corresponding backend queries.

Suppose you have an existing MySQL database containing a table of users of your application. (SQLite, PostgreSQL, SQL Server, Sybase will do just as well.) It would have been created using the following SQL command:

Note: MongoDB is a NoSQL database engine and inherently schema-less. F3 has its own fast and lightweight NoSQL implementation called Jig, which uses PHP-serialized or JSON-encoded flat files. These abstraction layers require no rigid data structures. Fields may vary from one record to another. They can also be defined or dropped on the fly.

Now back to SQL. First, we establish communication with our database.

To retrieve a record from our table:

The first line instantiates a data mapper object that interacts with the users table in our database. Behind the scene, F3 retrieves the structure of the users table and determines which field(s) are defined as primary key(s). At this point, the mapper object does not contain any data yet (it is called "dry state" ) and the $user var is basically nothing more than a structured object - but it contains the methods it needs to perform the basic CRUD operations plus some extras as you will see later. Now, to retrieve a record from our users table with, e.g. the field userID containing the string value tarzan. we use the load() method. This process is called "auto-hydrating" the data mapper object.

Easy, wasn't it? F3 understands that a SQL table already has a structural definition existing within the database engine itself. Unlike other frameworks, F3 requires no extra class declarations (unless you want to extend the data mappers to fit complex objects), no redundant PHP array/object property-to-field mappings (duplication of efforts), no code generators (which require code regeneration if the database structure changes), no stupid XML/YAML files to configure your models, no superfluous commands just to retrieve a single record. With F3, a simple resizing of a varchar field in your MySQL table does not require a single change in your application code. Consistent with MVC and "separation of concerns", the database admin has as much control over the data and the structures as a template designer has over HTML/XML templates.

If you prefer working with NoSQL databases, the similarities in query syntax are superficial. In the case of the MongoDB data mapper, the equivalent code would be:

With Jig, the syntax is similar to F3's template engine:

The Smart SQL ORM

The framework automatically maps the field visits in our table to a data mapper property during object instantiation, i.e. $user=new DB\SQL\Mapper($db,'users');. Once the object is created, $user->password and $user->userID would map to the password and userID fields in our table, respectively.

You can't add or delete a mapped field, or change a table structure using the ORM. You must do this in MySQL, or whatever database engine you're using. After you've made the changes in your database engine, Fat-Free will automatically synchronize the new table structure with your data mapper object when you run your application.

F3 derives the data mapper structure directly from the database schema. No guesswork involved. It understands the differences between MySQL, SQLite, MSSQL, Sybase, and PostgreSQL database engines.

Notice: SQL identifiers should not use reserved words, and should be limited to alphanumeric characters A-Z. 0-9. and the underscore symbol ( _ ). Column names containing spaces (or special characters) and surrounded by quotes in the data definition are not compatible with the ORM. They cannot be represented properly as PHP object properties.

Let's say we want to increment the user's number of visits and update the corresponding record in our users table, we can add the following code:

If we wanted to insert a record, we follow this process:

We still use the same save() method. But how does F3 know when a record should be inserted or updated? At the time a data mapper object is auto-hydrated by a record retrieval, the framework keeps track of the record's primary keys (or _id. in the case of MongoDB and Jig) - so it knows which record should be updated or deleted - even when the values of the primary keys are changed. A programmatically-hydrated data mapper - the values of which were not retrieved from the database, but populated by the application - will not have any memory of previous values in its primary keys. The same applies to MongoDB and Jig, but using object _id as reference. So, when we instantiated the $user object above and populated its properties with values from our program - without at all retrieving a record from the user table, F3 knows that it should insert this record.

A mapper object will not be empty after a save(). If you wish to add a new record to your database, you must first flush the mapper using the reset method:

Calling save() a second time without invoking reset() will simply update the record currently pointed to by the mapper.

Caveat for SQL Tables

Although the issue of having primary keys in all tables in your database is argumentative, F3 does not stop you from creating a data mapper object that communicates with a table containing no primary keys. The only drawback is: you can't delete or update a mapped record because there's absolutely no way for F3 to determine which record you're referring to plus the fact that positional references are not reliable. Row IDs are not portable across different SQL engines and may not be returned by the PHP database driver.

To remove a mapped record from our table, invoke the erase() method on an auto-hydrated data mapper. For example:

Jig's query syntax would be slightly similar:

And the MongoDB equivalent would be:

Mapper Data Status

To find out whether our data mapper was loaded with a valid data record or not, use the dry method:

Beyond CRUD

We've covered the CRUD handlers. There are some extra methods that you might find useful:

Notice that we can also use Fat-Free variables as containers for mapper objects. The copyFrom() method hydrates the mapper object with elements from a framework array variable, the array keys of which must have names identical to the mapper object properties, which in turn correspond to the record's field names. So, when a Web form is submitted (assuming the HTML name attribute is set to userID ), the contents of that input field is transferred to $_POST['userID']. duplicated by F3 in its POST.userID variable, and saved to the mapped field $user->userID in the database. The process becomes very simple if they all have identically-named elements. Consistency in array keys, i.e. template token names, framework variable names and field names is key :)

Danger: By default, copyfrom takes the whole array provided. This may open a security leak if the user posts more fields than you expect. Use the 2nd parameter to setup a filter callback function to get rid of unwanted fields to copy from.

On the other hand, if we wanted to retrieve a record and copy the field values to a framework variable for later use, like template rendering:

We can then assign << @POST.userID >> to the same input field's value attribute. To sum up, the HTML input field will look like this:

The save(). update(). copyFrom() data mapper methods and the parameterized variants of load() and erase() are safe from SQL injection.

Navigation and Pagination

By default, a data mapper's load() method retrieves only the first record that matches the specified criteria. If you have more than one that meets the same condition as the first record loaded, you can use the skip() method for navigation:

You may use $user->next() as a substitute for $user->skip(). and $user->prev() if you think it gives more meaning to $user->skip(-1) .

Use the dry() method to check if you've maneuvered beyond the limits of the result set. dry() will return TRUE if you try skip(-1) on the first record. It will also return TRUE if you skip(1) on the last record that meets the retrieval criteria.

The load() method accepts a second argument: an array of options containing key-value pairs such as:

If you're using MySQL, the query translates to:

This is one way of presenting data in small chunks. Here's another way of paginating results:

In the above scenario, F3 will retrieve records that match the criteria 'visits>3'. It will then limit the results to 5 records (per page) starting at page offset 2 (0-based). The framework will return an array consisting of the following elements:

The actual subset position returned will be NULL if the first argument of paginate() is a negative number or exceeeds the number of subsets found.

Virtual Fields

There are instances when you need to retrieve a computed value of a field, or a cross-referenced value from another table. Enter virtual fields. The SQL mini-ORM allows you to work on data derived from existing fields.

Suppose we have the following table defined as:

No totalprice field exists, so we can tell the framework to request from the database engine the arithmetic product of the two fields:

The above code snippet defines a virtual field called totalprice which is computed by multiplying unitprice by the quantity. The SQL mapper saves that rule/formula, so when the time comes to retrieve the record from the database, we can use the virtual field like a regular mapped field.

You can have more complex virtual fields:

This time the framework retrieves the product with the highest quantity (notice the load() method does not define any criteria, so all records in the table will be processed). Of course, the virtual field mostNumber will still give you the right figure if you wish to limit the expression to a specific group of records that match a specified criteria.

You can also derive a value from another table:

Every time you load a record from the products table, the ORM cross-references the supplerID in the products table with the supplierID in the suppliers table.

To destroy a virtual field, use unset($item->totalPrice);. The isset($item->totalPrice) expression returns TRUE if the totalPrice virtual field was defined, or FALSE if otherwise.

Remember that a virtual field must be defined prior to data retrieval. The ORM does not perform the actual computation, nor the derivation of results from another table. It is the database engine that does all the hard work.

Seek and You Shall Find

If you have no need for record-by-record navigation, you can retrieve an entire batch of records in one shot:

Jig mapper's query syntax has a slight resemblance:

The equivalent code using the MongoDB mapper:

The find() method searches the users table for records that match the criteria, sorts the result by userID and returns the result as an array of mapper objects. find('visits>3') is different from load('visits>3'). The latter refers to the current $user object. find() does not have any effect on skip() .

Declaring an empty condition, NULL, or a zero-length string as the first argument of find() or load() will retrieve all records. Be sure you know what you're doing - you might exceed PHP's `memory_limit` on large tables or collections

The find() method has the following syntax:

find() returns an array of objects. Each object is a mapper to a record that matches the specified criteria.:

If you need to convert a mapper object to an associative array, use the cast() method:

To retrieve the number of records in a table that match a certain condition, use the count() method.

There's also a select() method that's similar to find() but provides more fine-grained control over fields returned. It has a SQL-like syntax:

Much like the find() method, select() does not alter the mapper object's contents. It only serves as a convenience method for querying a mapped table. The return value of both methods is an array of mapper objects. Using dry() to determine whether a record was found by an of these methods is inappropriate. If no records match the find() or select() criteria, the return value is an empty array.

Keep in mind:

load() hydrates the current mapper object, findone returns a new hydrated mapper object, and find returns an array of hydrated mapper objects.

If you ever want to find out which SQL statements issued directly by your application (or indirectly thru mapper objects) are causing performance bottlenecks, you can do so with a simple:

F3 keeps track of all commands issued to the underlying SQL database driver, as well as the time it takes for each statement to complete - just the right information you need to tweak application performance.

Sometimes It Just Ain't Enough

In most cases, you can live by the comforts given by the data mapper methods we've discussed so far. If you need the framework to do some heavy-duty work, you can extend the SQL mapper by declaring your own classes with custom methods - but you can't avoid getting your hands greasy on some hardcore SQL:

Extending the data mappers in this fashion is an easy way to construct your application's DB-related models.

Pros and Cons

If you're handy with SQL, you'd probably say: everything in the ORM can be handled with old-school SQL queries. Indeed. We can do without the additional event listeners by using database triggers and stored procedures. We can accomplish relational queries with joined tables. The ORM is just unnecessary overhead. But the point is - data mappers give you the added functionality of using objects to represent database entities. As a developer, you can write code faster and be more productive. The resulting program will be cleaner, if not shorter. But you'll have to weigh the benefits against the compromise in speed - specially when handling large and complex data stores. Remember, all ORMS - no matter how thin they are - will always be just another abstraction layer. They still have to pass the work to the underlying SQL engines.

By design, F3's ORMs do not provide methods for directly connecting objects to each other, i.e. SQL joins - because this opens up a can of worms. It makes your application more complex than it should be, and there's the tendency of objects thru eager or lazy fetching techniques to be deadlocked and even out of sync due to object inheritance and polymorphism (impedance mismatch) with the database entities they're mapped to. There are indirect ways of doing it in the SQL mapper, using virtual fields - but you'll have to do this programmatically and at your own risk.

If you are tempted to apply "pure" OOP concepts in your application to represent all your data (because "everything is an object"), keep in mind that data almost always lives longer than the application. Your program may already be outdated long before the data has lost its value. Don't add another layer of complexity in your program by using intertwined objects and classes that deviate too much from the schema and physical structure of the data.

Before you weave multiple objects together in your application to manipulate the underlying tables in your database, think about this: creating views to represent relationships and triggers to define object behavior in the database engine are more efficient. Relational database engines are designed to handle views, joined tables and triggers. They are not dumb data stores. Tables joined in a view will appear as a single table, and Fat-Free can auto-map a view just as well as a regular table. Replicating JOINs as relational objects in PHP is slower compared to the database engine's machine code, relational algebra and optimization logic. Besides, joining tables repeatedly in our application is a sure sign that the database design needs to be audited, and views considered an integral part of data retrieval. If a table cross-references data from another table frequently, consider normalizing your structures or creating a view instead. Then create a mapper object to auto-map that view. It's faster and requires less effort.

Consider this SQL view created inside your database engine:

Your application code becomes simple because it does not have to maintain two mapper objects (one for the projects table and another for users) just to retrieve data from two joined tables:

Tip:Use the tools as they're designed for. Fat-Free already has an easy-to-use SQL helper. Use it if you need a bigger hammer :) Try to seek a balance between convenience and performance. SQL will always be your fallback if you're working on complex and legacy data structures.