Solved

Mixed-up PHP output

Posted on 2008-06-11
5
350 Views
Last Modified: 2013-12-13
I'm writing a couple of classes to drive a company's timeclock web application.  I have a test page that I've setup to help with testing at: http://timeclock.oagi.com/newTimeclock/index.php.

The output of this page is mixed up.  The output of the "Timecard retrieval test" should fall at the bottom of the page.  Any ideas what's up?
/***** index.php *****/
<html>
    <head>
        <title>Timecard Test</title>
        <style type="text/css">
			html {
				font-family: Verdana, Helvetica, Arial, sans-serif;
			}
			body, td {
				font-size: 12px;
			}
		</style>
    </head>
    <body>
        <?php
            // echo strtotime("6/6/2008 8:42am");
            require("Timecard.php");
            
            $tc = new Timecard("1","");
            $tc2 = new Timecard("2","41");
            $tc->readTimecardFromDatabase($tc->getUserID(), strtotime("January 1, 2008"), strtotime("December 1, 2008"));
            for($i = 0; $i < sizeof($tc->timecardActivities); $i++) {
                $tc->timecardActivities[$i]->displayInfoAsTable();
            }
            
            $tc2->getTimecardActivities($tc2->getTimecardID());
            
            /*
            $tc->addTimecardActivity(NULL,1,"6/8/2008 8:46pm","6/10/2008 11:21pm","Testing application",NULL,NULL);
            $tc->addTimecardActivity(NULL,2,"6/10/2008 11:32pm","6/10/2008 11:45pm","More testing",NULL,NULL);
            $tc->addTimecardActivity(NULL,4,"6/12/2008 8:46am","6/12/2008 11:01am","Driving",100456,101009);
            for($i = 0; $i < sizeof($tc->timecardActivities); $i++) {
                $tc->timecardActivities[$i]->displayInfoAsTable();
            }
            */
        ?>
    </body>
</html>
 
/***** Timecard.php *****/
<?php
 
class Timecard {
    private $userID;
    private $date;
    private $timecardID;
    private $timecardClosed;
    public $timecardActivities;
    
    public function __construct($userID, $timecardID) {
        $this->userID = $userID;
        $this->date = $date;
        $this->timecardActivities = array();
        $this->timecardClosed = 0;
        $this->timecardID = $timecardID;
        
        if($timecardID == "") {
	        include("dbConfig.inc.php");
	        $mysqli = new mysqli($dbhost,$dbusername,$dbpassword,$dbdatabase);
			if(mysqli_connect_errno()) {
				printf("Connect failed: %s\n", mysqli_connect_error());
				exit;
			}
			
			echo "<h2>Timecard creation test:</h2>";
			echo "Connected to database to create timecard...<br />";
			$query = "INSERT INTO timecards (userID, creationDate)
					  VALUES (?,NOW())";
			echo "Timecard creation query written...<br />";
			if($stmt = $mysqli->prepare($query)) {
				echo "Timecard creation query prepared...<br />";
				$stmt->bind_param('s', $this->userID);
				$stmt->execute();
				echo "Running query...<br />";
				echo $stmt->affected_rows . " rows inserted successfully.  Timecard successfully created!<br />";	
				$this->timecardID = mysqli_stmt_insert_id($stmt);
				echo "Created timecard with Timecard ID: " . $this->timecardID . "<br />";
				$stmt->close();
			}
			
			$query = "SELECT creationDate 
					  FROM timecards 
					  WHERE timecardID = ?";
			if($stmt = $mysqli->prepare($query)) {
				echo "Timecard creation date query prepared...<br />";
				$stmt->bind_param('s', $this->timecardID);
				$stmt->execute();
				$stmt->bind_result($creationDate);
				echo "Running query...<br />";
				$stmt->fetch();
				$this->date = $creationDate;
				echo "Timecard Datestamp is: " . $this->date . "<br /><hr>";
				$stmt->close();
			}
			
			$mysqli->close();
        }
    }
    
    public function addTimecardActivity($activityID,
    									$timecardID,
                                        $activityCode,
                                        $timeBegin,
                                        $timeEnd,
                                        $description,
                                        $mileageBegin,
                                        $mileageEnd) {
        $this->timecardActivities[] = new TimecardActivity($activityID,
        												   $timecardID,
                                                           $activityCode,
                                                           $timeBegin,
                                                           $timeEnd,
                                                           $description,
                                                           $mileageBegin,
                                                           $mileageEnd);
    }
    
    public function getTimecardActivities($timecardID) {
    	$this->timecardID = $timecardID;
    	
    	include("dbConfig.inc.php");
        $mysqli = new mysqli($dbhost,$dbusername,$dbpassword,$dbdatabase);
		if(mysqli_connect_errno()) {
			printf("Connect failed: %s\n", mysqli_connect_error());
			exit;
		}
		
		echo "<h2>Timecard retrieval test:</h2>";
		echo "Connected to database to retrieve timecard...<br />";
		$query = "SELECT activityID, timecardID, userID, typeID, 
				  	timeBegin, timeEnd, serviceOrder, mileageBegin, 
				  	mileageEnd, confirmed 
				  FROM timecardActivities 
				  WHERE timecardID = ? 
				  ORDER BY timeBegin ASC";
		echo "Timecard retrieval query written...<br />";
		if($stmt = $mysqli->prepare($query)) {
			echo "Timecard retrieval query prepared...<br />";
			$stmt->bind_param('s', $timecardID);
			$stmt->execute();
			echo "Running query...<br />";
			$stmt->bind_result($activityID, $timecardID, $userID, $typeID, $timeBegin,
							   $timeEnd, $serviceOrder, $mileageBegin, $mileageEnd, 
							   $confirmed);
			while($stmt->fetch()) {
				$this->addTimecardActivity($activityID,$timecardID,$activityID,$timeBegin,
										   $time,$serviceOrder,$mileageBegin,$mileageEnd);
			}
			echo "Retrieved timecard with Timecard ID: " . $this->timecardID . "<br />";
			$stmt->close();
		}
    }
    
    public function getUserID() {
    	return $this->userID;
    }
    
    public function getTimecardID() {
    	return $this->timecardID;
    }
    
    public function removeAllActivities() {
		if(isset($this->timecardActivities) || empty($this->timecardActivities)) {
			unset($this->timecardActivities);
			$this->timecardActivities = array();
		}
	}
	
	public function readTimecardFromDatabase() {
		/**
		 * Function accepts a variable number of parameters. See below:
		 * 
		 * 0 parameters: Function echoes: "You have not included any parameters..."
		 * 1 parameter: string userID
		 * 2 parameters: string userID, timestamp date
		 * 3 parameters: string userID, timestamp timeBegin, timestamp timeEnd
		 *  
		 */
    	
		echo "<h2>Timecard activity display test:</h2>";
		include("dbConfig.inc.php");
    	echo "Connecting to database...<br />";
    	echo "readTimecardFromDatabase() received " . func_num_args() . " arguments.<br />";
		
    	// 0 parameters in function call:
    	if(func_num_args() == 0) {
    		echo "You have not included any parameters for the function: readTimecardFromDatabase().<br />";
    	
    	// 1 parameter in function call (userID).  Will display all entries for userID to date:
    	} elseif (func_num_args() == 1) {
    		
    		$this->removeAllActivities();
    		$userID = func_get_arg(0);
    		
    		$mysqli = new mysqli($dbhost,$dbusername,$dbpassword,$dbdatabase);
    		if(mysqli_connect_errno()) {
    			printf("Connect failed: %s\n", mysqli_connect_error());
    			exit;
    		}
    		
    		$query = "SELECT activityID, typeID, timeBegin, timeEnd, serviceOrder, mileageBegin, mileageEnd
    				  FROM timecardActivities 
    				  WHERE userID = ? 
    				  ORDER BY timeBegin ASC";
    		echo "Query written...<br />";
    		if($stmt = $mysqli->prepare($query)) {
    			echo "Query prepared for User ID: " . $userID . "<br />";
    			$stmt->bind_param('s', $userID);
    			$stmt->execute();
    			echo "Running query...<br />";
    			$stmt->bind_result($activityID, $typeID, $timeBegin, $timeEnd, $serviceOrder, $mileageBegin, $mileageEnd);
    			$stmt->store_result();
    			if($stmt->num_rows < 1) {
    				echo "There was no data for this user ID.<br />";
    			} else {
    				echo "Fetching results...<br />";
	    			while($stmt->fetch()) {
	    				$this->timecardActivities[] = new TimecardActivity($activityID,
	    																   $typeID,
	    																   $timeBegin,
	    																   $timeEnd,
	    																   $serviceOrder,
	    																   $mileageBegin,
	    																   $mileageEnd);
	    			}
    			}	
    			$stmt->close();
    		}
    		
    		$mysqli->close();
    	
    	// 2 parameters in function call.
    	// Will return all entries for $userID (paramter 1) on the date given in $time (parameter 2)
    	} elseif (func_num_args() == 2) {
    		
    		$this->removeAllActivities();
    		
    		$userID = func_get_arg(0);
    		$date = func_get_arg(1);
    		
    		$timeBegin = date("Y-m-d 00:00:00", $date);
    		$timeBegin = date("Y-m-d 11:59:59", $date);
    		
    		$mysqli = new mysqli($dbhost,$dbusername,$dbpassword,$dbdatabase);
    		if(mysqli_connect_errno()) {
    			printf("Connect failed: %s\n", mysqli_connect_error());
    			exit;
    		}
    		
    		$query = "SELECT activityID, timecardID, typeID, timeBegin, timeEnd, serviceOrder, mileageBegin, mileageEnd
    				  FROM timecardActivities 
    				  WHERE userID = ?
    				  AND timeBegin > ? 
    				  AND timeBegin < ? 
    				  ORDER BY timeBegin ASC";
    		echo "Query written...<br />";
    		if($stmt = $mysqli->prepare($query)) {
    			echo "Query prepared for User ID: " . $userID . "<br />";
    			echo "Query limited to entries between: " . $timeBegin . " and " . $timeEnd . "<br />";
    			$stmt->bind_param('sss', $userID, $timeBegin, $timeEnd);
    			$stmt->execute();
    			echo "Running query...<br />";
    			$stmt->bind_result($activityID, $timecardID, $typeID, $timeBegin, $timeEnd, $serviceOrder, $mileageBegin, $mileageEnd);
    			$stmt->store_result();
    			if($stmt->num_rows < 1) {
    				echo "There was no data for this user ID.<br />";
    			} else {
    				echo "Fetching results...<br />";
	    			while($stmt->fetch()) {
	    				$this->timecardActivities[] = new TimecardActivity($activityID,
	    																   $timecardID,
	    																   $typeID,
	    																   $timeBegin,
	    																   $timeEnd,
	    																   $serviceOrder,
	    																   $mileageBegin,
	    																   $mileageEnd);
	    			}
    			}	
    			$stmt->close();
    		}
    		
    		$mysqli->close();
    		
    	// 3 parameters in function call.
    	// Will return all entries for userID between timeBegin and timeEnd		
    	} elseif(func_num_args() == 3) {
    		
    		$this->removeAllActivities();
    		
    		$userID = func_get_arg(0);
    		$timeBegin = func_get_arg(1);
    		$timeEnd = func_get_arg(2);
    		
    		$timeBegin = date("Y-m-d H:i:s", $timeBegin);
    		$timeEnd = date("Y-m-d H:i:s", $timeEnd);
    		
    		$mysqli = new mysqli($dbhost,$dbusername,$dbpassword,$dbdatabase);
    		if(mysqli_connect_errno()) {
    			printf("Connect failed: %s\n", mysqli_connect_error());
    			exit;
    		}
    		
    		$query = "SELECT activityID, timecardID, typeID, timeBegin, timeEnd, serviceOrder, mileageBegin, mileageEnd
    				  FROM timecardActivities 
    				  WHERE userID = ?
    				  AND timeBegin > ? 
    				  AND timeBegin < ? 
    				  ORDER BY timeBegin ASC";
    		echo "Query written...<br />";
    		if($stmt = $mysqli->prepare($query)) {
    			echo "Query prepared for User ID: " . $userID . "<br />";
    			echo "Query limited to entries between: " . $timeBegin . " and " . $timeEnd . "<br />";
    			$stmt->bind_param('sss', $userID, $timeBegin, $timeEnd);
    			$stmt->execute();
    			echo "Running query...<br />";
    			$stmt->bind_result($activityID, $timecardID, $typeID, $timeBegin, $timeEnd, $serviceOrder, $mileageBegin, $mileageEnd);
    			$stmt->store_result();
    			if($stmt->num_rows < 1) {
    				echo "There was no data for this user ID.<br />";
    			} else {
    				echo "Fetching results...<br />";
	    			while($stmt->fetch()) {
	    				$this->timecardActivities[] = new TimecardActivity($activityID,
	    																   $timecardID,
	    																   $typeID,
	    																   $timeBegin,
	    																   $timeEnd,
	    																   $serviceOrder,
	    																   $mileageBegin,
	    																   $mileageEnd);
	    			}
    			}	
    			$stmt->close();
    		}
    		
    		$mysqli->close();
    	}
    }
}
 
class TimecardActivity{
    private $activityCode;
    private $activityID;
    private $timecardID;
    private $timeBegin;
    private $timeEnd;
    private $description;
    private $mileageBegin;
    private $mileageEnd;
    private $totalTime;
    private $activityClosed;
    
    //  Activity codes:
    //  1:  Main Clock In/Out
    //  2:  Break
    //  3:  Meal
    //  4:  Travel To/From Office/Home
    //  5:  Service Order Work
    //  6:  Service Order Travel
    //	7:	Other Work
    
    public function __construct($activityID,
    							$timecardID,
    							$activityCode,
                                $timeBegin,
                                $timeEnd,
                                $description,
                                $mileageBegin,
                                $mileageEnd) {
        $this->activityID = $activityID;
        $this->activityCode = $activityCode;
        $this->timecardID = $timecardID;
        $this->timecardID = $timecardID;
        $this->timeBegin = $timeBegin;
        $this->timeEnd = $timeEnd;
        $this->description = $description;
        $this->mileageBegin = $mileageBegin;
        $this->mileageEnd = $mileageEnd;
        
        if(is_null($timeEnd)) {
            // 0 = open, 1 = closed
            $this->activityClosed = 0;
        } else {
            $this->activityClosed = 1;
        }
        
        if($this->activityClosed == "closed") {
            $this->calculateElapsedTime($this->timeBegin, $this->timeEnd);
        }
    }
    
    private function calculateElapsedTime($timeBegin, $timeEnd) {
        if(is_null($timeEnd) || $timeEnd == "") {
        	$totalHours = "This activity is not yet closed.";
        } else {
	    	$totalTime = strtotime($timeEnd)-strtotime($timeBegin);
	        $totalHours = round($totalTime/3600, 2);
        }
        return $totalHours;
    }
    
    private function calculateMileage($mileageBegin, $mileageEnd) {
        $totalMileage = $mileageEnd - $mileageBegin;
        return $totalMileage;
    }
    
    public function writeActivityToDatabase() {
    }
    
    public function updateActivityInDatabase() {
    }
    
    public function displayInfo() {
        $info = "<p>Activity ID: " . $this->activityID . "<br />";
        $info .= "Timecard ID: " . $this->timecardID . "<br />";
        $info .= "Activity Code: " . $this->activityCode . "<br />";
        $info .= "Begin Time: " . $this->timeBegin . "<br />";
        $info .= "End Time: " . $this->timeEnd . "<br />";
        $info .= "Total Hours: " . $this->calculateElapsedTime($this->timeBegin, $this->timeEnd) . "<br />";
        $info .= "Begin Mileage: " . $this->mileageBegin . "<br />";
        $info .= "End Mileage: " . $this->mileageEnd . "<br />";
        $info .= "Total Miles: " . $this->calculateMileage($this->mileageBegin, $this->mileageEnd) . "<br />";
        $info .= "Description: " . $this->description . "<br /><br /></p>";
        
        $info .= "<p>" . $this->activityID . " || " . $this->activityCode . " || " . $this->timeBegin . " || " . 
        			$this->timeEnd . "</p>";
        
        return $info;
    }
    
    public function displayInfoAsTable() {
    	$activityDesc = $this->fetchActivityDescription($this->activityCode);
    	
    	echo "<table border='1'>";
    	echo "<tr><td>Activity ID: " . $this->activityID . "</td><td>Timecard ID: " . $this->timecardID . "</td></tr>";
    	echo "<tr><td>Activity Code: " . $this->activityCode . "</td><td>Activity Description: " . $activityDesc . "</td></tr>";
        echo "<tr><td>Begin Time: " . $this->timeBegin . "</td><td>End Time: " . $this->timeEnd . "</td></tr>";
        echo "<tr><td colspan='2'>Total Hours: " . $this->calculateElapsedTime($this->timeBegin, $this->timeEnd) . "</td></tr>";
        echo "<tr><td>Begin Mileage: " . $this->mileageBegin . "</td><td>End Mileage: " . $this->mileageEnd . "</td></tr>";
        echo "<tr><td colspan='2'>Total Miles: " . $this->calculateMileage($this->mileageBegin, $this->mileageEnd) . "</td></tr>";
        echo "<tr><td colspan='2'>Service Order # / Description: " . $this->description . "</td></tr>";	
    }
    
    public function fetchActivityDescription($activityCode) {
    	include("dbConfig.inc.php");
    	$mysqli = new mysqli($dbhost,$dbusername,$dbpassword,$dbdatabase);
    	if(mysqli_connect_errno()) {
    			printf("Connect failed: %s\n", mysqli_connect_error());
    			exit;
    	}
    	
    	$query = "SELECT `shortDesc` FROM `timeTypes` WHERE `typeID` = ? LIMIT 1";
    	if($stmt = $mysqli->prepare($query)) {
    		$stmt->bind_param("s", $activityCode);
    		$stmt->execute();
    		$stmt->bind_result($result);
    		echo mysql_error();
    		while($stmt->fetch()) {
    			$activityDesc = $result;
    		}
    		$stmt->close();
    	}
    	
    	$mysqli->close();
    	
    	return $activityDesc;
    	
    }
    
    public function __toString() {
        $str = $this->displayInfo();
        return $str;
    }
    
}
 
?>

Open in new window

0
Comment
Question by:TechComposer
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 2

Expert Comment

by:jml948
ID: 21766606
The output of the "Timecard retrieval test" is falling at the bottom of the page:

Layout is as follows on Firefox and Internet Explorer:

Timecard creation test:
Connected to database to create timecard...
Timecard creation query written...
Timecard creation query prepared...
Running query...
1 rows inserted successfully. Timecard successfully created!
Created timecard with Timecard ID: 119
Timecard creation date query prepared...
Running query...
Timecard Datestamp is: 2008-06-11 23:28:49

Timecard activity display test:
Connecting to database...
readTimecardFromDatabase() received 3 arguments.
Query written...
Query prepared for User ID: 1
Query limited to entries between: 2008-01-01 00:00:00 and 2008-12-01 00:00:00
Running query...
Fetching results...
Activity ID: 196      Timecard ID: 16
Activity Code: 1      Activity Description: Clock In
Begin Time: 2008-06-11 08:34:00      End Time:
Total Hours: This activity is not yet closed.
Begin Mileage: 11469      End Mileage: 11572
Total Miles: 103
Service Order # / Description: SR2008-00689

Timecard retrieval test:
Connected to database to retrieve timecard...
Timecard retrieval query written...
Timecard retrieval query prepared...
Running query...
Retrieved timecard with Timecard ID: 41
Activity ID: 197      Timecard ID: 16
Activity Code: 5      Activity Description: Meal Break Start
Begin Time: 2008-06-26 15:17:44      End Time: 2008-06-26 17:18:07
Total Hours: 2.01
Begin Mileage: 11487      End Mileage: 11496
Total Miles: 9
Service Order # / Description: SR2008-00793
0
 
LVL 2

Author Comment

by:TechComposer
ID: 21766755
This, and only this, should be at the bottom of the page:

Timecard retrieval test:
Connected to database to retrieve timecard...
Timecard retrieval query written...
Timecard retrieval query prepared...
Running query...
Retrieved timecard with Timecard ID: 41

The two tables should follow each other in succession...
0
 
LVL 2

Expert Comment

by:jml948
ID: 21766905
So would I be correct in assuming that this is what you want for output:

Timecard retrieval test:
Connected to database to retrieve timecard...
Timecard retrieval query written...
Timecard retrieval query prepared...
Running query...
Retrieved timecard with Timecard ID: 41

Activity ID: 196      Timecard ID: 16
Activity Code: 1      Activity Description: Clock In
Begin Time: 2008-06-11 08:34:00      End Time:
Total Hours: This activity is not yet closed.
Begin Mileage: 11469      End Mileage: 11572
Total Miles: 103
Service Order # / Description: SR2008-00689

Activity ID: 197      Timecard ID: 16
Activity Code: 5      Activity Description: Meal Break Start
Begin Time: 2008-06-26 15:17:44      End Time: 2008-06-26 17:18:07
Total Hours: 2.01
Begin Mileage: 11487      End Mileage: 11496
Total Miles: 9
Service Order # / Description: SR2008-00793
0
 
LVL 2

Author Comment

by:TechComposer
ID: 21766948
That is correct.  Sorry for the ambiguity, I should have been clearer.

--BB
0
 
LVL 2

Accepted Solution

by:
TechComposer earned 0 total points
ID: 21771822
Was missing a </table> tag in displayInfoAsTable()...
public function displayInfoAsTable() {
    	$activityDesc = $this->fetchActivityDescription($this->activityCode);
    	
    	echo "<table border='1'>";
    	echo "<tr><td>Activity ID: " . $this->activityID . "</td><td>Timecard ID: " . $this->timecardID . "</td></tr>";
    	echo "<tr><td>Activity Code: " . $this->activityCode . "</td><td>Activity Description: " . $activityDesc . "</td></tr>";
        echo "<tr><td>Begin Time: " . $this->timeBegin . "</td><td>End Time: " . $this->timeEnd . "</td></tr>";
        echo "<tr><td colspan='2'>Total Hours: " . $this->calculateElapsedTime($this->timeBegin, $this->timeEnd) . "</td></tr>";
        echo "<tr><td>Begin Mileage: " . $this->mileageBegin . "</td><td>End Mileage: " . $this->mileageEnd . "</td></tr>";
        echo "<tr><td colspan='2'>Total Miles: " . $this->calculateMileage($this->mileageBegin, $this->mileageEnd) . "</td></tr>";
        echo "<tr><td colspan='2'>Service Order # / Description: " . $this->description . "</td></tr>";
        
        // Was missing this line!
        echo "</table>";
    }

Open in new window

0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question