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 biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Blank page with no errors...

Status
Not open for further replies.

JBlair

Programmer
May 30, 2003
76
US
Okay. I'm still a beginner with PHP, but I usually know how to get something done that I want done.

I'm having a problem with a self-processing file that I'm not sure of. I'm using this file for keeping records on some dwarf hamsters I'm breeding, making it easier for other people on my computer to help with the updates. Problem is that I'm running the script and getting a completely blank web page. I'm not getting any errors (with reporting set to E_STRICT and error logging turned on), and it appears the script is not running at all, since it doesn't even put in my header and footer functions.

I'm using PHP 5.0.3 on Apache 2.0.52 and MySQL 4.1.8nt
My OS is Windows XP SP2

Could someone possibly point out what is wrong? Also, would you recommend self-processing pages, or should I split functions up into individual files?

Fair warning, this code is long.

Code:
<?php

    set_error_handler("err");

    @ $db = mysqli_pconnect();

    if (!$db) {
        err(mysqli_errno(), mysqli_error());
        exit;
    }

    mysqli_select_db("breeding");
    
    // Column titles for Database information.
    $column = array('Name',
                    'Sex',
                    'Birth',
                    'Type',
                    'Generation',
                    'Mother',
                    'Father',
                    'Litters',
                    'Children',
                    'LastLitter');

    // Options for quick links.
    $options = array('View',
                    'Add',
                    'Update',
                    'Labels');

    if (array_key_exists('option', $_POST)) {
        process_option($_POST['option']);
    } elseif (array_key_exists('option', $_GET)) {
        process_option($_GET['option']);
    } else {
        show_index();
    }
    
    function page_header() {
        echo "<html><head><title>Dwarf Hamster Records</title></head><body>";
        echo "<center>";

        foreach ($GLOBALS['options'] as $opt) {
            echo "&nbsp;<a href='{$_SERVER['PHP_SELF']}?option={$opt}'>[{$opt}]</a>&nbsp;";
        }
        echo "</center><br>";
    }

    function page_footer() {
        echo "<br><center>";

        foreach ($GLOBALS['options'] as $opt) {
            echo "&nbsp;<a href='{$_SERVER['PHP_SELF']}?option={$opt}'>[{$opt}]</a>&nbsp;";
        }

        echo "</center>";
        echo "</body></html>";
    }

    // If no options are present, show the option selection index.
    function show_index() {
        page_header();

        echo "<center>Please select one of the options below to perform on the database.";
        echo "<form action='{$_SERVER['PHP_SELF']}' method='post'>";
        echo "<select name='option' size=3>";

        // Cycle through all available options and add them to the selector.
        foreach ($GLOBALS['options'] as $opt) {
            echo "<option value='{$opt}'>{$opt}</option>";
        }

        echo "</select><br><br>";
        echo "<input type='submit' value='Go!' />";
        echo "</form></center>";

        page_footer();
    }

    // If "option" is present in the post or get of the page, choose what to do depending on its value.
    function process_option($option) {
        switch ( $option ) {
            case 'View':
                page_header();
                
                if (array_key_exists('limits', $_POST)) {
                    $limits = explode(",", $_POST['limits']);
                    $limits[0] = trim($limits[0]);
                    $limits[1] = trim($limits[1]);
                    view_hamsters($limits);
                } else {
                    view_hamsters();
                }
                
                page_footer();
                
                break;
                    
            case 'Update':
                page_header();
                
                if (array_key_exists('update', $_POST)) {
                    update_hamster($_POST['update']);
                } else {
                    update_hamster();
                }
                
                page_footer();
                break;
                
            case 'Add':
                page_header();
                
                if (aray_key_exists('add', $_POST)) {
                    add_hamster($_POST['add']);
                } else {
                    add_hamster();
                }
                
                page_footer();
                break;

            case 'Labels':
                page_header();
                print_labels();
                page_footer();
                break;
                
            default:
                show_index();
        	    break;
        }
    }

    function view_hamsters($limits = array(0, 30)) {
        // This query will get the total number of records.
        $query = "select * from dwarf";
        $results = mysqli_query($query);
        $total_records = mysqli_num_rows($results);
        
        // Force integer values.
        foreach ($limits as $num) {
            $num = intval($num);
        }
        
        // If only one limit is passed, force it into two limits.
        if (count($limits) < 2) {
            $limits[1] = $limits[0];
            $limits[0] = 0;
        }
        
        // Set up query using the pre-established limits.
        $query = "select * from dwarf limit $limit[0], $limit[1]";

        // Apply current query to results, then retrieve number of results.
        $results = mysqli_query($query);
        $num_results = mysqli_num_rows($results);

        // Form so that the view can be changed.
        echo "<form action='{$_SERVER['PHP_SELF']}' method='post'>";
        echo "To see the first 10 records, you would enter '0, 10' without the quotes... This tells the database to select records 0 through 9.<br>";
        echo "If you wanted to start at the 5th record and view only 2 records, enter '4, 2' without quotes... Telling the database to start at record 4, and end at record 5.<br>";
        echo "To show all records at once, simply put the total number of records.<br>";
        echo "<br>Records to show:<br>";
        echo "<input type=text name='limits' value='{$limit[0]}, {$limit[1]}' />";
        echo "<input type=hidden name='option' value='ViewHamsters' />";
        echo "<input type=submit value='Show Records' /></form>";

        // Determine the range of records being shown.
        $high_range = ($limit[0] + $limit[1]) - 1;
        if ($high_range >= $total_records) {
            $high_range = $total_records - 1;
        }
        
        // Begin creating the table for displaying records.
        echo "<br>Currently viewing records {$limit[0]} through {$high_range} ({$num_results} records) out of {$total_records}.";

        echo "<table border=1 width=100%>";
        echo "<caption>Dwarf Hamster Breeding Records</caption>";
        echo "<thead><tr bgcolor=silver>";
        
        // Iterate through the global column array and set each column as a table header.
        foreach ($GLOBALS['column'] as $field) {
            echo "<th>{$field}</th>";
        }
        
        echo "</tr></thead>";
        echo "<tbody>";

        // Iterate through the query results.
        for ($i=0; $i < $num_results; $i++) {
            // Gets the current row.
            $row = mysqli_fetch_array($results);

            // Check to see if the row is odd or even.
            $odd = $i % 2;
            
            // Default the table color white.
            $tc = "#ffffff";

            // If row is odd number, change table color.
            if ($odd) {
                $tc = "#ffffba";
            }

            // Creat row with background color.
            echo "<tr bgcolor={$tc}>";
            
            // Iterate through global column array, this time filling in data.
            foreach ($GLOBALS['column'] as $field) {
                echo "<td>{$row[$field]}</td>";
            }
            
            echo "</tr>";
        }
        
        echo "</tbody></table>";
    }
    
    function add_hamster($add = '') {
        if ($add == '') {
            echo "<center>Use this form to add a hamster to the database.<br>";
            echo "<b>Do NOT use this to add or change information for a hamster already in the database.</b>";
            echo "<br><br>All dates are in this format: <b>YYYY-MM-DD</b>";
            echo "<form action='{$_SERVER['PHP_SELF']}' method='post'>";
            echo "<table width=50% border=1><tr><td width=50%>";

            foreach ($GLOBALS['column'] as $field) {
                if ($field == 'Name'){
                    echo "Name:<br><input type=text name='add' size=12 /><br><br>";
                } elseif ($field == 'Sex'){
                    echo "Sex:<br><input type=radio name='Sex' value='Female' />Female<br><input type=radio name='Sex' value='Male' />Male<br><br>";
                } elseif ($field == 'Generation'){
                    echo "Generation:<br><input type=text name='Generation' size=12 /><br><br></td><td width=50%>";
                } else {
                    echo "$field:<br><input type=text name='$field' size=12 /><br><br>";
                }
            }

            echo "<tr><td colspan=2><input type=hidden name='option' value='Add' />";
            echo "<input type=submit value='Add Hamster' /></td></tr>";
            echo "</table></form></center>";
        } else {
            $query = 'INSERT INTO `dwarf` (`Name`, `Sex`, `Birth`, `Type`, `Generation`, `Mother`, `Father`, `Litters`, `Children`, `LastLitter`) VALUES ("'.$_POST['add'].'", "'.$_POST['Sex'].'", "'.$_POST['Birth'].'", "'.$_POST['Type'].'", "'.$_POST['Generation'].'", "'.$_POST['Mother'].'", "'.$_POST['Father'].'", "'.$_POST['Litters'].'", "'.$_POST['Children'].'", "'.$_POST['LastLitter'].'")';
            $result = mysqli_query($query);

            if ($result) {
                echo "<br><br><center><b>".mysqli_affected_rows()." hamster added successfully.</b></center><br><br>";
                $_POST['option']='View';
                view_hamsters();
            } else {
                err(mysqli_errno(), mysqli_error());
                echo "<br><br><center><b>There was a problem with either the information provided or the database.  Hamster was not added successfully.</center><br><br>";
                $_POST['option']='View';
                view_hamsters();
            }
        }
    }
    
    function update_hamster($update = '') {
        if ($update == '') {
            echo "<center>Please select which hamster you would like to update.<br>";
            echo "<form action='{$_SERVER['PHP_SELF']}' method='post'>";
            echo "<table width=50% border=1><tr><td width=100%>";
            echo "<select name='update' size=6>";

            $query = "SELECT * FROM dwarf";
            $result = mysqli_query($query);
            $num_results = mysqli_num_rows($result);
            for ($i=0; $i < $num_results; $i++) {
                $row = mysqli_result($result, $i, "Name");
                echo "<option>".$row."</option>";
            }

            echo "</select>";
            echo "<tr><td><input type=hidden name='option' value='Update' />";
            echo "<input type=submit value='Update Selected Hamster' /></td></tr>";
            echo "</table></form></center>";
        } elseif ($substr($update, 0, 10) == 'do_update_') {
            $update = $substr($update, 10);

            $query = "UPDATE dwarf SET Name='$update', Sex='".$_POST['Sex']."', Birth='".$_POST['Birth']."', Type='".$_POST['Type']."', Generation='".$_POST['Generation']."', Mother='".$_POST['Mother']."', Father='".$_POST['Father']."', Litters='".$_POST['Litters']."', Children='".$_POST['Children']."', LastLitter='".$_POST['LastLitter']."' WHERE Name = '".$_POST['UpdateHamster']."'";
            $result = mysqli_query($query);
            if ($result) {
                echo "<br><br><center><b>".mysql_affected_rows()." updated successfully.</b></center><br><br>";
                $_POST['option'] = 'View';
                view_hamsters();
            } else {
                err(mysqli_errno(), mysqli_error());
                echo "<br><br><center><b>Problem encountered; update unsuccessful.</b></center><br><br>";
                $_POST['option'] = 'View';
                view_hamsters();
            }
        } else {
            $query = "SELECT * FROM dwarf WHERE Name = '$update'";
            $result = mysqli_query($query);
            $row = mysqli_fetch_array($result);

            echo "<center>Use this form to modify the hamster named {$update}'s record.<br>";
            echo "<form action='{$_SERVER['PHP_SELF']}' method='post'>";
            echo "<table width=50% border=1><tr><td width=50%>";

            foreach ($GLOBALS['column'] as $field) {
                if ($field == 'Sex'){
                    if ($row[$field] == "Female") {
                        echo "Sex:<br><input type=radio checked='on' name='Sex' value='Female' />Female<br><input type=radio name='Sex' value='Male' />Male<br><br>";
                    } else {
                        echo "Sex:<br><input type=radio name='Sex' value='Female' />Female<br><input type=radio checked='on' name='Sex' value='Male' />Male<br><br>";
                    }
                } elseif ($field == 'Generation'){
                    echo "Generation:<br><input type=text name='Generation' size=12 value='$row[$field]' /><br><br></td><td width=50%>";
                } else {
                    echo "{$field}:<br><input type=text name='$field' size=12 value='$row[$field]' /><br><br>";
                }
            }

            echo "</td></tr><tr><td colspan=2><input type=hidden name='option' value='UpdateRecord' />";
            echo "<input type=hidden name='update' value='do_update_{$row['Name']}' />";
            echo "<input type=submit value='Update {$row['Name']}' /></td></tr>";
            echo "</table></form></center>";
        }
    }
    
    function err($num, $msg) {
        echo "<center><b><br><br>Error ($num) has occured.<br>";
        echo $msg."<br><br></b></center>";
    }
    
    function print_labels() {
        echo "Not yet implemented.";
    }
?>
 
You have used @ control operator which suppreses the errors.
Also you can use error_reporting() instead of custom error handling for the time being.

Code:
error_reporting(E_ALL);
$db = mysqli_pconnect();



--------------------------------------------------------------------------
I never set a goal because u never know whats going to happen tommorow.
 
Well, I was able to get it all working by changing mysqli to mysql, but I'm having a hard time figuring out why mysqli doesn't work for me.

I've tried reading the PHP docs, and other peoples examples, but most of it isn't clearly stated and I just gave up. Mysql works fine for what I need so I'm no longer bothering with mysqli
 
you may not have the mysqli extension installed. use phpinfo() to check. (mysqli is a separate extension to mysql).
 
Yes, it is installed...

mysqli
MysqlI Support enabled
Client API version 4.1.7
MYSQLI_SOCKET /tmp/mysql.sock

Directive Local Value Master Value
mysqli.default_host localhost localhost
mysqli.default_port 3306 3306
mysqli.default_pw no value no value
mysqli.default_socket no value no value
mysqli.default_user no value no value
mysqli.max_links Unlimited Unlimited
mysqli.reconnect Off Off
 
I got the page working with mysqli, though I don't know how.

Now I've run into a problem with one of my functions...

The page runs fine up until it reaches this function. If it is passed no $update variable, it works fine. When passed an $update variable, it outputs the first echo line (stating it has entered the function, and displaying the passed value) then nothing else happens. Is there a problem I am missing from the outermost IF statements?

Code:
// Update Hamster function.
function update_hamster( $update = '' ) {
    // Debug information only.
	echo "function update_hamster($update)<br>";

	if ( $update == '' ){
            // Debug information only.
		echo "update == ''";

		echo "<center>Please select which hamster you would like to update.<br>";
		echo "<form action='{$_SERVER['PHP_SELF']}' method='post'>";
		echo "<table width=50% border=1><tr><td width=100%>";
		echo "<select name='update' size=6>";
		
		$query = "SELECT * FROM dwarf";
		$result = mysqli_query( $GLOBALS['db'], $query );
		$num_results = mysqli_num_rows( $result );
		for ( $i = 0; $i < $num_results; $i++ ){
			$row = mysqli_fetch_array( $result );
			echo "<option>{$row['Name']}</option>";
		}

		echo "</select>";
		echo "<tr><td><input type=hidden name='option' value='Update' />";
		echo "<input type=submit value='Update Selected Hamster' /></td></tr>";
		echo "</table></form></center>";
	}elseif ( $substr( $update, 0, 10 ) == 'do_update_' ){
            // Debug information only.
		echo "$update becomes ";
		$update = $substr( $update, 9 );
		echo "$update<br>";
		
		$query = "UPDATE dwarf SET Name='$update', Sex='" . $_POST['Sex'] . "', Birth='" . $_POST['Birth'] . "', Type='" . $_POST['Type'] . "', Generation='" . $_POST['Generation'] . "', Mother='" . $_POST['Mother'] . "', Father='" . $_POST['Father'] . "', Litters='" . $_POST['Litters'] . "', Children='" . $_POST['Children'] . "', LastLitter='" . $_POST['LastLitter'] . "' WHERE Name = $update";
		$result = mysqli_query( $GLOBALS['db'], $query );
		if ( $result ){
			echo "<br><br><center><b>" . mysqli_affected_rows( $GLOBALS['db'] ) . " updated successfully.</b></center><br><br>";
			view_hamsters();
		}else{
			echo "<br><br><center><b>Problem encountered; update unsuccessful.</b></center><br><br>";
			view_hamsters();
		}
	}else{
            // Debug information only.
		echo "update was not 'do_update_[name]' and was not empty.  update == $update <br>";

		$query = "SELECT * FROM dwarf WHERE Name = '$update'";
		$result = mysqli_query( $GLOBALS['db'], $query );
		$row = mysqli_fetch_array( $result );
		
		echo "<center>Use this form to modify the hamster named {$update}'s record.<br>";
		echo "<form action='{$_SERVER['PHP_SELF']}' method='post'>";
		echo "<table width=50% border=1><tr><td width=50%>";
		
		foreach ( $GLOBALS['column'] as $field ){
			if ( $field == 'Sex' ){
				if ( $row[$field] == "Female" ){
					echo "Sex:<br><input type=radio checked='on' name='Sex' value='Female' />Female<br><input type=radio name='Sex' value='Male' />Male<br><br>";
				}else{
					echo "Sex:<br><input type=radio name='Sex' value='Female' />Female<br><input type=radio checked='on' name='Sex' value='Male' />Male<br><br>";
				}
			}elseif ( $field == 'Generation' ){
				echo "Generation:<br><input type=text name='Generation' size=12 value='$row[$field]' /><br><br></td><td width=50%>";
			}else{
				echo "{$field}:<br><input type=text name='$field' size=12 value='$row[$field]' /><br><br>";
			}
		}

		echo "</td></tr><tr><td colspan=2><input type=hidden name='option' value='Update' />";
		echo "<input type=hidden name='update' value='do_update_{$row['Name']}' />";
		echo "<input type=submit value='Update {$row['Name']}' /></td></tr>";
		echo "</table></form></center>";
	}
}
 
difficult to work through it all without all the mysql bits being reflected.

it could be failing because your sql statement will always refer to $update as being empty - and thus may return an empty recordset each time. this is because you have a line :
Code:
$update = $substr( $update, 9 );
which should read
Code:
$update = substr( $update, 9 );
(i.e. substr is a php function and not a variable as coded currently it will set $update = "" each time).

i'd also consider not using "==" unless you are clear about the difference between "=". "==" and "===". the empty function is good practice or it is also OK to negate the equality. ie:
Code:
 if ($str != "") {} else {}

hth
Justin
 
Let's go back to basics... you keep posting these huge code sections that no one is really going to look at that closely.

Debugging 101: Simplify. Eliminate code that you know is not getting executed, delete lines that don't do anything related to the problem. In a worst case scenario I've done a binary search where I just delete the second half of my code and see if it errors out. If it does, I delete half of the code remaining, otherwise I know the problem was in the first half.

With a little initiative and a modicum of intelligence, 9 times out of 10 you will figure out what your problem is. But if not, then you can post a 5 line example of what the problem is instead of 500.
 
My apologies.

When I post I tend to be short on time, I'll try to avoid that in the future.

Anyhow, I fixed the $substr typo and still get the same problem.

I know that the error is occuring in the outer layer of IF/THEN/ELSE, and only when it comes to the ELSEIF and ELSE statements.

I'll keep testing once I have more time.
 
the same error repeats multiple times in the outer condition.

turn error reporting to all and rerun the code. if that doesnt throw up the answer then follow eric's advice and simplify the code : i'd start by deleting everything within the conditions and building from there.
 
Oddly enough, my error reporting isn't working.

I have E_STRICT set, with logging turned on and a filename specified, but it doesn't log anything.

I also removed my error handler and still no change. I'm going to have to follow Eric's advice if I intend to get through it. Though rather than deleting everything, I'm commenting things out.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top