PHP Classes

File: example.php

Recommend this page to a friend!
  Classes of Corey W.   MySQL Database & Model Classes   example.php   Download  
File: example.php
Role: Example script
Content type: text/plain
Description: Example Usage
Class: MySQL Database & Model Classes
Manipulate MySQL database table records as objects
Author: By
Last change:
Date: 15 years ago
Size: 1,261 bytes
 

Contents

Class file image Download
<?php
require_once('models/agency.php');

$db = new Agency_Model;

// Get all results from database and echo them

foreach($db->find_all() as $record) {
   
?>
<p>Record <?php echo $record->id; ?>: <?php echo $record->name; ?></p>
    <?php
}

// Insert new row into database from form submission.
// If you use the same input names and you use in your database it's as easy as this:
$db->save($_POST);

// That probably doesn't look to safe, but in the Database method "save",
// it escapes and sanitizes everything automatically.

// Then the same to update a row
$db->id = intval($_POST['record_id']);
$db->save($_POST);

// Same as
$db = new Agency_Model(2);
$db->save($_POST);

// Since the id is set before saving, it updates that row instead of inserting a new one.

// Find all with parameters
// ORDER BY, WHERE, COLUMNS, LIMIT
$records = $db->find_all('name ASC', 'id IN(1, 3, 4, 6, 7)', 'name, id, title', '0, 10');
// Which results in "SELECT name, id, title FROM agency WHERE id IN(1, 3, 4, 6, 7) ORDER BY name ASC LIMIT 0,10"

// Of course you can also use the database class w/out a model.
$db = new Database;
$db->select('agency');
$records = $db->get();
// or just get first record
$record = $db->get_first();