Table of Contents


Installation

Installing the AutoCRUD for PHP library is extremely easy. After you've downloaded the package from TPG PHP Scripts you will need to unpack the archive and store all the files somewhere.

Then all you need to do is copy the 'lib' directory, and include the autocrud.php file in your script, and that's all. Your script can then use the AutoCRUD for PHP library. Below is an example of including the library into your script:

<?php
include ('/path/to/lib/autocrud.php');

// now it's possible to use the AutoCRUD for PHP library

?>


Requirements

To use the AutoCRUD for PHP library, your server has to support the following:

It's not possible to use this library with any other database yet. Only MySQL is supported. In the future more databases might be supported, possibly through the use of PDO, but for now it's strictly MySQL only. Don't try to use it with any other database either, because this could cause havoc.


Setting up the library

Before you can use any of the functionality that this library offers, you have to set it up first.

The first step is to create a new instance of the AutoCRUD class, like this:

<?php
include ('/path/to/autocrud.php');

$autocrud = new AutoCRUD():

?>

Now that we have an AutoCRUD object, the next step is to setup the connection to your MySQL database. This can be done using the connect() method, and takes four arguments: the MySQL user, the MySQL password, the database name, and optionally the MySQL host (which defaults to 'localhost'). Here's an example:

<?php
include ('/path/to/autocrud.php');

// Setup AutoCRUD and create connection
$autocrud = new AutoCRUD():
$result = $autocrud->connect ('sa', 'mysecretpassword', 'my_blog', 'localhost');

?>

If everything goes okay, $result will now be set to true. If an error occured (for example the password is incorrect) an error object will be returned. See the example below:

<?php
include ('/path/to/autocrud.php');

// Setup AutoCRUD and create connection
$autocrud = new AutoCRUD():
$result = $autocrud->connect ('sa', 'mysecretpassword', 'my_blog', 'localhost');

if (autocrud_is_error($result)) {
    die ('Unable to establish connection');
}

// ... all went okay

?>

The error object can be used to get more information, but we'll go into this in the 'Handling Errors' article.

Now that we've established a connection there's only one more thing to do: generating all the necessary table objects. This is really easy, and all you have to do is call the generate() method, like this:

<?php
include ('/path/to/autocrud.php');

// Setup AutoCRUD and create connection
$autocrud = new AutoCRUD():
$result = $autocrud->connect ('sa', 'mysecretpassword', 'my_blog', 'localhost');

if (autocrud_is_error($result)) {
    die ('Unable to establish connection');
}

// Generate table objects
$autocrud->generate();

// ... ready to rock and roll

?>

Now everything has been setup, and it is possible to start using the inbuilt CRUD functionality. See the 'Basic CRUD functionality' article for information on using the CRUD functionality.


Including the CRUD definition file

This article should only be read if you want to include the CRUD definition file (which is used to create the table objects) instead of using the generate() method.

Although the generate() method is very easy, it comes at a performance cost. Since your database needs to be inspected at runtime, several queries will be used, which could result in a slower response. During development this is no problem, but if you want to deploy a script, you probably want optimal performance.

That's why it's also possible to include the CRUD definition file, instead of generating it on-the-fly. The first step in including the CRUD definition file is creating the file first. This can be done using the generate() method, like this:

<?php
include ('/path/to/autocrud.php');

// Setup AutoCRUD and create connection
$autocrud = new AutoCRUD():
$result = $autocrud->connect ('sa', 'mysecretpassword', 'my_blog', 'localhost');

if (autocrud_is_error($result)) {
    die ('Unable to establish connection');
}

// Generate CRUD definition file and display it
$autocrud->generate(true);

?>

Note the first argument passed to the generate() method (true). This tells the library that you want to create a CRUD file, and it will return all the CRUD definitions instead of executing them.

You will need to copy the code that is returned, and save it in a file, ending with the .php extension. It's probably wise to name it something like 'crud_definitions.php', but that's entirely up to you.

Now that we have a CRUD definition file, you can include it in your script by using the include_crud() method. The example below demonstrates this:

<?php
include ('/path/to/autocrud.php');

// Setup AutoCRUD and create connection
$autocrud = new AutoCRUD():
$result = $autocrud->connect ('sa', 'mysecretpassword', 'my_blog', 'localhost');

if (autocrud_is_error($result)) {
    die ('Unable to establish connection');
}

// Include the generated CRUD file
$autocrud->include_crud ('path/to/crud_definitions.php');

?>

Now the library no longer needs to inspect the database and only needs to include the CRUD definitions file, which is considerably faster.

Be aware though that you MUST update the CRUD definitions file when you make a change in your database structure. That's why it's highly recommended to use the generate() method during development. 

The library comes with another method called isSetup() to check if the CRUD objects have been setup. This can be used to make that the CRUD objects are generated. See the example below:

<?php

$crud = new AutoCRUD;
$crud->connect ('sa', 'mysecrectpass', 'demo');

// Try to load CRUD definition file
$crud->include_crud ('crud_def.php');

// Did it work?
if ($crud->isSetup() == false) {
    // Generate them on the fly
    $crud->generate();
}

// ... objects should be setup now

?>


Basic CRUD functionality

AutoCRUD for PHP comes with basic CRUD functionality to handle the standard tasks, like inserting a new record.

To use the CRUD functionality all you need to do is call the right method on the right table object. For example, let's say there's a table in your database called 'article'. The article object is then located under the article property of the AutoCRUD object, and to insert a new record you would use the following code:

<?php

// ... Setup AutoCRUD ...

$crud->article->insert ($data);

?>

The same goes for every other table and method.

To learn more about the CRUD functionality, read the articles on each CRUD method (insert, update, delete, select, get). 


Insert

The insert() method can be used to insert a new record into the table, and it needs only one argument: the data that needs to be inserted as an associative array. The example below demonstrates a simple insert:

<?php

// ... Setup AutoCRUD ...

$data = array();
$data['title'] = 'My article title';
$data['description'] = 'This is an example article';
$data['author'] = 'John Smith';
$data['timestamp'] = time();

$result = $crud->article->insert ($data);

?>

If everything goes okay, $result will now contain the ID of the record that was inserted.

The insert() method will automatically check if all the required fields are there. To make a field required, you have to set it to 'NOT NULL' in your database structure. If you want it optional, set it 'NULL'. The insert() method will also check for numeric values. A numeric field will not allow for non-numeric data.

If a field is missing or non-numeric data is passed, an error object is returned. See the 'Handling Errors' article for more information on how to handle these errors.

The insert() method will also prevent SQL injection, so you don't have to escape your data. This is also handled automatically by the library. 


Update

The update() method is used to update an existing record, and it takes two arguments: the updated data (as an associative array) and an optional ID of the record you want to update. It's used in a similar way as the insert() method:

<?php

// ... Setup AutoCRUD ...

$data = array();
$data['title'] = 'Updated title';
$data['description'] = 'The example article is updated';

$result = $crud->article->update ($data, 23);

?>

It will return true on success, and an error on failure (just like the insert() method). Because we're updating a record now, it's possible to leave out certain fields, and you can even leave out required fields. 

If you don't specify the second argument (the ID of the record) all the records will be updated. This probably something you don't want so be careful about this. It's best to always pass a record ID.

It's also possible to specify a custom WHERE clause (and leaving out the second argument), by setting the $where property on the table object, like this:

<?php

// ... Setup AutoCRUD ...

$data = array();
$data['title'] = 'Updated title';
$data['description'] = 'The example article is updated';

$crud->article->where = "author = 'John Smith'";
$result = $crud->article->update ($data);

?>

The where clause will be automatically cleared after the update() method has ran. It's also possible to specify a record ID and use a custom WHERE clause. See the example below:

<?php

// ... Setup AutoCRUD ...

$data = array();
$data['title'] = 'Updated title';
$data['description'] = 'The example article is updated';

$crud->article->where = " AND author = 'John Smith'";
$result = $crud->article->update ($data, 23);

?>

Just like the insert() method, the update() method will also automatically prevent SQL injection. 


Delete

The delete() method is used to delete a record, and takes only one optional argument: the record ID of the record that should be deleted. It's used like this:

<?php

// ... Setup AutoCRUD ...

// $id contains the record ID
$crud->article->delete ($id);

?>

Like the update() method you can also leave out the record ID, and use a custom WHERE clause, using the where property, for example: 

<?php

// ... Setup AutoCRUD ...

$crud->article->where = "title = 'My Article'";
$crud->article->delete ();

?>

That's all there is to the delete() method.

Please note that if you don't specify a custom WHERE clause and don't pass a record ID ALL the records in the table will be deleted! 


Select

The select() method is used to select a list of records. In its simplest form it's used like this:

<?php

// ... Setup AutoCRUD ...

$articles = $crud->article->select();

?>

In the above example all the records from the article table will be selected, and returned as an array of records, with each record being an associative array.

But you might not want to select all the articles, so that's why you can specify a custom WHERE clause, just like with the update() and delete() methods. See the example below:

<?php

// ... Setup AutoCRUD ...

$crud->article->where = "visible = 'yes'"
$articles = $crud->article->select();

?>

It's also possible to set the order of the articles, by setting the orderby property. See the example below:

<?php

// ... Setup AutoCRUD ...

// Order by timestamp, newest first
$crud->article->orderby = "timestamp DESC"
$articles = $crud->article->select();

?>

In the example above all the records selected will be sorted by the timestamp field in descending order.

If you're expecting to get many results, you might want to paginate the results. This is no problem, and all you need to do is set three paging properties. See the example below:

<?php

// ... Setup AutoCRUD ...

// Enable paging
$crud->article->paging = true;
$crud->article->perpage = 20;
$crud->article->currentpage = $_GET['page'];

$articles = $crud->article->select();

?>

In the above example paging has enabled, and it will return 20 records per page. The current page is set by getting the 'page' value from the $_GET variable. If you pass an invalid page number it will default to page 1. 

Finally, it's also possible to have the articles returned in a special way. Instead of returning the records as a regular array, you can specify a 'key' and each record will be set under that key. See the example below:

<?php

// ... Setup AutoCRUD ...

$articles = $crud->article->select('articleid');

?>

In the example above each article will now be set under its own articleid. This is very rarely needed though, and it's mainly used by the library itself. 


Get

The get() method is used to get a single record, and takes one optional argument: the record ID. It will return the record as an associative array, and it's like this:

<?php

// ... Setup AutoCRUD ...

$article = $crud->article->get (23);

?>

In the above example the record with record ID 23 will be retrieved. If you try to fetch an invalid record, false will be returned.

You can also specify a custom WHERE clause to get a single record, in the same way as with the select() method. 


Handling relationships between tables

One of the greatest aspects of the AutoCRUD for PHP library is the ability to automatically handle relationships between tables. For example, let's consider two tables with the following structure:

CREATE TABLE `article` (
  `articleid` smallint(5) unsigned NOT NULL auto_increment,
  `title` varchar(255) NOT NULL default '',
  `content` text,
  `datetimestamp` int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (`articleid`)
) TYPE=MyISAM AUTO_INCREMENT=0 ;

CREATE TABLE `comment` (
  `commentid` bigint(20) unsigned NOT NULL auto_increment,
  `title` varchar(25) default '',
  `author` varchar(255) default NULL,
  `article` smallint(6) NOT NULL default '0',
  PRIMARY KEY  (`commentid`),
  KEY `article` (`article`)
) TYPE=MyISAM AUTO_INCREMENT=0

There's a clear relationship between the article and comment table. Each comment belongs to a certain article, and one article can have multiple comments.

Now let's suppose you want to get a list of articles, and each article should have its comments selected as well. Without this library this wouldn't be a very easy task, and involves writing some tedious code to handle it. But with the AutoCRUD for PHP library this is no problem.

The first setup is setting up a relationship between two tables, using the addRelationship() method. The example below demonstrates this:

<?php

// ... setup AutoCRUD

$crud-> ;comment->addRelationship ($crud->article, 'article', 'articleid', 'many-to-one');

?>

As you can see the addRelationship() method takes four arguments: the CRUD object of the other table, the field in the first table, the field in the second table, and finally the relationship type.

There are four different relationship types: 

Each relationship type is discussed in seperate sub articles.

Now that we've setup a relationship between two tables, you only need to use the join() method when selecting records to get the related records. The example below demonstrates this:

<?php

// ... setup AutoCRUD

// Add relationship
$crud->comment->addRelationship ($crud->article, 'article', 'articleid', 'many-to-one');

// Get articles and comments
$crud->article->join ('comment');
$articles = $crud->article->select();

?>

In the above example a list of articles will be selected, and for each article all its comments will also be selected. 

Read more about each relationship type in the sub articles. 


One-to-One

The most basic relationship type is the One-to-One relationship, and it's used to get two related records. The example below demonstrates the one-to-one relationship:

<?php

// ... setup AutoCRUD

// Add relationship
$crud->author->addRelationship ($crud->article, 'authorid', 'author', 'one-to-one');

// Get articles and authors
$crud->article->join ('author');
$articles = $crud->article->select();

?>

In the above example, $articles will contain the following array:

Array
(
    [0] => Array
        (
            [articleid] => 1
            [title] => Article title
            [description] => This is an article
            [author] => Array
                (
                    [authorid] => 4
                    [name] => John Smith
                    [email] => j.smith@example.com
                )
            [content] => Content of the article goes here
        )
    [1] => Array
        (
            [articleid] => 2
            [title] => Second article
            [description] => This is the second article
            [author] => Array
                (
                    [authorid] => 2
                    [name] => Perry Bloom
                    [email] => p.bloom@example.com
                )
            [content] => Content of the second article
        )
)

As you can see each article has automatically had its author retrieved from the database.


One-to-Many

The Ony-to-Many relatationship is used when a record in one table has multiple related records in another table, like an article record with multiple comment records. The one-to-many relationship can be setup in two ways. See the example below:

<?php

// ... setup AutoCRUD

// First way
$crud->comment->addRelationship ($crud->article, 'article', 'articleid', 'many-to-one');

// Second way
$crud->article->addRelationship ($crud->comment, 'articleid', 'article', 'one-to-many');

?>

It doesn't matter what way you use, since both are exactly the same, and you only have to use one.

Now that the relationship has been setup it, you can use the join() method to get related records, like this:

<?php

// ... setup AutoCRUD

// First way
$crud->comment->addRelationship ($crud->article, 'article', 'articleid', 'many-to-one');

// Second way
$crud->article->addRelationship ($crud->comment, 'articleid', 'article', 'one-to-many');

// Get articles and comments
$crud->article->join ('comment');
$articles = $crud->article->select();

?>

In the above example, $articles will be contain the following array: 

Array
(
    [0] => Array
        (
            [articleid] => 1
            [title] => Article title
            [description] => This is an article
            [content] => Content of the article goes here
            [comment] => Array
                (
                    [0] => Array
                        (
                            [commentid] => 3
                            [content] => This is a comment!
                            [author] => John Smith
                        )
                    [1] => Array
                        (
                            [commentid] => 6
                            [content] => Another comment
                            [author] => Jerry
                        )
                    [2] => Array
                        (
                            [commentid] => 8
                            [content] => Fifth comment
                            [author] => Tom
                        )
                )
        )
    [1] => Array
        (
            [articleid] => 2
            [title] => Second article
            [description] => This is the second article
            [content] => Content of the second article
            [comment] => Array
                (
                    [0] => Array
                        (
                            [commentid] => 1
                            [content] => First comment ever!
                            [author] => Caleb
                        )
                    [1] => Array
                        (
                            [commentid] => 2
                            [content] => Also a comment
                            [author] => Dylan
                        )
                    [2] => Array
                        (
                            [commentid] => 7
                            [content] => fourth comment
                            [author] => Noah
                        )
                )
        )
)

As you can see each article now has an item called 'comment' which is an array of all the comments.

It's also possible to select a list of comments, and for each comment get the article it belongs to. This works just like the One-to-One relationship. 


Many-to-Many

The Many-to-Many relationship is probably the most difficult relationship to handle, but with the AutoCRUD for PHP library this is no problem.

Unlike other relationship types, you have to setup up two relationships, because a many-to-many relationship involves three tables: two data tables, and a "connector" table. The example below demonstrates setting up the relationships. 

<?php

// ... setup AutoCRUD

$crud->article2category->addRelationship ($crud->article, 'article', 'articleid', 'many-to-many');
$crud->article2category->addRelationship ($crud->category, 'category', 'categoryid', 'many-to-many');

?>

In the example above we've setup a relationship between the article2category table and the article table, and the article2categorytable and the category table. As you might've guess, the article2category table is the connector table, and the article and category tables are the data tables.

Now that we've setup the relationships we only have to use the join() method again to select related records. Let's suppose we want to select a list of articles, and for each articles get the related categories. All it takes is the following code:

<?php

// ... setup AutoCRUD

$crud->article2category->addRelationship ($crud->article, 'article', 'articleid', 'many-to-many');
$crud->article2category->addRelationship ($crud->category, 'category', 'categoryid', 'many-to-many');

// Get articles and categories
$crud->article->join ('category');
$articles = $crud->article->select();

?>

In the example above, $articles will now contain the following array:

Array
(
    [0] => Array
        (
            [articleid] => 1
            [title] => Article title
            [description] => This is an article
            [content] => Content of the article goes here
            [category] => Array
                (
                    [0] => Array
                        (
                            [categoryid] => 1
                            [title] => Some Category

                        )
                    [1] => Array
                        (
                            [categoryid] => 2
                            [title] => Another Category

                        )
                )
        )
    [1] => Array
        (
            [articleid] => 2
            [title] => Second article
            [description] => This is the second article
            [content] => Content of the second article
            [category] => Array
                (
                    [0] => Array
                        (
                            [categoryid] => 2
                            [title] => Another Category

                        )
                )
        )
)

As you can see, we've selected the related categories by using the connector table. Likewise, it's also possible to get a list of categories, and for each category get the related articles. 


Child-Parent

The Child-Parent relationship is used to define a relationship within a table. A good example would be a script that supports categories, but also sub-categories. A 'parent' field in the category table would make it possible to create sub-categories, and a child-parent relationship can be setup like this:

<?php

// ... setup AutoCRUD

$crud->category->addRelationship ($crud->category, 'parent', 'categoryid', 'child-parent');

?>

As you can see the second CRUD object is the same CRUD object we're using. 

Now that we've setup a relationship, we can use the join() method to select a list of categories and for each category gets its children:

<?php

// ... setup AutoCRUD

$crud->category->addRelationship ($crud->category, 'parent', 'categoryid', 'child-parent');

// Get categories and children
$crud->category->join ('category');
$category = $crud->category->select();

?>

In the above example, $category will contain the following array:

Array
(
    [0] => Array
        (
            [categoryid] => 1
            [title] => Some Category
            [children] => Array
                (
                    [0] => Array
                        (
                            [categoryid] => 3
                            [title] => Sub Category
                            [parent] => 1
                        )
                    [1] => Array
                        (
                            [categoryid] => 5
                            [title] => Another Sub Category
                            [parent] => 1
                        )
                )
        )
    [1] => Array
        (
            [categoryid] => 2
            [title] => Another category
            [children] => Array
                (
                    [0] => Array
                        (
                            [categoryid] => 4
                            [title] => Sub Category Two
                            [parent] => 2
                        )
                    [1] => Array
                        (
                            [categoryid] => 6
                            [title] => Another Sub Category Two
                            [parent] => 2
                        )
                )
        )
               
)

As you can see an array of children is selected for each category. 

Only direct children will be selected. The library does (not yet) support selecting a full tree of records. This may be added in the future.

 

Preventing SQL Injection

Although the basic CRUD functionality automatically prevents SQL injection attacks (unless you use a WHERE clause), the library comes with two inbuilt methods to prevent SQL injection.

The first method, called quote(), is a simple function that will escape all the "dangerous" characters and adds quotes around the value. See the example below:

<?php

// ... setup AutoCRUD

$data = "This is some 'very dangerous' data, which should be escaped";

$safe_data = $crud->quote ($data);

// $safe_data now contains "'This is some \'very dangerous\' data, which should be escaped'"

?>

The second method, called quoteInto(), is used to prepare full statements, and is very useful for long queries. The below example demonstrates this method:

<?php

// ... setup AutoCRUD

// Raw SQL query
$sql = "INSERT INTO article (title, description, timestamp) VALUES (?, ?, ?)";

// Dangerous and unescaped data
$data = array('My article title', 'This is an article', time());

// Safe SQL query with escaped data
$sql_safe = $crud->quoteInto($sql, $data);

// $sql_safe now contains "INSERT INTO article (title, description, timestamp) VALUES ('My article title', 'This is an article', '6436346532')"

?>

It's highly recommend you ALWAYS use the quote() or quoteInto() mtehod whenever writing custom SQL or when using a custom WHERE or ORDER BY clause.


Advanced Functionality

The AutoCRUD for PHP library offers a few more advanced features, such as an (experimental) ActiveRecord implementation, table aliases and more.

Read the sub-articles of this article to learn about each individual feature. 


Automatically handling table prefixes

If your script needs to support table prefixes, which is usual amongst scripts that are distributed, you can use the setTablePrefix() method to automatically set the table prefix, and still be able to use the table names without having to worry about the prefix. This means you won't have to change anything in your script whenever the prefix changes. The example below demonstrates this:

<?php

$crud = new AutoCRUD();
$crud->connect ('sa', '', 'my_db');

// Set table prefix, BEFORE using generate() or include_crud()
$crud->setTablePrefix ('myscript_');

// Create table objects
$crud->generate();

// The tables are now available under two names, with and without the prefix
// for example:

$articles = $crud->article->select();

// OR

$articles = $crud->myscript_article->select();

?>

As you see by setting the table prefix, the library has automatically created two table objects (which in reality point to the same table object within the library).

You can also use both table names when using the join() method, for example:

<?php

// ... setup AutoCRUD and set table prefix (myscript_)

$crud->comment->addRelationship ($crud->article, 'article', 'articleid', 'many-to-one');

// Get comments and articles
$crud->comment->join ('article');
$comments = $crud->comment->select();

?>

Even though the actual table is called 'myscript_article', you can continue to use 'article' in your script. This makes it extremely easy to change table prefixes without having to worry about changing anything in your script.


Creating table aliases

Just like with table prefixes, it's also possible to create your own table aliases, by using the addAlias() method. See the example below:

<?php

// ... setup AutoCRUD

$crud->article->addAlias ('my_table');

// The article CRUD object is now accessible under 'my_table', e.g.
$articles = $crud->my_table->select();

?>

In the example above we've created a new alias called 'my_table', which can now be used to access the article table, and can do everything the article object can.

It's also possible to use aliases with the join() method, for example:

<?php

// ... setup AutoCRUD and set table prefix (myscript_)

$crud->article->addAlias('my_table');

$crud->comment->addRelationship ($crud->my_table, 'article', 'articleid', 'many-to-one');

// Get comments and articles
$crud->comment->join ('my_table');
$comments = $crud->comment->select();

?>

In the example above we created the 'my_table' alias, and then used that to setup the relationship with the comment table and used it with the join() table.  

Aliases are mainly used to automatically setup table prefixes, but the functionality is there if you need it (though I don't really know what for). 


ActiveRecord

The AutoCRUD for PHP library also includes an experimental version of the ActiveRecord pattern. It isn't completely finished yet though, and only supports the basic things. For example, if you select the related records when using an ActiveRecord, all the related records will be returned, but as an array of items (like normal) and not as an array of objects (like it should with the ActiveRecord pattern). But this will probably be added in the future.

To setup a new ActiveRecord, all you have to do is create an instance of the AutoCRUD_ActiveRecord class, and pass a CRUD object to it, like so:

<?php

// ... setup AutoCRUD

$article = new AutoCRUD_ActiveRecord ($crud->article);

?>

Now that we've got an ActiveRecord, you can set its properties, like a normal object. See the example below:

<?php

// ... setup AutoCRUD

$article = new AutoCRUD_ActiveRecord ($crud->article);

$article->title = 'My article';
$article->description = 'This is an article';
$article->author = 'John Smith';

?>

Finally, to save the record you need to call the save() method which will handle everything for you:

<?php

// ... setup AutoCRUD

$article = new AutoCRUD_ActiveRecord ($crud->article);

$article->title = 'My article';
$article->description = 'This is an article';
$article->author = 'John Smith';

$article->save();

?>

It's also possible to load a record first, by using the load() method and passing the record ID as the first argument. See the following example:

<?php

// ... setup AutoCRUD

$article = new AutoCRUD_ActiveRecord ($crud->article);

// Load article #45
$article->load ('45');

// Make some changes
$article->title = 'My new title';

// And save the changes
$article->save();

?>

As you can see in the example above the save() method is also used to update a record.

If you've made some changes, but want to undo them, you can use the reset() method, which will return all the default values:

<?php

// ... setup AutoCRUD

$article = new AutoCRUD_ActiveRecord ($crud->article);

// Load article #45
$article->load ('45');

// Make some changes
$article->title = 'My new title';

// Undo changes
$article->reset();

?>

Finally, it's also possible to delete a record, by calling the delete() method, like this:

<?php

// ... setup AutoCRUD

$article = new AutoCRUD_ActiveRecord ($crud->article);

// Load article #45
$article->load ('45');

// And delete it
$article->delete();

?>


Handling Errors

Whenever something unexpected happens, the AutoCRUD for PHP library will return an error object. To check whether a variable contains an error, you should use the inbuilt 'autocrud_is_error' function, like this:

<?php

$crud = new AutoCRUD();
$result = $crud->connect ('sa', '', 'my_db');

// Error occured?
if (autocrud_is_error($result) == true) {
    die ('Error occured');
}

// ...

?>

The error object that is returned can be used to get additional information about the error, and it supports two methods: getCode() and getMessage().

The getCode() method will return an error code, usually something like 'invalid-user', 'missing-fields', or something similar. See the error list appendix for all the error codes.

The getMessage() method will return a small information message on the error and can be used to present the user with additional information.

See the example below for a demonstration of the getCode() and getMessage() methods:

<?php

$crud = new AutoCRUD();
$result = $crud->connect ('sa', '', 'my_db');

// Error occured?
if (autocrud_is_error($result) == true) {
    $error = $result->getCode() . ': ' . $result->getMessage();
    echo $error;
    die();
}

// ...

?>

In some cases there may also be extra error codes and messages. These can be used by passing an index number to the getCode() and getMessage() methods, like this:

<?php

$crud = new AutoCRUD();
$result = $crud->connect ('sa', '', 'my_db');

// Error occured?
if (autocrud_is_error($result) == true) {
    $error = $result->getCode() . ': ' . $result->getMessage() . '<br />';
    $error .= $result->getCode(2) . ': ' . $result->getMessage(2) . '<br />';
    echo $error;
    die();
}

// ...

?>

In the example above the main and secodary codes and messages will be printed.

It's also possible to retrieve the last error without having to use the return value, by using the static AutoCRUD_Error::get_last_errno() function function and the static AutoCRUD_Error::get_last_errmsg() function. These will return the same thing as the getCode() and getMessage() functions, and are used in the same way:

<?php

$crud = new AutoCRUD();
$result = $crud->connect ('sa', '', 'my_db');

// Error occured?
if (autocrud_is_error($result) == true) {
    $error = AutoCRUD_Error::get_last_errno() . ': ' . AutoCRUD_Error::get_last_errmsg() . '<br />';
    echo $error;
    die();
}

// ...

?>

It's also possible to get a complete array of all the errors that have happened, using the static AutoCRUD_Error::stack() function.

In the future the AutoCRUD for PHP library might switch to using Exceptions, but for now this is the most acceptable way of returning errors. 


Inbuilt support for unique errors

The AutoCRUD for PHP library has an inbuilt method for handling "unique errors". Unique errors are errors that will occur when you've created a UNIQUE index in a table. To check for a unique error, you should use the unique_error() method, like this:

<?php

// ... setup AutoCRUD

$crud->article->insert (array('title' => 'My article', 'filename' => 'should-be-unique'));

if ($crud->article->unique_error() == true) {
    echo 'Another article with this filename already exists';
    die();
}

?>

In the above example the 'filename' field must be unique, and the unique_error() method is used to check whether another article with the filename we specified already exists.

If you've got multiple UNIQUE indexes in your table, you can also pass the name of the index you want to check as the first argument for the unique_error() method. See the example below:

<?php

// ... setup AutoCRUD

$crud->article->insert (array('title' => 'My article', 'filename' => 'should-be-unique'));

if ($crud->article->unique_error('filename') == true) {
    echo 'Another article with this filename already exists';
    die();
}

?>

The unique_error() method is very useful for checking if another article with a particular value already exists, but you must have a UNIQUE index for this. If you don't have a UNIQUE index, you'll have to manually check (using the get() method). 


Appendix: Error Codes

This appendix contains a complete list of all the error codes used in the AutoCRUD for PHP library:


Comments / Suggestions

If you have any comments or suggestions, feel free to leave them in the Support Forums, available at http://forums.pallettgroup.com.

We listen to all the suggestions that are given, but we do not make any promise to follow every suggestion. Only the suggestions that we think have any use will be implemented.


License

The AutoCRUD for PHP library is licensed under the MIT license, which means you can do whatever you want with it, as long as you retain all the copyright notices. The full license can be viewed below:

Copyright (c) 2006 Dennis Pallett

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


Credits

The AutoCRUD for PHP library has been developed entirely by Dennis Pallett, who can be contacted at dennis [AT] pallettgroup.com [DOT] com.