Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help parsing an inserting an xml document

Status
Not open for further replies.

sd0t1

IS-IT--Management
Mar 14, 2007
131
US
Here's the task. I need to read the xml file below into a database. One row per defendant. However the xml file doesn't necessarily put all the defendants data on one row. The way I know how to parse xml with simplexml generated the following. 3 rows per defendant and now i'm trying to figure a way to merge the necessary data per row into one row, or somehow end up with one row per defendant.


Event Type: system
Event Time: 10:42:49
Length: 00:00:01
Start/Stop: Start Cap:10h42m48s.asf on 2011-04-19
Case Number:
Case Type:
Defendant 1:
Defendant 2:
Counselor 1:
Counselor 2:


Event Type: case
Event Time: 10:42:49
Length: 00:00:01
Start/Stop:
Case Number: GS534164
Case Type: GSPH
Defendant 1: Jeff Dearing
Defendant 2:
Counselor 1: Mike Engle
Counselor 2:


Event Type: system
Event Time: 10:59:12
Length: 00:16:24
Start/Stop: Stop Cap
Case Number:
Case Type:
Defendant 1:
Defendant 2:
Counselor 1:
Counselor 2:


Here is the actual xml file, I only used one defendant for the example above.

[/code]
And here is the xml file that I'm reading and trying to generate one row per defendant.
Code:
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet href="log.xsl" type="text/xsl"?>

<log>
	<header>
		<title><![CDATA[2011-04-19-Turner]]></title>
		<state><![CDATA[Tn]]></state>
		<county><![CDATA[Davision]]></county>
		<courtroom display="true"><![CDATA[]]></courtroom>
		<courtSystem><![CDATA[General Sessions]]></courtSystem>
		<department><![CDATA[Division 5]]></department>
		<judge><![CDATA[Diane Turner]]></judge>
		<clerk><![CDATA[Mike Walker]]></clerk>
		<bailiff><![CDATA[]]></bailiff>
		<logSuffix><![CDATA[Turner]]></logSuffix>
		<logDate><![CDATA[2011-04-19]]></logDate>
		<tapeNumber display="false"><![CDATA[]]></tapeNumber>
	</header>
	<event type="system" time="10:42:49" vcrTime="00:00:00" digitalTime="00:00:01" cvf="10h42m48s_00_00_01.cvf">
		<text><![CDATA[Start Cap:10h42m48s.asf on 2011-04-19]]></text>
	</event>
	<event type="case" time="10:42:49" vcrTime="00:00:00" digitalTime="00:00:01" cvf="10h42m48s_00_00_01.cvf">
		<case>
			<caseId><![CDATA[GS534164]]></caseId>
			<caseType><![CDATA[GSPH]]></caseType>
			<party1><![CDATA[Jeff Dearing]]></party1>
			<party2><![CDATA[]]></party2>
			<counsel1><![CDATA[Mike Engle]]></counsel1>
			<counsel2><![CDATA[]]></counsel2>
		</case>
	</event>
	<event type="system" time="10:59:12" vcrTime="00:00:00" digitalTime="00:16:24" cvf="10h42m48s_00_16_24.cvf">
		<text><![CDATA[Stop Cap]]></text>
	</event>
	<event type="system" time="11:15:50" vcrTime="00:00:00" digitalTime="00:00:01" cvf="11h15m49s_00_00_01.cvf">
		<text><![CDATA[Start Cap:11h15m49s.asf on 2011-04-19]]></text>
	</event>
	<event type="case" time="11:15:50" vcrTime="00:00:00" digitalTime="00:00:01" cvf="11h15m49s_00_00_01.cvf">
		<case>
			<caseId><![CDATA[GS534491]]></caseId>
			<caseType><![CDATA[GSPH]]></caseType>
			<party1><![CDATA[James Guest]]></party1>
			<party2><![CDATA[]]></party2>
			<counsel1><![CDATA[Mike Engle]]></counsel1>
			<counsel2><![CDATA[]]></counsel2>
		</case>
	</event>
	<event type="system" time="11:57:14" vcrTime="00:00:00" digitalTime="00:41:25" cvf="11h15m49s_00_41_25.cvf">
		<text><![CDATA[Stop Cap]]></text>
	</event>
	<event type="system" time="12:02:25" vcrTime="00:00:00" digitalTime="00:00:00" cvf="12h02m25s_00_00_00.cvf">
		<text><![CDATA[Start Cap:12h02m25s.asf on 2011-04-19]]></text>
	</event>
	<event type="case" time="12:02:26" vcrTime="00:00:00" digitalTime="00:00:01" cvf="12h02m25s_00_00_01.cvf">
		<case>
			<caseId><![CDATA[GS532494]]></caseId>
			<caseType><![CDATA[GSPH]]></caseType>
			<party1><![CDATA[Jeremy Johnson]]></party1>
			<party2><![CDATA[]]></party2>
			<counsel1><![CDATA[Robert Turner]]></counsel1>
			<counsel2><![CDATA[]]></counsel2>
		</case>
	</event>
	<event type="system" time="12:33:26" vcrTime="00:00:00" digitalTime="00:31:01" cvf="12h02m25s_00_31_01.cvf">
		<text><![CDATA[Stop Cap]]></text>
	</event>
	<event type="system" time="12:55:49" vcrTime="00:00:00" digitalTime="00:00:00" cvf="12h55m49s_00_00_00.cvf">
		<text><![CDATA[Start Cap:12h55m49s.asf on 2011-04-19]]></text>
	</event>
	<event type="case" time="12:55:49" vcrTime="00:00:00" digitalTime="00:00:00" cvf="12h55m49s_00_00_00.cvf">
		<case>
			<caseId><![CDATA[GS534424]]></caseId>
			<caseType><![CDATA[GSPH]]></caseType>
			<party1><![CDATA[Samuel Lee & Johnathon Abernathy]]></party1>
			<party2><![CDATA[Lacy Lyles]]></party2>
			<counsel1><![CDATA[Mike Engle & Barry Gearon]]></counsel1>
			<counsel2><![CDATA[Kyle Parks]]></counsel2>
		</case>
	</event>
	<event type="system" time="01:33:24" vcrTime="00:00:00" digitalTime="00:37:35" cvf="12h55m49s_00_37_35.cvf">
		<text><![CDATA[Stop Cap]]></text>
	</event>
</log>

Hears the script that reads it into the database.
Code:
$xmlstr = file_get_contents($file); 	
$phLog = new SimpleXMLElement($xmlstr); 
foreach($phLog->header as $headerInfo)
{

		$hquery = "INSERT INTO ph_headers (`id`, `title`, `department`, `judge`, `clerk`, `logDate`) VALUES ('', '$headerInfo->title', '$headerInfo->department', '$headerInfo->judge', '$headerInfo->clerk', '$headerInfo->logDate')";
		mysql_query($hquery)or die(mysql_error());
		$hid = mysql_insert_id();
}
foreach($phLog->event as $eventInfo)
{

		$caseId = $eventInfo->case->caseId;
		$caseType = $eventInfo->case->caseType;
		$party1 = $eventInfo->case->party1;
		$party2 = $eventInfo->case->party2;
		$counsel1 = $eventInfo->case->counsel1;
		$counsel2 = $eventInfo->case->counsel2;
		
		$dquery = "INSERT INTO ph_detail (`id`, `hid`, `caseId`, `caseType`, `party1`, `party2`, `counsel1`, `counsel2`, `length`, `startTime`, `stopTime`, `asfFileName`, `path`, `link`) VALUES ('', '$hid', '$caseId', '$caseType', '$party1', '$party2', '$counsel1', '$counsel2', '$eventInfo[digitalTime]', '$eventInfo->text', '$eventInfo->text', '$asfFileName', '$dp', '$link')";
		mysql_query($dquery)or die(mysql_error());

}

Please someone, how would you do this?
Parse this xml and insert pertinent data into one row per defendant.

Thanks for any help.
 
as i see this the entity structure should be like this

case 1->m defendants 1->m counselors

i.e. any particular case may have 1 or more defendants.
any particular defendant may have 1 or more counsel.

correct?
 
These hearing are all for lower courts (misdemeanors) so these are actually one to one. One defendant per case but you are correct for the attorneys. It would be rare but possible.

Now what is more likely is, one defendant and multiple cases. However they are usually listed in one field separated by a comma.

From the data in red, here's what I need to pull out and create a single row.

section 1:
start/stop:

Section 2:
Case Number:
Defendant 1:
Defendant 2:
Counselor 1:
Counselor 2:

Section 3:
Length: 00:16:24

I'm not sure if it's best try to parse the xml in a way where I only end up with one row per 3 sections, or try and read all three rows into the database and then do some sort of database clean up.

Here is my code that reads the directories.
Code:
<?php 
require('Connections/user_login.php'); 
function ListFiles($dir) 
{

    if($dh = opendir($dir)) 
	{

        $folders = Array();
        $inner_folders = Array();

        while($file = readdir($dh)) 
		{
			
            if($file != "." && $file != ".." && $file[0] != '.') 
			{
				
               
				   if(is_dir($dir . "/" . $file)) 
				   {
						$inner_folders = ListFiles($dir . "/" . $file);
						
						if(is_array($inner_folders)) $folders = array_merge($folders, $inner_folders); 
						
					} 
					else 				
					{
						array_push($folders, $dir . "/" . $file);
					}
            }
        }

        closedir($dh);
		 return $folders;
		
		
    }
}

// Work Environment  $dirpath = "\\\\crim10048\\attachments$\\"; 
$dirpath = "C:\AppServ\[URL unfurl="true"]www\psi\files";[/URL]  // Home Environment 
foreach (ListFiles($dirpath) as $key => $file)
{
    
	$x = substr($file,-4,4);
					switch ($x)
					{
						case ".asf" :	
									$path = $file;
									$asfFileName = basename($path);
									$asfSize = filesize($file);
									$dp = dirname($path);
									$dp = substr($dp,25);
									/*echo $asfSize."<br />";
									echo $asfFileName."<br />";
									echo $dp."<br />";*/
									break;
						case ".xml" :
									
									echo $asfSize;
									echo $asfFileName."<br />";
									echo $dp."<br />";
									$xmlstr = file_get_contents($file);     
$phLog = new SimpleXMLElement($xmlstr); 
foreach($phLog->header as $headerInfo)
{

        $hquery = "INSERT INTO ph_headers (`id`, `title`, `department`, `judge`, `clerk`, `logDate`) VALUES ('', '$headerInfo->title', '$headerInfo->department', '$headerInfo->judge', '$headerInfo->clerk', '$headerInfo->logDate')";
        mysql_query($hquery)or die(mysql_error());
        $hid = mysql_insert_id();
}
foreach($phLog->event as $eventInfo)
{

        $caseId = $eventInfo->case->caseId;
        $caseType = $eventInfo->case->caseType;
        $party1 = $eventInfo->case->party1;
        $party2 = $eventInfo->case->party2;
        $counsel1 = $eventInfo->case->counsel1;
        $counsel2 = $eventInfo->case->counsel2;
        
        $dquery = "INSERT INTO ph_detail (`id`, `hid`, `caseId`, `caseType`, `party1`, `party2`, `counsel1`, `counsel2`, `length`, `startTime`, `stopTime`, `asfFileName`, `path`, `link`) VALUES ('', '$hid', '$caseId', '$caseType', '$party1', '$party2', '$counsel1', '$counsel2', '$eventInfo[digitalTime]', '$eventInfo->text', '$eventInfo->text', '$asfFileName', '$dp', '$link')";
        mysql_query($dquery)or die(mysql_error());

}

									break;
								
					}	
					
	
} 

?>
 
hopefully this will give you a headstart.

Code:
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

$xml = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet href="log.xsl" type="text/xsl"?>

<log>
    <header>
        <title><![CDATA[2011-04-19-Turner]]></title>
        <state><![CDATA[Tn]]></state>
        <county><![CDATA[Davision]]></county>
        <courtroom display="true"><![CDATA[]]></courtroom>
        <courtSystem><![CDATA[General Sessions]]></courtSystem>
        <department><![CDATA[Division 5]]></department>
        <judge><![CDATA[Diane Turner]]></judge>
        <clerk><![CDATA[Mike Walker]]></clerk>
        <bailiff><![CDATA[]]></bailiff>
        <logSuffix><![CDATA[Turner]]></logSuffix>
        <logDate><![CDATA[2011-04-19]]></logDate>
        <tapeNumber display="false"><![CDATA[]]></tapeNumber>
    </header>
    <event type="system" time="10:42:49" vcrTime="00:00:00" digitalTime="00:00:01" cvf="10h42m48s_00_00_01.cvf">
        <text><![CDATA[Start Cap:10h42m48s.asf on 2011-04-19]]></text>
    </event>
    <event type="case" time="10:42:49" vcrTime="00:00:00" digitalTime="00:00:01" cvf="10h42m48s_00_00_01.cvf">
        <case>
            <caseId><![CDATA[GS534164]]></caseId>
            <caseType><![CDATA[GSPH]]></caseType>
            <party1><![CDATA[Jeff Dearing]]></party1>
            <party2><![CDATA[]]></party2>
            <counsel1><![CDATA[Mike Engle]]></counsel1>
            <counsel2><![CDATA[]]></counsel2>
        </case>
    </event>
    <event type="system" time="10:59:12" vcrTime="00:00:00" digitalTime="00:16:24" cvf="10h42m48s_00_16_24.cvf">
        <text><![CDATA[Stop Cap]]></text>
    </event>
    <event type="system" time="11:15:50" vcrTime="00:00:00" digitalTime="00:00:01" cvf="11h15m49s_00_00_01.cvf">
        <text><![CDATA[Start Cap:11h15m49s.asf on 2011-04-19]]></text>
    </event>
    <event type="case" time="11:15:50" vcrTime="00:00:00" digitalTime="00:00:01" cvf="11h15m49s_00_00_01.cvf">
        <case>
            <caseId><![CDATA[GS534491]]></caseId>
            <caseType><![CDATA[GSPH]]></caseType>
            <party1><![CDATA[James Guest]]></party1>
            <party2><![CDATA[]]></party2>
            <counsel1><![CDATA[Mike Engle]]></counsel1>
            <counsel2><![CDATA[]]></counsel2>
        </case>
    </event>
    <event type="system" time="11:57:14" vcrTime="00:00:00" digitalTime="00:41:25" cvf="11h15m49s_00_41_25.cvf">
        <text><![CDATA[Stop Cap]]></text>
    </event>
    <event type="system" time="12:02:25" vcrTime="00:00:00" digitalTime="00:00:00" cvf="12h02m25s_00_00_00.cvf">
        <text><![CDATA[Start Cap:12h02m25s.asf on 2011-04-19]]></text>
    </event>
    <event type="case" time="12:02:26" vcrTime="00:00:00" digitalTime="00:00:01" cvf="12h02m25s_00_00_01.cvf">
        <case>
            <caseId><![CDATA[GS532494]]></caseId>
            <caseType><![CDATA[GSPH]]></caseType>
            <party1><![CDATA[Jeremy Johnson]]></party1>
            <party2><![CDATA[]]></party2>
            <counsel1><![CDATA[Robert Turner]]></counsel1>
            <counsel2><![CDATA[]]></counsel2>
        </case>
    </event>
    <event type="system" time="12:33:26" vcrTime="00:00:00" digitalTime="00:31:01" cvf="12h02m25s_00_31_01.cvf">
        <text><![CDATA[Stop Cap]]></text>
    </event>
    <event type="system" time="12:55:49" vcrTime="00:00:00" digitalTime="00:00:00" cvf="12h55m49s_00_00_00.cvf">
        <text><![CDATA[Start Cap:12h55m49s.asf on 2011-04-19]]></text>
    </event>
    <event type="case" time="12:55:49" vcrTime="00:00:00" digitalTime="00:00:00" cvf="12h55m49s_00_00_00.cvf">
        <case>
            <caseId><![CDATA[GS534424]]></caseId>
            <caseType><![CDATA[GSPH]]></caseType>
            <party1><![CDATA[Samuel Lee & Johnathon Abernathy]]></party1>
            <party2><![CDATA[Lacy Lyles]]></party2>
            <counsel1><![CDATA[Mike Engle & Barry Gearon]]></counsel1>
            <counsel2><![CDATA[Kyle Parks]]></counsel2>
        </case>
    </event>
    <event type="system" time="01:33:24" vcrTime="00:00:00" digitalTime="00:37:35" cvf="12h55m49s_00_37_35.cvf">
        <text><![CDATA[Stop Cap]]></text>
    </event>
</log>
XML;
//remove the CDATA


class courtCase extends baseClass {
	
	public $caseID;
	public $caseType;
	public $party1;
	public $party2;
	public $counsel1;
	public $counsel2;
	public $startTime;
	public $stopTime;
	public $primary = 'id';
	public $table = 'courtCase';
	public $fields = array('id','caseID','caseType','party1','party2','counsel1','counsel2','startTime','stopTime');
	
	public function __construct(){
		parent::__construct();
	}
	
	public function saveNew(){
		foreach(array('caseType','defendant1', 'defendant2','counsel1','counsel2','startTime','stopTime') as $field):
			if(!empty($this->$field)):
				$this->$field = $this->removeCData($this->$field);
			endif;
		endforeach;
		parent::saveNew();
	}
	public function setStartTime($time){
		$this->startTime = (string) $time;
	}
	public function setStopTime($time){
		$this->stopTime = (string) $time;
	}
	private function removeCData($string){
		$pattern = '/<\!\[CDATA\[(.*?)\]\]\>/imsx';
		preg_match($pattern, $string, $match);
		return (!empty($match[1]) ? $match[1] : $string);
	}
}

class baseClass{
	
	public function __construct(){
		require_once	'dbConnect.php';
	}

	public function load($array){
		if (is_object($array)):
			$array = get_object_vars($array);
		endif;
		foreach($this->fields as $field):
			if (isset($array[$field])):
				$this->$field = (string) $array[$field];
			else:
				$this->$field = NULL;
			endif;
		endforeach;
	}

	public function save(){
		if (empty($this->{$this->primary})):
			$result = $this->saveNew();
			if( $result == true ):
				return $this->getPrimary();
			else:
				return false;
			endif;
		else:
			$result = $this->update();
			return $result;
		endif;
	}
	
	public function saveNew(){
		$sql = <<<SQL
INSERT 
INTO {$this->table}
(
	{$this->getFields()}
)
VALUES
(
	{$this->getValues()}
)
SQL;
		$this->lastQuery = $sql;
		$r = mysql_query($sql);		
		if ($r):
			$this->{$this->primary} = mysql_insert_id();
			return true;
		else:
			$this->error = mysql_error();
			return false;
		endif;
	}
	
	public function update(){
		$sql = <<<SQL
UPDATE {$this->table}
SET
	{$this->getUpdate()}
WHERE
	{$this->primary} = '{$this->getPrimary()}'
SQL;
		$this->lastQuery = $sql;
		$r = mysql_query($sql);		
		if ($r):
			return true;
		else:
			$this->error = mysql_error();
			return false;
		endif;
	}
	
	public function delete(){
		if($this->getPrimary() < 1) return false;
		$sql = <<<SQL
DELETE
FROM {$this->table} 
WHERE 
	{$this->primary} = '{$this->getPrimary()}'
SQL;
		$this->lastQuery = $sql;
		$r = mysql_query($sql);
		return $r;
	}
	
	public function getPrimary(){
		if (	isset($this->primary) && 
				!empty($this->primary) && 
				!empty($this->{$this->primary})):
			return $this->{$this->primary};
		else:
			return null;
		endif;
	}
	
	private function getFields(){
		return implode(',',$this->fields);
	}
	
	private function getValues(){
		$return = array();
		foreach($this->fields as $field):
			$return[] = "'" . $this->escape($this->$field) . "'";
		endforeach;
		return implode(',', $return);
	}
		
	private function getUpdate(){
		$return = array();
		foreach($this->fields as $field):
			$return[] = "$field = '" . $this->escape($this->$field) ."'"; 
		endforeach;
		return implode(',',$return);
	}
	
	private function escape($string){
		return mysql_real_escape_string($string);
	}
}
$s  = new SimpleXMLElement($xml, LIBXML_NOCDATA);
echo '<pre>';
foreach($s->event as $key=>$event):
	$attributes = $event->attributes();
		if($attributes->type == 'system'):
			if(strpos($event->text, 'Start Cap') !== false):
				$startTime = $attributes->time;
			elseif(strpos($event->text, 'Stop Cap') !== false):
				$m->setStopTime($attributes->time);
				$m->setStartTime($startTime);
				$startTime = null;
				$m->save();
			endif; 
		elseif($attributes->type == 'case' ):
			$m = new courtCase;
			$m->load($event->case);	
		endif;
endforeach;
?>
 
Wow, thanks Jpadie.

I really appreciate this. It's going to take me a couple days to decipher all this, but I've learned so much over the years by deciphering examples you've given me and others on this board.

I'm going to try and comment your code and maybe that will tell if I understand it like I should. I'll say up front that I haven't jumped into OOP as much as I would have liked to, maybe this is my chance.

Have a great evening and thanks again.
 
not much to the code I provided. the essence of the solution is to create a class that reflects the properties of each logical entity. in this case you have only one logical entity and that is the case itself.

ideally the court would provide unique references for the defendants and their counsel and you would then have a nice searchable entity schema that you could deploy. However without 'uniqueness', you will never know whether one 'John Smith' is the same as another. so it makes (mostly) sense to treat the data as flat.

so ... the first class just sets up the properties of your object. By creating a couple of further properties ($primary, $table and $fields), we can also 'profile' the data to make it easy to perform operations on the data.

The class inherits from and extends a base class which has some methods that are useful for saving and deleting database records. I use a class similar to this for everything I do, and all entity classes inherit from this base.

It's neat because it keeps all db interaction nicely segmented from business logic.

back to the main class ...
the removeCData function should not be needed as I have specified that CData sections should be 'expanded' in the creation of the simple XML object. It's in there for belt and braces.

The procedural code at the end takes the XML input and parses it into a simpleXML Object. I then assume that the objects ALWAYS go in the order

* system start cap
* case details
* system stop cap

and in making that assumption I have a viable method to traverse the XML tree. If the assumption is incorrect then we will need to come up with another algorithm that matches the shape of the data.


 

ok, I was pulled away from this project but now I'm back.

I see what you mean about the logical entities. I think I may need the actual .asf file to be the logical entity. Here’s why, please tell me what you think. While in general sessions court there is always one defendant to each case. However for these preliminary hearings it’s not uncommon for 3 codefendants to share the same preliminary hearing. It will be listed in the xml file separated by commas “GS123, GS234, GS345”.

So that’s why I think we may need to use the .asf file as the logical entity and give it characteristics of, cases, defendants, counselors, also each hearing will have a path to the .asf and a file name that is used to generate the link to the .asf when someone searches for a case number.

Here is one of my other concerns. Here is some background on the actual process to create a preliminary hearing.
These particular PH's (preliminary hearings) are recorded via a 3rd party vendor and their system (there system generates the event types on the xml file that you’re helping me parse).

How they go about this is to start and stop the recording equipment between each case. This is how we get the “start, case and stop event types” for each unique hearing on the xml file. Well the problem I ran into that caused the script to error is when this common situation happens.
When a case(s) and defendant(s) is about to be heard the clerk hits the ‘Record’ button which generates the “Start event type”, then when the hearing begins they enter the data entry (case#, defendant, counselors), this generates the “Case event type” in the xml file. Then when they finish the hit stop and the “Stop event” is generated.

Right now the code is looking for those three events each time. Well what frequently happens is the clerks Start, then Stop and then start again, hear the case and stop. So the first instance is just a start and stop event without a case event so it crashed the script. I cannot figure out how to modify the code for this scenario.

Now I want to try and walk you through my understanding of the code you wrote in hopes that you’ll correct any errors and steer me toward the right direction.

I understand declaring variables

I don’t understand why $primary is set to “ID”, shouldn’t it be set to a integer value?
Code:
public $primary = 'id';

Is this $fields variable an array of columns in the database? So if I add a column than I need to add it hear also to be looped through later in one of the database functions below.
Code:
public $fields = array('id','caseId','caseType','party1','party2','counsel1','counsel2','digitalTime','startTime','stopTime');

This is confusing to me because it’s a function called saveNew() and it references a parent::saveNew() too. It appears to be creating an array of all the data fields (should it be party1 instead of defendant1) and looping through each one and calling the removeCData() function.
Code:
public function saveNew(){
        foreach(array('caseType','caseId','defendant1', 'defendant2','counsel1','counsel2','digitalTime','startTime','stopTime') as $field):
            if(!empty($this->$field)):
                $this->$field = $this->removeCData($this->$field);
            endif;
        endforeach;
        parent::saveNew();
    }

These seem pretty self explanatory. It appears these just set the start and stop time to strings and remove CData does exactly that, it removes the encapsulating CData tag from the values.
Code:
public function setStartTime($time){
        $this->startTime = (string) $time;
    }
    public function setStopTime($time){
        $this->stopTime = (string) $time;
    }
    private function removeCData($string){
        $pattern = '/<\!\[CDATA\[(.*?)\]\]\>/imsx';
        preg_match($pattern, $string, $match);
        return (!empty($match[1]) ? $match[1] : $string);
    }

Base Class
I understand the construct loads the connection settings
Code:
public function __construct(){
        require_once    'Connections/user_login.php';
    }

Ok, here is where I really start drawing blanks… This appears to be checking an array for values and converting them to strings unless they are empty. But I don’t see where this function is ever called.
Code:
public function load($array){
        if (is_object($array)):
            $array = get_object_vars($array);
        endif;
        foreach($this->fields as $field):
            if (isset($array[$field])):
                $this->$field = (string) $array[$field];
            else:
                $this->$field = NULL;
            endif;
        endforeach;
    }

I’m just lost looking at this
Code:
public function save(){
        if (empty($this->{$this->primary})):
            $result = $this->saveNew();
            if( $result == true ):
                return $this->getPrimary();
            else:
                return false;
            endif;
        else:
            $result = $this->update();
            return $result;
        endif;
    }

These database functions are cool as heck… I saw what they did, but don’t know how. PLEASE help me understand how they work. I see why you use these in everything.
Code:
    public function saveNew(){
        $sql = <<<SQL
INSERT 
INTO {$this->table}
(
    {$this->getFields()}
)
VALUES
(
    {$this->getValues()}
)
SQL;
        $this->lastQuery = $sql;
        $r = mysql_query($sql);        
        if ($r):
            $this->{$this->primary} = mysql_insert_id();
            return true;
        else:
            $this->error = mysql_error();
            return false;
        endif;
    }
    
    public function update(){
        $sql = <<<SQL
UPDATE {$this->table}
SET
    {$this->getUpdate()}
WHERE
    {$this->primary} = '{$this->getPrimary()}'
SQL;
        $this->lastQuery = $sql;
        $r = mysql_query($sql);        
        if ($r):
            return true;
        else:
            $this->error = mysql_error();
            return false;
        endif;
    }
    
    public function delete(){
        if($this->getPrimary() < 1) return false;
        $sql = <<<SQL
DELETE
FROM {$this->table} 
WHERE 
    {$this->primary} = '{$this->getPrimary()}'
SQL;
        $this->lastQuery = $sql;
        $r = mysql_query($sql);
        return $r;
    }

This seems to just get an id if there is one.
Code:
public function getPrimary(){
        if (    isset($this->primary) && 
                !empty($this->primary) && 
                !empty($this->{$this->primary})):
            return $this->{$this->primary};
        else:
            return null;
        endif;
    }

This separates fields with a ‘.
Code:
private function getFields(){
        return implode(',',$this->fields);
    }
I didn’t understand the next two getValues and getUpdate
Code:
private function getValues(){
        $return = array();
        foreach($this->fields as $field):
            $return[] = "'" . $this->escape($this->$field) . "'";
        endforeach;
        return implode(',', $return);
    }
        
    private function getUpdate(){
        $return = array();
        foreach($this->fields as $field):
            $return[] = "$field = '" . $this->escape($this->$field) ."'"; 
        endforeach;
        return implode(',',$return);
    }

Ok, for the last part. Is this only to get the attributes from each event type? Does this code do more? I tried to modify it to capture the ‘digitalTime’ attribute which I need for the database but was unsuccessful. Where does the $m-> come from? Note the code I inserted that didn’t work “$digitalTime = $attributes->digitalTime;”
Code:
$s  = new SimpleXMLElement($xml, LIBXML_NOCDATA);
echo '<pre>';
foreach($s->event as $key=>$event):
    $attributes = $event->attributes();
        if($attributes->type == 'system'):
            if(strpos($event->text, 'Start Cap') !== false):
                $startTime = $attributes->time;
            elseif(strpos($event->text, 'Stop Cap') !== false):
                $m->setStopTime($attributes->time);
                $m->setStartTime($startTime);
                $startTime = null;
				$digitalTime = $attributes->digitalTime;
                $m->save();
            endif; 
        elseif($attributes->type == 'case' ):
            $m = new courtCase;
            $m->load($event->case);    
        endif;
endforeach;


Again, thanks for any help you can provide.
 
hopefully this code with comments will help explain.

I do not think that an asf file should be the core object but perhaps it could be an entity. it seems to me that the main unitary piece of information that you have is the case itself.
if so I would use the case as the core object and create a method called addASFFile. pass in the xml to that method and then use the code above to parse the file and create the sub-entities. apply a foreign key to each of the sub-entities (being the primary key of the core case object).

I note your comments about the abortive start/stops. this is easily remedied by checking for the presence of a $m variable at the point that we get to the stop event. if none exists it means that there is no actual case data. so we just skip it.

Code:
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);

$xml = <<<XML
<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet href="log.xsl" type="text/xsl"?>

<log>
    <header>
        <title><![CDATA[2011-04-19-Turner]]></title>
        <state><![CDATA[Tn]]></state>
        <county><![CDATA[Davision]]></county>
        <courtroom display="true"><![CDATA[]]></courtroom>
        <courtSystem><![CDATA[General Sessions]]></courtSystem>
        <department><![CDATA[Division 5]]></department>
        <judge><![CDATA[Diane Turner]]></judge>
        <clerk><![CDATA[Mike Walker]]></clerk>
        <bailiff><![CDATA[]]></bailiff>
        <logSuffix><![CDATA[Turner]]></logSuffix>
        <logDate><![CDATA[2011-04-19]]></logDate>
        <tapeNumber display="false"><![CDATA[]]></tapeNumber>
    </header>
    <event type="system" time="10:42:49" vcrTime="00:00:00" digitalTime="00:00:01" cvf="10h42m48s_00_00_01.cvf">
        <text><![CDATA[Start Cap:10h42m48s.asf on 2011-04-19]]></text>
    </event>
    <event type="case" time="10:42:49" vcrTime="00:00:00" digitalTime="00:00:01" cvf="10h42m48s_00_00_01.cvf">
        <case>
            <caseId><![CDATA[GS534164]]></caseId>
            <caseType><![CDATA[GSPH]]></caseType>
            <party1><![CDATA[Jeff Dearing]]></party1>
            <party2><![CDATA[]]></party2>
            <counsel1><![CDATA[Mike Engle]]></counsel1>
            <counsel2><![CDATA[]]></counsel2>
        </case>
    </event>
    <event type="system" time="10:59:12" vcrTime="00:00:00" digitalTime="00:16:24" cvf="10h42m48s_00_16_24.cvf">
        <text><![CDATA[Stop Cap]]></text>
    </event>
    <event type="system" time="11:15:50" vcrTime="00:00:00" digitalTime="00:00:01" cvf="11h15m49s_00_00_01.cvf">
        <text><![CDATA[Start Cap:11h15m49s.asf on 2011-04-19]]></text>
    </event>
    <event type="case" time="11:15:50" vcrTime="00:00:00" digitalTime="00:00:01" cvf="11h15m49s_00_00_01.cvf">
        <case>
            <caseId><![CDATA[GS534491]]></caseId>
            <caseType><![CDATA[GSPH]]></caseType>
            <party1><![CDATA[James Guest]]></party1>
            <party2><![CDATA[]]></party2>
            <counsel1><![CDATA[Mike Engle]]></counsel1>
            <counsel2><![CDATA[]]></counsel2>
        </case>
    </event>
    <event type="system" time="11:57:14" vcrTime="00:00:00" digitalTime="00:41:25" cvf="11h15m49s_00_41_25.cvf">
        <text><![CDATA[Stop Cap]]></text>
    </event>
    <event type="system" time="12:02:25" vcrTime="00:00:00" digitalTime="00:00:00" cvf="12h02m25s_00_00_00.cvf">
        <text><![CDATA[Start Cap:12h02m25s.asf on 2011-04-19]]></text>
    </event>
    <event type="case" time="12:02:26" vcrTime="00:00:00" digitalTime="00:00:01" cvf="12h02m25s_00_00_01.cvf">
        <case>
            <caseId><![CDATA[GS532494]]></caseId>
            <caseType><![CDATA[GSPH]]></caseType>
            <party1><![CDATA[Jeremy Johnson]]></party1>
            <party2><![CDATA[]]></party2>
            <counsel1><![CDATA[Robert Turner]]></counsel1>
            <counsel2><![CDATA[]]></counsel2>
        </case>
    </event>
    <event type="system" time="12:33:26" vcrTime="00:00:00" digitalTime="00:31:01" cvf="12h02m25s_00_31_01.cvf">
        <text><![CDATA[Stop Cap]]></text>
    </event>
    <event type="system" time="12:55:49" vcrTime="00:00:00" digitalTime="00:00:00" cvf="12h55m49s_00_00_00.cvf">
        <text><![CDATA[Start Cap:12h55m49s.asf on 2011-04-19]]></text>
    </event>
    <event type="case" time="12:55:49" vcrTime="00:00:00" digitalTime="00:00:00" cvf="12h55m49s_00_00_00.cvf">
        <case>
            <caseId><![CDATA[GS534424]]></caseId>
            <caseType><![CDATA[GSPH]]></caseType>
            <party1><![CDATA[Samuel Lee & Johnathon Abernathy]]></party1>
            <party2><![CDATA[Lacy Lyles]]></party2>
            <counsel1><![CDATA[Mike Engle & Barry Gearon]]></counsel1>
            <counsel2><![CDATA[Kyle Parks]]></counsel2>
        </case>
    </event>
    <event type="system" time="01:33:24" vcrTime="00:00:00" digitalTime="00:37:35" cvf="12h55m49s_00_37_35.cvf">
        <text><![CDATA[Stop Cap]]></text>
    </event>
</log>
XML;
//remove the CDATA


class courtCase extends baseClass {
    
	//create properties that match the database fields
    public $caseID;
    public $caseType;
    public $party1;
    public $party2;
    public $counsel1;
    public $counsel2;
    public $startTime;
    public $stopTime;
	
	//create an array of all the database fields for use in db write operations
	public $fields = array('id','caseID','caseType','party1','party2','counsel1','counsel2','startTime','stopTime');
    
	//creat some other useful properties for use in db write operations
	//note that the record's primary key is held in $this->id.
	//the $this->primary property helps the db write know which field to use as a primary key
    public $primary = 'id';
    public $table = 'courtCase';
    
	
	/**
	 * constructor. does nothing except fire the parent constructor
	 * @return 
	 */
    public function __construct(){
        parent::__construct();
    }
    
	/**
	 * this is an overriden class.  it fires BEFORE the parent saveNew.  
	 * most of the time we would not need such an overrider but in this case we 
	 * want to make really sure that the data fields do not contain any cData code.  They should not, but this is belt and braces
	 * 
	 * @return 
	 */
    public function saveNew(){
        foreach(array('caseType','defendant1', 'defendant2','counsel1','counsel2','startTime','stopTime') as $field):
            if(!empty($this->$field)):
                $this->$field = $this->removeCData($this->$field);
            endif;
        endforeach;
        parent::saveNew();
    }
	
	/**
	 * this is just a setter function that forces the incoming information to a string.
	 * 
	 * @param object $time
	 * @return 
	 */
    public function setStartTime($time){
        $this->startTime = (string) $time;
    }
	
	/**
	 * as per the startTime
	 * 
	 * @param object $time
	 * @return 
	 */
    public function setStopTime($time){
        $this->stopTime = (string) $time;
    }
	
	/**
	 * this is an internal helper function to cleanse data of CData segments.
	 * it is called from the saveNew method only.
	 * 
	 * @param object $string
	 * @return 
	 */
    private function removeCData($string){
        $pattern = '/<\!\[CDATA\[(.*?)\]\]\>/imsx';
        preg_match($pattern, $string, $match);
        return (!empty($match[1]) ? $match[1] : $string);
    }
}

/**
 * this class automates create, update and delete operations on database entities
 * it is inherited by all other classes that represent database records
 * 
 */
class baseClass{
    
	/**
	 * constructor that just makes sure that the database is properly connected
	 * 
	 * @return 
	 */
    public function __construct(){
        require_once    'dbConnect.php';
    }

	/**
	 * this method facilitates the loading of data into the object
	 * it first transforms the incoming data into an array
	 * then looks at the $fields method (set in the inheritor) and
	 * iterates that checking that there is an incoming variable and setting that.
	 * therefore you can pass an array of lots of extra data (like for example, the submit buttons) 
	 * and they will simply be ignored.
	 * 
	 * @param object $array
	 * @return 
	 */
    public function load($array){
        if (is_object($array)):
            $array = get_object_vars($array);
        endif;
        foreach($this->fields as $field):
            if (isset($array[$field])):
                $this->$field = (string) $array[$field];
            else:
                $this->$field = NULL;
            endif;
        endforeach;
    }

	/**
	 * this function is a despatcher.  it determines whether the save should be
	 * an update or an insert based on the value of the primary key
	 * 
	 * @return 
	 */
    public function save(){
        if (empty($this->{$this->primary})):
            $result = $this->saveNew();
            if( $result == true ):
                return $this->getPrimary();
            else:
                return false;
            endif;
        else:
            $result = $this->update();
            return $result;
        endif;
    }
    
	
	/** 
	 * this method assembles an insert query from the object's properties 
	 * and returns a true/false combo depending on whether the insert went ok.
	 * the last query executed is always stored in $lastQuery for debugging
	 * @return 
	 */
    public function saveNew(){
        $sql = <<<SQL
INSERT 
INTO {$this->table}
(
    {$this->getFields()}
)
VALUES
(
    {$this->getValues()}
)
SQL;
        $this->lastQuery = $sql;
        $r = mysql_query($sql);        
        if ($r):
            $this->{$this->primary} = mysql_insert_id();
            return true;
        else:
            $this->error = mysql_error();
            return false;
        endif;
    }
    
	/**
	 * this method assembles and executes an update query from the object properties.
	 * it returns a true/false combo depending on success
	 * @return 
	 */
    public function update(){
        $sql = <<<SQL
UPDATE {$this->table}
SET
    {$this->getUpdate()}
WHERE
    {$this->primary} = '{$this->getPrimary()}'
SQL;
        $this->lastQuery = $sql;
        $r = mysql_query($sql);        
        if ($r):
            return true;
        else:
            $this->error = mysql_error();
            return false;
        endif;
    }
    
	/**
	 * this method assembles a delete query from the object properties
	 * it returns a true/false combo
	 * @return 
	 */
    public function delete(){
        if($this->getPrimary() < 1) return false;
        $sql = <<<SQL
DELETE
FROM {$this->table} 
WHERE 
    {$this->primary} = '{$this->getPrimary()}'
SQL;
        $this->lastQuery = $sql;
        $r = mysql_query($sql);
        return $r;
    }
    
	/**
	 * this is a helper function that is sometimes useful to determine what the primary key of the 
	 * current record might be.
	 * it returns null if there is not a primary key set or if $this-primary is not set.
	 * @return 
	 */
    public function getPrimary(){
        if (    isset($this->primary) && 
                !empty($this->primary) && 
                !empty($this->{$this->primary})):
            return $this->{$this->primary};
        else:
            return null;
        endif;
    }
    
	/**
	 * this method is used to return a comma delimited list of fields to use in an insert query
	 * 
	 * @return 
	 */
    private function getFields(){
        return implode(',',$this->fields);
    }
    
	/**
	 * this method returns a comma delimeted enquoted escaped set of values to use in an insert query
	 * @return 
	 */
    private function getValues(){
        $return = array();
        foreach($this->fields as $field):
            $return[] = "'" . $this->escape($this->$field) . "'";
        endforeach;
        return implode(',', $return);
    }
       
	/**
	 * update queries are more computationally complex to create dynamically
	 * so we need to have a special method for creating the sql string
	 * this method simply creates the 'field="value",field2=value2' string needed 
	 * for an update query
	 * 
	 * @return 
	 */
    private function getUpdate(){
        $return = array();
        foreach($this->fields as $field):
            $return[] = "$field = '" . $this->escape($this->$field) ."'"; 
        endforeach;
        return implode(',',$return);
    }
    
	/**
	 * this method simply calls mysql_real_escape_string on the input argument.
	 * 
	 * @param object $string
	 * @return 
	 */
    private function escape($string){
        return mysql_real_escape_string($string);
    }
}


$s  = new SimpleXMLElement($xml, LIBXML_NOCDATA);
echo '<pre>';
foreach($s->event as $key=>$event):
    $attributes = $event->attributes();
	
		/*
		 * to avoid overwriting values the order of the ifs etc is quite important.
		 * logically the order of the xml goes
		 * startime
		 * case date
		 * stoptime
		 * 
		 * for the first item we capture only the starttime.  at this point no object exists
		 * then hopefully we hit a case type.
		 * then create the object ($m) and load the event data into the object
		 * 
		 * then the third item will be a Stop Cap and we hit the second limb of the first test
		 * and set the stop time and start time properties of $m.
		 * then reset the internal counter of $startTime and then 
		 * save the record.
		 * 
		 * the loop then restarts
		 */
        if($attributes->type == 'system'):
            if(strpos($event->text, 'Start Cap') !== false):
                $startTime = $attributes->time;
            elseif(strpos($event->text, 'Stop Cap') !== false):
				if(!$m) continue;
                $m->setStopTime($attributes->time);
                $m->setStartTime($startTime);
                $startTime = null;
                $m->save();
				unset($m);
            endif; 
        elseif($attributes->type == 'case' ):
            $m = new courtCase;
			//NOTE THAT THIS IS WHERE THE BASECLASS LOAD() METHOD IS USED 
			//TO LOAD IN EXTERNAL DATA TO THE OBJECT
            $m->load($event->case);    
        endif;
endforeach;
?>
 
Ok, I'm slowly figuring out SOME of how this code works section by section as I attempt to modify it. I really appreciate your help and I promise I'm trying to figure this out myself before I post. I'm just too new to OOP and right when I think I've made some sense of the code I find a section that I just can't figure out. But I am glad to be getting thrust into OOP because I know it's going to benefit me down the road.

It does work like I need it to. Now I'm having trouble integrating it with the rest of my code and having it continue to work.

here's the overview of how I need to integrate it.

I'm scanning hundreds of directories and sub directories. Each directory has at one .asf file per defendant and a single .xml file that tells which defendant goes to which .asf.
the first thing on every xml file is the header information such as judge, clerk, courtroom, department and date.

then it loops through each actual defendant and details their hearing data.

What I'm trying to do is separate the header information into one table called 'ph_headers' then put the detailed data in another table called 'ph_detail' and link them with a foreign key called 'hid' which is just the coresponding id from the ph_header.

So my ph_headers table is as such:
id title judge clerk logDate
3 GS court Turner Joe Smith 2011-1-1

My ph_detail would then be as such: (all for the one header above)
id hid caseId caseType party1 counsel1 asfFileName path asfSize
1 3 GS123456 PH Joe Blow attorney someasf.asf basename(file) filesize(file)
2 3 GS123434 PH Some Guy attorney another.asf basename(file) filesize(file)
3 3 GS123442 PH Joe Blow attorney someasf.asf basename(file) filesize(file)


One problem is getting the last three fields in the database because they are not on the xml file.
What I was doing is, just runing the following code and using mysql_insert_id to the 'hid'.
Code:
foreach($phLog->header as $headerInfo)
{

		$hquery = "INSERT INTO ph_headers (`id`, `title`, `department`, `judge`, `clerk`, `logDate`) VALUES ('', '$headerInfo->title', '$headerInfo->department', '$headerInfo->judge', '$headerInfo->clerk', '$headerInfo->logDate')";
		mysql_query($hquery)or die(mysql_error());
		$hid = mysql_insert_id();
}
foreach($phLog->event as $eventInfo)
{

		$caseId = $eventInfo->case->caseId;
		$caseType = $eventInfo->case->caseType;
		$party1 = $eventInfo->case->party1;
		$party2 = $eventInfo->case->party2;
		$counsel1 = $eventInfo->case->counsel1;
		$counsel2 = $eventInfo->case->counsel2;
		
		$dquery = "INSERT INTO ph_detail (`id`, `hid`, `caseId`, `caseType`, `party1`, `party2`, `counsel1`, `counsel2`, `digitalTime`, `startTime`, `stopTime`, `asfFileName`, `path`, `link`) VALUES ('', '$hid', '$caseId', '$caseType', '$party1', '$party2', '$counsel1', '$counsel2', '$eventInfo[digitalTime]', '$eventInfo->text', '$eventInfo->text', '$asfFileName', '$dp', '$link')";
		mysql_query($dquery)or die(mysql_error());

Since I'm now implementing your code, which parses the xml beautifully. I'm trying to figure how to handle the header info and the file size, name and path data.

Here are the different ways I've tried. This is all my code for this entire project so you can see the whole thing.
This is the main page
Code:
<?php 
ini_set('display_errors', true);
error_reporting(E_ALL);
require('Connections/user_login.php'); 
include('jpxmltodb.php');

 $dirpath = "\\\\crim10048\\attachments$\\"; // Work Environment 
 // see function page for ListFiles function
foreach (ListFiles($dirpath) as $key => $file)
{
    
	$x = substr($file,-4,4);
					switch ($x)
					{
						case ".asf" :	
									$path = $file;
									$asfFileName = basename($path);
									$asfSize = filesize($file);
									$dp = dirname($path);
									$dp = substr($dp,25);
									break;
						case ".xml" :
									
									$xml = file_get_contents($file);
									$s  = new SimpleXMLElement($xml, LIBXML_NOCDATA);
									// I know here I need to be trying to duplicate your class, but I couldn't figure it out.
									foreach($phLog->header as $headerInfo)
									{
											echo "<br />Title:   ".$headerInfo->title;
											echo "<br />Department:   ".$headerInfo->department;
											echo "<br />Judge:   ".$headerInfo->judge;
											echo "<br />Clerk:   ".$headerInfo->clerk;
											echo "<br />Date:   ".$headerInfo->logDate;
											echo "<br />";
									}
									$hquery = "INSERT INTO ph_headers (`id`, `title`, `department`, `judge`, `clerk`, `logDate`) 
									VALUES ('', '$headerInfo->title', '$headerInfo->department', '$headerInfo->judge', '$headerInfo->
									clerk', '$headerInfo->logDate')";
									mysql_query($hquery)or die(mysql_error());
									$hid = mysql_insert_id();
																	
									
									echo '<pre>';
									foreach($s->event as $key=>$event):
										$attributes = $event->attributes();
											if($attributes->type == 'system'):
												if(strpos($event->text, 'Start Cap') !== false):
													$startTime = $attributes->time;
												elseif(strpos($event->text, 'Stop Cap') !== false):
													if(!$m) continue;
													$m->setStopTime($attributes->time);
													$m->setStartTime($startTime);
													$startTime = null;
													$digitalTime = $attributes->digitalTime;
													$m->setDigitalTime($digitalTime);
													$asfFileName = $asfFileName;// trying to use variables from the .asf case above
													$asfSize = $asfSize;// trying to use variables from the .asf case above
													$path = $path;// trying to use variables from the .asf case above
													$m->save();													
													unset($m);
												endif; 
											elseif($attributes->type == 'case' ):
												$m = new courtCase;
												//NOTE THAT THIS IS WHERE THE BASECLASS LOAD() METHOD IS USED 
												//TO LOAD IN EXTERNAL DATA TO THE OBJECT

												// tried to load external data here but couldn't figure this out either. 
												$m->load($event->case);    
											endif;
									endforeach;
									break;
								
					}	
					
	
} 

?>

this is the functions page

Code:
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);


function ListFiles($dir) 
{
    if($dh = opendir($dir)) 
	{
        $folders = Array(); 
        $inner_folders = Array();
        while($file = readdir($dh)) 
		{			
            if($file != "." && $file != ".." && $file[0] != '.') 
			{              
				   if(is_dir($dir . "/" . $file)) 
				   {
						$inner_folders = ListFiles($dir . "/" . $file);						
						if(is_array($inner_folders)) $folders = array_merge($folders, $inner_folders); 						
					} 
					else 				
					{
						array_push($folders, $dir . "/" . $file);
					}
            }
        }
        closedir($dh);
		return $folders;	
    }
}

class courtCase extends baseClass {
    
    //create properties that match the database fields
    public $caseId;
	public $hid;
    public $caseType;
    public $party1;
    public $party2;
    public $counsel1;
    public $counsel2;
	public $digitalTime;
    public $startTime;
    public $stopTime;	
	public $asfFileName;
	public $path;
	public $asfSize;
	
    
    //create an array of all the database fields for use in db write operations
    public $fields = array('id', 'hid','caseId','caseType','party1','party2','counsel1','counsel2','digitalTime','startTime','stopTime', 'asfFileName', 'path', 'asfSize');
    
    //creat some other useful properties for use in db write operations
    //note that the record's primary key is held in $this->id.
    //the $this->primary property helps the db write know which field to use as a primary key
    public $primary = 'id';
    public $table = 'ph_detail';
    
    
    /**
     * constructor. does nothing except fire the parent constructor
     * @return 
     */
    public function __construct(){
        parent::__construct();
    }
    
    /**
     * this is an overriden class.  it fires BEFORE the parent saveNew.  
     * most of the time we would not need such an overrider but in this case we 
     * want to make really sure that the data fields do not contain any cData code.  They should not, but this is belt and braces
     * 
     * @return 
     */
    public function saveNew(){
        foreach(array('caseType','defendant1', 'defendant2','counsel1','counsel2', 'digitalTime', 'startTime','stopTime', 'asfFileName', 'path', 'asfSize') as $field):
            if(!empty($this->$field)):
                $this->$field = $this->removeCData($this->$field);
            endif;
        endforeach;
        parent::saveNew();
    }
    
    /**
     * this is just a setter function that forces the incoming information to a string.
     * 
     * @param object $time
     * @return 
     */
    public function setStartTime($time){
        $this->startTime = (string) $time;
    }
    
    /**
     * as per the startTime
     * 
     * @param object $time
     * @return 
     */
    public function setStopTime($time){
        $this->stopTime = (string) $time;
    }
    /**
     * this is just a setter function that forces the incoming information to a string.
     * 
     * @param object $time
     * @return 
     */	
	public function setDigitalTime($time){
        $this->digitalTime = (string) $time;
    }
    /**
     * this is an internal helper function to cleanse data of CData segments.
     * it is called from the saveNew method only.
     * 
     * @param object $string
     * @return 
     */
    private function removeCData($string){
        $pattern = '/<\!\[CDATA\[(.*?)\]\]\>/imsx';
        preg_match($pattern, $string, $match);
        return (!empty($match[1]) ? $match[1] : $string);
    }
}

/**
 * this class automates create, update and delete operations on database entities
 * it is inherited by all other classes that represent database records
 * 
 */
class baseClass{
    
    /**
     * constructor that just makes sure that the database is properly connected
     * 
     * @return 
     */
    public function __construct(){
        require_once    'Connections/user_login.php';
    }

    /**
     * this method facilitates the loading of data into the object
     * it first transforms the incoming data into an array
     * then looks at the $fields method (set in the inheritor) and
     * iterates that checking that there is an incoming variable and setting that.
     * therefore you can pass an array of lots of extra data (like for example, the submit buttons) 
     * and they will simply be ignored.
     * 
     * @param object $array
     * @return 
     */
    public function load($array){
        if (is_object($array)):
            $array = get_object_vars($array);
        endif;
        foreach($this->fields as $field):
            if (isset($array[$field])):
                $this->$field = (string) $array[$field];
            else:
                $this->$field = NULL;
            endif;
        endforeach;
    }

    /**
     * this function is a despatcher.  it determines whether the save should be
     * an update or an insert based on the value of the primary key
     * 
     * @return 
     */
    public function save(){
        if (empty($this->{$this->primary})):
            $result = $this->saveNew();
            if( $result == true ):
                return $this->getPrimary();
            else:
                return false;
            endif;
        else:
            $result = $this->update();
            return $result;
        endif;
    }
    
    
    /** 
     * this method assembles an insert query from the object's properties 
     * and returns a true/false combo depending on whether the insert went ok.
     * the last query executed is always stored in $lastQuery for debugging
     * @return 
     */
    public function saveNew(){
        $sql = <<<SQL
INSERT 
INTO {$this->table}
(
    {$this->getFields()}
)
VALUES
(
    {$this->getValues()}
)
SQL;
        $this->lastQuery = $sql;
        $r = mysql_query($sql);        
        if ($r):
            $this->{$this->primary} = mysql_insert_id();
            return true;
        else:
            $this->error = mysql_error();
            return false;
        endif;
    }
    
    /**
     * this method assembles and executes an update query from the object properties.
     * it returns a true/false combo depending on success
     * @return 
     */
    public function update(){
        $sql = <<<SQL
UPDATE {$this->table}
SET
    {$this->getUpdate()}
WHERE
    {$this->primary} = '{$this->getPrimary()}'
SQL;
        $this->lastQuery = $sql;
        $r = mysql_query($sql);        
        if ($r):
            return true;
        else:
            $this->error = mysql_error();
            return false;
        endif;
    }
    
    /**
     * this method assembles a delete query from the object properties
     * it returns a true/false combo
     * @return 
     */
    public function delete(){
        if($this->getPrimary() < 1) return false;
        $sql = <<<SQL
DELETE
FROM {$this->table} 
WHERE 
    {$this->primary} = '{$this->getPrimary()}'
SQL;
        $this->lastQuery = $sql;
        $r = mysql_query($sql);
        return $r;
    }
    
    /**
     * this is a helper function that is sometimes useful to determine what the primary key of the 
     * current record might be.
     * it returns null if there is not a primary key set or if $this-primary is not set.
     * @return 
     */
    public function getPrimary(){
        if (    isset($this->primary) && 
                !empty($this->primary) && 
                !empty($this->{$this->primary})):
            return $this->{$this->primary};
        else:
            return null;
        endif;
    }
    
    /**
     * this method is used to return a comma delimited list of fields to use in an insert query
     * 
     * @return 
     */
    private function getFields(){
        return implode(',',$this->fields);
    }
    
    /**
     * this method returns a comma delimeted enquoted escaped set of values to use in an insert query
     * @return 
     */
    private function getValues(){
        $return = array();
        foreach($this->fields as $field):
            $return[] = "'" . $this->escape($this->$field) . "'";
        endforeach;
        return implode(',', $return);
    }
       
    /**
     * update queries are more computationally complex to create dynamically
     * so we need to have a special method for creating the sql string
     * this method simply creates the 'field="value",field2=value2' string needed 
     * for an update query
     * 
     * @return 
     */
    private function getUpdate(){
        $return = array();
        foreach($this->fields as $field):
            $return[] = "$field = '" . $this->escape($this->$field) ."'"; 
        endforeach;
        return implode(',',$return);
    }
    
    /**
     * this method simply calls mysql_real_escape_string on the input argument.
     * 
     * @param object $string
     * @return 
     */
    private function escape($string){
        return mysql_real_escape_string($string);
    }
}


?>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top