Jump to content

[SOLVED] Loop to C/R/U/D team roster


webguy262

Recommended Posts

SNAP!

 

It took me a while, but I got it working.

 

I would love to get your comments in what I did re: the insert/update of the rosters_to_events date.

 

In particular, I'm wondering why I had to post the $doupdate value as a hidden field; I thought it would be available without submitting it in the form.

 

I wish I knew the 'rules' on basic stuff... like single quotes / double quotes, and whether it's $var==1 or $var=='1', and whether if(!empty($var)) is the same as if ($var==0) / ($var=='0').

 

It's tough being self-taught!

 

Anyway, here is my code, pretty much done...

 

<?php
require('includes/application_top.php');

// if the customer is not logged on, redirect them to the login page
  if (!tep_session_is_registered('customer_id')) {
   $navigation->set_snapshot();
   tep_redirect(tep_href_link(FILENAME_LOGIN, '', 'SSL'));
  }
?>

<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<title><?php echo TITLE; ?></title>
<base href="<?php echo (($request_type == 'SSL') ? HTTPS_SERVER : HTTP_SERVER) . DIR_WS_CATALOG; ?>">
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<?php require('includes/form_check_coach.js.php'); ?>

</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0">
<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>
<!-- header_eof //-->
<!-- body //-->

<?php

// echo $customer_id;
echo $row['customers_id'];

mydbg( 'POST: ' ); mydbg( $_POST );//%%
if( !empty( $_POST ) ) {

foreach($_POST as $var => $value)
{
echo $var . ' : ' . $value . "<br>";
}

echo $doupdate;
if($doupdate=='1') {
echo "WE ARE GOING TO DO AN UPDATE";


$sqlupdevent="UPDATE rosters_to_events SET event_code='$_POST[event_code]', team_name='$_POST[team_name]', team_age='$_POST[team_age]' WHERE customers_id=$customer_id";

if(!mysql_query($sqlupdevent)) {
die('UpdateEventError: ' . mysql_error());
} 

} else {
echo "WE ARE GOING TO DO AN INSERT";

$sqlinsevent="INSERT INTO rosters_to_events (customers_id, event_code, team_name, team_age) VALUES ('$customer_id', '$_POST[event_code]', '$_POST[team_name]', '$_POST[team_age]')";


if(!mysql_query($sqlinsevent)) {
die('InsertEventError: ' . mysql_error());
} 


}

foreach( $_POST['player'] as $player_id => $player_info ) {
      // ADDED A CHECK FOR IF THE PLAYER IS EMPTY!
      $emptyplayer = $player_info; // Copy the array
      unset( $emptyplayer['customer_id'] ); // Remove customer_id from empty player
      $emptyplayer = trim( implode( " ", $emptyplayer ) );
      $emptyplayer = !strlen( $emptyplayer ); // true if empty, false otherwise
      foreach( $player_info as $k => $v ) {
         $player_info[$k] = "'" . mysql_real_escape_string( $v ) . "'";
      }
      if( $player_id < 0 ) {
         if( $emptyplayer ) {
            mydbg( 'Skipped player' );//%%
            continue; // SKIP TO NEXT PLAYER
         }
         // OOPS!  SINCE 'player_id' IS AUTO-INCREMENTING, WE DO NOT HAVE TO INSERT IT.
         // THEREFORE THE FOLLOWING LINE IS COMMENTED OUT
         //$player_info['player_id'] = "'" . mysql_real_escape_string( $player_id ) . "'";
         $stmt = "insert into `rosters` ( " . implode( ', ', array_keys( $player_info ) )
            . " ) values ( " . implode( ', ', $player_info ) . " )";
         mydbg( 'Insert player' );//%%
      }else if( !$emptyplayer ){
         // player_id GREATER THAN ZERO, SO PLAYER EXISTS IN DATABASE.  PLAYER IS NOT
         // EMPTY, SO WE UPDATE HIM!
         foreach( $player_info as $k => $v ) {
            // SLIGHTLY MORE READABLE
            $player_info[$k] = "`{$k}`={$v}";
         }
         $stmt = "update `rosters` set " . implode( ', ', $player_info ) . " where "
            . "`player_id`='" . mysql_real_escape_string( $player_id ) . "'";
         mydbg( 'Update player' );//%%
      }else{
         // player_id GREATER THAN ZERO SO HE EXISTS IN DATABASE.  PLAYER IS EMPTY
         // SO WE DELETE HIM!
         $stmt = "delete from `rosters` where `player_id`='" . mysql_real_escape_string( $player_id ) . "'";
         mydbg( 'Delete player' );//%%
      }
      $r = mysql_query( $stmt ); // check for errors and success
      if( !$r ) {
         mydbg( $stmt );//%%
         mydbg( mysql_error() );//%%
      }
   }
}

$sqlgetevent = "SELECT customers_id, event_code, team_name, team_age FROM rosters_to_events WHERE customers_id = $customer_id";

$result=mysql_query($sqlgetevent);

$num_rows=mysql_num_rows($result);

if ($num_rows>1) {
echo "too many results";
} elseif ($num_rows==1) {
$doupdate=1;
echo "we need an update";
} else {
$doupdate=0;
echo "we need an insert";
}
$row=mysql_fetch_array($result);
echo $doupdate;
?>

<form action="roster.php" method="post"><table cellpadding="3"><tr bgcolor="#eeeeee"><td colspan="12"><table><tr><td>Team Name: <?php echo  tep_draw_input_field('team_name', $row['team_name'], 'size="10"'); ?></td><td>Age Level: <?php echo  tep_draw_input_field('team_age', $row['team_age'], 'size="10"'); ?></td><td>Event Code: <?php echo  tep_draw_input_field('event_code', $row['event_code'], 'size="10"'); ?></td><td><input type="hidden" name="doupdate" value="<?php echo $doupdate; ?>"></td></tr></table></td></tr><tr><td class="headerNavigation">Player First Name</td><td class="headerNavigation">Player Last Name</td><td class="headerNavigation">Player Address</td><td class="headerNavigation">City</td><td class="headerNavigation">State</td><td class="headerNavigation">Zip</td><td class="headerNavigation">Player Phone</td><td class="headerNavigation">Player Email</td><td class="headerNavigation">Jersey #</td><td class="headerNavigation">Grad Yr</td><td class="headerNavigation">Ht. Ft.</td><td class="headerNavigation">Ht. In.</td></tr>

<?php

$sqlplayers = "select * from `rosters` where `customer_id`='" . mysql_real_escape_string( $customer_id ) . "'";
$result = mysql_query( $sqlplayers );
$maxrows = 15;
$insid = -1;
// create a blank player template
$cols = array( 'fname' => 'size="15"', 'lname' => 'size="15"', 'address' => 'size="20"', 'city' => 'size="15"', 'state' => 'size="2"',
   'zip' => 'size="10"', 'phone' => 'size="10"',
   'email' => 'size="20"', 'number' => 'size="2"', 'gradyear' => 'size="4"', 'height_feet' => 'size="2"', 'height_inches' => 'size="2"' );
$blankplayer = array();
foreach( $cols as $c => $extra ) {
   $blankplayer['player_roster_' . $c] = ''; // MODIFIED TO ADD player_roster_ prefix
}
// we now have a blank player template
for( $i = 1; $i <= $maxrows; $i++ ) {
   echo "<tr>";
   if( $result ) {
     $player = mysql_fetch_assoc( $result );
     mydbg( $player );//%%
   }
   if( !$player ) {
     // We've run out of players, so create a blank one to insert
      $result = null; // stop trying to access result
     $player = $blankplayer;
      $player['player_id'] = $insid--; // first blank player is id -1, second is -2, third is -3, etc.
   }
   // dump the fields
   $firstcol = true;
   foreach( $cols as $c => $extra ) {
    $c = 'player_roster_' . $c; // MODIFIED TO ADD player_roster_ prefix
    echo "<td>";
    if( $firstcol === true ) {
      echo "<input type=\"hidden\" name=\"player[{$player['player_id']}][customer_id]\" value=\"{$customer_id}\" />";
    }
    echo tep_draw_input_field( "player[{$player['player_id']}][{$c}]", $player[$c], $extra ) ."</td>";
   }
   $player = null; // important!
   echo "</tr>";

}
?>
</table><input type="submit" name="editplayers" value="Submit" />
</form>

<?php mydbg( null, false ); /*%%REMOVE ME dump debugging */?>
<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
</body>
</html>
<?php require(DIR_WS_INCLUDES . 'application_bottom.php'); ?>
<?php
/**
* Simple debugging function.  If $add is true, it adds debugging message.  If $add is
* is false, it dumps debugging messages that were added.
*
* @param mixed $msg
* @param bool $add
*/
function mydbg( $msg, $add = true ) {
   static $msgs = array();
   if( $add === true ) {
      $msgs[] = $msg;
   }else{
      echo '<pre style="text-align: left; font-weight: bold; font-size: 10px; background-color: #ececec;">
      DEBUG:';
      foreach( $msgs as $msg ) {
         if( is_bool( $msg ) ) {
            $msg = 'BOOLEAN [' . ($msg ? 'T' : 'F' ) . ']';
         }else if( is_null( $msg ) ) {
            $msg = '__NULL__';
         }else if( is_string( $msg ) && !strlen( $msg ) ) {
            $msg = '__EMPTY_STRING__';
         }else if( is_array( $msg ) || is_object( $msg ) ) {
            $msg = print_r( $msg, true );
         }
         echo $msg . "\n\n";
      }
      echo '</pre>';
   }
}
?>

Link to comment
Share on other sites

  • Replies 59
  • Created
  • Last Reply

Top Posters In This Topic

Now that I managed to actually add something with you doing it for me  ;D I need a hand with validation. 

 

Nothing fancy for now, just a javascript alert if there are any empty fields.

 

The form could have as many as 183 fields.  How can I easily check if any fields are empty, and throw the alert if one is?

Link to comment
Share on other sites

>In particular, I'm wondering why I had to post the $doupdate value as a hidden field; I thought it would be available without submitting it in the form.

 

Can you shed any light on this?  I assumed by setting the value in the sql that populates the form, the variable would be available after submitting the form to the same page.

 

No?

Link to comment
Share on other sites

PHP doesn't keep the values of variables from page to page.  Every page request from the user starts with a "clean slate" in terms of variables and their values.  The only way to save values from page to page is to use some form of persistent storage; for web applications that is typically done with sessions or with the database.

 

I hope that explanation helps somewhat.

 

My apologies for not being as helpful the past few days; I had less downtime at work and I've been enjoying every moment of my free time away from the computer.  :)

Link to comment
Share on other sites

If you added Dojo to your application, then you might achieve your validation with the following JavaScript:

 

/**
* Called when the form is sumitted.
*
* @param Event
*/
function myFormSubmitHandler( e ) {
var valid = true,
	possible_rows = dojo.query( 'tr', dojo.query( 'form[action="roster.php"]' )[0] /* You can probably replace this query with some property of argument e, such as e.target */ ),
	i, k, input_qry, count_empty, count_not_empty;

for( i = 0; i < possible_rows.length; i++ ) {
	// For each possible TR row, make sure it is one with immediate input[name=player*] children
	input_qry = dojo.query( 'td > input + input[name^="player["]', possible_rows[i] );
	if( input_qry.length === 0 ) {
		continue;
	}

	// input_qry[i] is a valid TR row with inputs.
	input_qry = dojo.query( 'input[name^="player["]', possible_rows[i] );
	if( input_qry.length === 0 ) {
		continue; // This should never happen
	}

	count = 0;
	count_empty = 0;
	count_not_empty = 0;
	for( k = 0; k < input_qry.length; k++ ) {
		if( dojo.attr( input_qry[k].name ).indexOf( '[customer_id]' ) ) {
			continue; // Skip hidden inputs of customer ID
		}
		if( dojo.trim( input_qry[k].value ).length === 0 ) {
			count_empty++;
		}else{
			count_not_empty++;
		}
	}
	if( count_empty > 0 && count_not_empty > 0 ) {
		alert( 'you must fill in all of the rows!' );
		valid = false;
	}
}

if( valid === false ) {
	e.preventDefault();
}
}

// When the page loads, we add an onSubmit handler to the form
dojo.addOnLoad( function() {
var qry = dojo.query( 'form[action="roster.php"]' );
if( qry ) {
	dojo.connect( qry[0], 'onsubmit', 'myFormSubmitHandler' );
}
} );

 

It's not the best written and probably won't even work as-is, but it may give you an idea.  That's about as much as I can help you with JS validation though.  You may think about posting a topic in the JS forums.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.