function fix_amputees($type_id = 0)
 {
     set_time_limit(240);
     $types = get_entities_by_type_name('type');
     foreach ($types as $type) {
         if ($type_id == 0 || $type_id == $type['id']) {
             $tables = get_entity_tables_by_type($type['id'], false);
             // lets not cache - this could be used right after a type is setup
             foreach ($tables as $table) {
                 // changed from e.* to e.id ... test for speed improvements.
                 $q = "SELECT e.id,type.name as type_name FROM entity AS e LEFT JOIN {$table} AS t ON e.id = t.id, entity AS type WHERE e.type = " . $type['id'] . " AND t.id IS NULL AND e.type = type.id";
                 $r = db_query($q, 'Unable to grab amputees.');
                 while ($row = mysql_fetch_array($r, MYSQL_ASSOC)) {
                     $q = 'INSERT INTO ' . $table . ' (id) VALUES (' . $row['id'] . ')';
                     $this->queries[] = $q;
                     if (empty($this->stats[$type['name']])) {
                         $this->stats[$type['name']] = array();
                     }
                     if (empty($this->stats[$type['name']][$table])) {
                         $this->stats[$type['name']][$table] = 0;
                     }
                     $this->stats[$type['name']][$table]++;
                     db_query($q, 'Unable to add prosthetic record.');
                 }
                 mysql_free_result($r);
             }
         }
     }
 }
	<title>Reason: Delete Headless Chickens</title>
	</head>
	<body>
	<h1>Delete Headless Chickens</h1>
	<?php 
if (empty($_POST['do_it'])) {
    ?>
	<form method="post">
	<p>Headless chickens are records in Reason tables that do not correspond to a record in the master entity table. This script will delete all of the headless chickens.</p>
	<p>This script is a useful tool to keep the Reason DB from getting too crufty. This script probably should be run regularly. In fact, it should probably be made into a cron job at some point.</p>
	<input type="submit" name="do_it" value="Run the script" />
	</form>
	<?php 
} else {
    connectDB(REASON_DB);
    $tables = get_entities_by_type_name('content_table');
    $to_delete = array();
    foreach ($tables as $t_info) {
        if (!empty($t_info['name']) && !empty($t_info['state']) && $t_info['state'] == 'Live') {
            $table = $t_info['name'];
            $q = "SELECT t.id FROM {$table} AS t LEFT JOIN entity AS e ON e.id = t.id WHERE e.id IS NULL";
            $r = db_query($q, 'Unable to grab headless chickens.');
            while ($row = mysql_fetch_array($r, MYSQL_ASSOC)) {
                $to_delete[$table][] = $row['id'];
            }
            if (!empty($to_delete[$table])) {
                $q = 'DELETE FROM ' . $table . ' WHERE id IN (' . implode(', ', $to_delete[$table]) . ')';
                $queries[] = $q . '<br /><br />';
                db_query($q, 'Unable to delete headless chickens.');
            }
        }