CSC220 formSkel.php

From dftwiki3
Jump to: navigation, search

--D. Thiebaut 16:46, 27 October 2010 (UTC)


<!--
formskel.php
D. Thiebaut
A skeleton form that contains 1 text field and
loads up the information in the database 
defined in the file accessinfo.php, whose
contents are show below:

$hostName='xgridmac.xxxxxx.xxx';
$userName='220a';
$password='xxxxxx';
$database='220a-xx';
-->

<html>
<head>
</head>
<body>

<?php

//----------------------------------------------------------------
function openDBAddUserClose( $name ) {
  include 'accessinfo.php';

  //--- connect to mysql server ---
  $link = mysql_connect( $hostName, $userName, $password );
  if ( ! $link ) {
    printf( "Could not connect to server: " . $mysql_error() );
    return 0;
  }

  //--- select database ---
  $db = mysql_select_db( $database, $link );
  if ( ! $db ) {
    printf( "Could not connect to database " . $database . ": "
    	 . mysql_error() );
    return 0;
  }
  //--- insert new name in table users ---
  $query = sprintf( "INSERT INTO `users` (`userName`) VALUE ('%s')", $name );
  $result = mysql_query( $query, $link );
  $retVal = 1;
  if ( ! $result ) {
    printf( "Insertion of user %s unsuccessful\n", $name );
    $retVal = 0;
  }

  //--- close database ---
  mysql_close( $link );
  return $retVal;
}

//----------------------------------------------------------------
function printForm( $name ) {
  printf(  '<form action="formskel.php" method="post">
       
         Name: <input type="text" name="name" VALUE="%s" SIZE="40">
         <input type="submit" value="Send">
         </form>', $name );
}

//----------------------------------------------------------------
function success( $name ) {
  printf ( "<h2>Success!</h2><br>%s has successfully been added\n",
	   $name );
}

//----------------------------------------------------------------
function error( $name ) {
  printf( "<h3><font color=\"red\">There was an error inserting %s in database</font></h3>\n",
	  $name );
}

//----------------------------------------------------------------
//                            M A I N 
//----------------------------------------------------------------
//--- get user input ---
$name = $_REQUEST[ 'name' ];

//--- if set, add it to database ---
if ( !empty( $name ) ) {
  $retVal = openDBAddUserClose( $name );
  if ( $retVal ) 
    success( $name );
  else 
    error( $name );
}

//--- show empty form for getting next input---
unset( $name );
printForm( $name );

?>

</body>
</html>