Jump to content

Two forms in One Page


siabanie

Recommended Posts

Ok here are two of my form codes: Basically I like to use if/elseif, can someone please explain to me how these two form here can combine together so it will only have one form but do two different function (create and modify form). Then after these form being edit or create - it will go to another different page which is the confirmation page using sessions.

 

modify form code

<?php

    require 'includes/application.php';    
    //Define
    $name = "";
    $surname = "";
    $add = "";
    $dept= "";
    $mobile = "";
    
    if (!isset($_POST['goSubmit']))
    {
    
        $q = "SELECT * FROM persons WHERE ID = $_GET[id]";
       
        $result = mysql_query($q) or die (mysql_error());
        $row = mysql_fetch_array($result);
        
        $name = $row['name'];
        $surname = $row['surname'];
        $address = $row['address'];
        $dept = $row['dept_id'];
        $mobile = $row['mobile'];
    
        }
        
        $errormsg = "";
        
        if($name == "")
            $errormsg = $errormsg. "Name<br/ >";
            
        if ($surname == "")
            $errormsg = $errormsg. "Surname Please <br/ >";
            
        if ($mobile != "" && !is_numeric ($mobile))
            $errormsg = $errormsg. "Mobile No? <br/ >";
            
         if ($errormsg != "")
            echo "Please fill the blank info: <br/ > $errormsg";
            
            else
            {
                $input_field = "";
                
                
                foreach ($_POST as $key => $val)
                {
                    if ($key != 'goSubmit')
                    {
                    $_SESSION[$key] = $val;
                    }
                }
                
                 header("Location: confirmPage.php");
            }        
}   
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Modify Document</title>
</head>

<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <div align="center">
  <table width="300" border="1">
    <h1> Modifying A User </h1>
    
      <tr>
        <th scope="row">Name</th>
        <td><input type="text" name="name" value="<?php echo $name;?>" /></td>
      </tr>
    
    <tr>
      <th scope="row">Surname</th>
        <td>
        <input type="text" name="surname" value="<?php echo $surname; ?>" /></td>
      </tr>
    
    <tr>
      <th scope="row">Address</th>
        <td><input type="text" name="address" value="<?php echo $address; ?>" /></td>
    </tr>
      
        
    <tr>
      <th scope="row">Department</th>
        <td>
        
        <select name="dept">
            <option value="">Select..</option>

        <?php
        $data = mysql_query ("SELECT * FROM dept ORDER BY `id` DESC") or die (mysql_error());
      
          echo $data;
      
            while($row_dept = mysql_fetch_array( $data ))
        {
        ?>
        <option value="<?php echo $row_dept['id'] ;?>" <?php if($row_dept['id']==$dept){echo ' selected="selected"';}?>>
        <?php echo $row_dept['dept_name'] ;?>
        </option>
    
    <?php
    }
    ?>
        </select>
        </td>
    </tr>
    
    <tr>
      <th scope="row">Mobile</th>
        <td><input type="text" name="mobile" value="<?php echo $mobile; ?>" /></td>
      </tr>
  
  </table>
  <br/>
  
  <a href="indexPage.php">
    <input type="button" name="back" value="Back" /></a>
    
    <input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
    
    <input type="submit" name="goSubmit" value="Modify"/>
    
  </div>
</form>

</body>
</html>

 

create form page

<?php

    require 'includes/application.php';    
    //Define
    $name = "";
    $surname = "";
    $address = "";
    $dept= "";
    $mobile = "";

    // isset determine if a varaible is set
    
    
        
    if (isset($_POST['goSubmit']))
    {
        $name = $_POST['name'];
        $surname = $_POST['surname'];
        $address = $_POST['address'];
        $dept = $_POST['dept'];
        $mobile = $_POST['mobile'];
        
    print_r($_POST);

        $errormsg = "";
        
        if($name == "")
            $errormsg = $errormsg. "Name<br/ >";
            
        if ($surname == "")
            $errormsg = $errormsg. "Surname Please <br/ >";
            
        if ($mobile != "" && !is_numeric ($mobile))
            $errormsg = $errormsg. "Mobile No? <br/ >";
            
         if ($errormsg != "")
            echo "Please fill the blank info: <br/ > $errormsg";
            
            else
            {
                $input_field = "";
                
                
                foreach ($_POST as $key => $val)
                {
                    if ($key != 'goSubmit')
                    {
                    $_SESSION[$key] = $val;
                    
                    }
                }
                
                 header("Location: confirmPage.php");
                    
            }        
}   

    
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Modify Document</title>
</head>

<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <div align="center">
  <table width="300" border="1">
    <h1> Modifying A User </h1>
    
      <tr>
        <th scope="row">Name</th>
        <td><input type="text" name="name" value="<?php echo $name;?>" /></td>
      </tr>
    
    <tr>
      <th scope="row">Surname</th>
        <td>
        <input type="text" name="surname" value="<?php echo $surname; ?>" /></td>
      </tr>
    
    <tr>
      <th scope="row">Address</th>
        <td><input type="text" name="address" value="<?php echo $address; ?>" /></td>
    </tr>
      
        
    <tr>
      <th scope="row">Department</th>
        <td>
        
        <select name="dept">
            <option value="">Select..</option>

        <?php
        $data = mysql_query ("SELECT * FROM dept ORDER BY `id` DESC") or die (mysql_error());
      
          echo $data;
      
            while($row_dept = mysql_fetch_array( $data ))
        {
        ?>
        <option value="<?php echo $row_dept['id'] ;?>" <?php if($row_dept['id']==$dept){echo ' selected="selected"';}?>>
        <?php echo $row_dept['dept_name'] ;?>
        </option>
    
    <?php
    }
    ?>
        </select>
        </td>
    </tr>
    
    <tr>
      <th scope="row">Mobile</th>
        <td><input type="text" name="mobile" value="<?php echo $mobile; ?>" /></td>
      </tr>
  
  </table>
  <br/>
  
  <a href="indexPage.php">
    <input type="button" name="back" value="Back" /></a>
    
    <input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
    
    <input type="submit" name="goSubmit" value="Modify"/>
    
  </div>
</form>
</body>
</html>

 

I was thinking something like these condition to do the forms but I am not exactly sure... - But after this page another confirmation page will appear once the button submitted is click.

if (isset($_GET['id']) == $id) {
  //do the modify query
  //display the modify form
} else if (isset ($_GET ['id'] == NULL) {
  //display the form where user can fill up the form
} 

 

OR, can I do like this instead:

if (isset ($_GET['id'])) {
  $_SESSION ['page'] = 'modify';
  //perform the modify form
} else if (isset($_GET['id'])) {
  $_SESSION ['page'] = 'create';
//perform the create form
} 

 

Any inputs would be appreciated...

Link to comment
Share on other sites

Just a rough idea, not tested, not proof-read, no error trapping or cleansing.

 

the form page

<?PHP
/* determine if we are modifying or new */
if(isset($_GET['id']) {
$id = (int) $_GET['id'];
}else{
$id = 0;
}
/* if modifying connect to db and get the origianl values */
if($id>0) {
include('db.php');
/* create the query */
$query = "SELECT * FROM tablename WHERE id = $id";
/* execute the query */
$result = mysql_query($query);
/* count the results */
$num_rows = mysql_num_rows($result);
if($num_rows != 1) {
	/* bad id - do some error code and send user somewhere */
	exit(); /* make sure you stop the script here */
}
/* if you got here that means 1 record was found - so we can proceed */
/* since only 1 record matches - we do NOT need to loop */
$row = mysql_fetch_array($result);
/* assign values to the form field values */
$name_value = $row['name'];
$street_value = $row['street'];
}else{
$name_value = "";
$street_value = "";
}
/* display the form */
?>
<form action="process.php" method="post">
Name: <input type="text" name="name" size="40" maxlength="80" value="<?PHP echo $name_value; ?>"><br>
Name: <input type="text" name="street" size="40" maxlength="80" value="<?PHP echo $street_value; ?>"><br>
<input type="hidden" name="id" value="<?PHP echo $id; ?>">
<input type="submit" value="Submit">
</form>

the process page

<?PHP
/* get the form values */
$id = (int) $_POST['id'];
$name = $_POST['name'];
$street = $_POST['street'];
/* check to see if its modify or new */
if($id>0) {
$query ="UPDATE tablename set name = '$name', street = '$street' WHERE id = '$id'";
}else{
$query ="INSERT INTO tablename (name, street) values('$name', '$street')";
}
/* execute the query */
$result = mysql_query($query);
?>

Link to comment
Share on other sites

Hi

 

Another quick attempt, merging the 2 pages

 

<?php

require 'includes/application.php';    
//Define
$name = "";
$surname = "";
$add = "";
$dept= "";
$mobile = "";

if (isset($_POST['goSubmit']))
{
    $name = $_POST['name'];
    $surname = $_POST['surname'];
    $address = $_POST['address'];
    $dept = $_POST['dept'];
    $mobile = $_POST['mobile'];
}
else
{
    if (isset($_GET[id]))
    {
        $q = "SELECT * FROM persons WHERE ID = $_GET[id]";
        $result = mysql_query($q) or die (mysql_error());
        $row = mysql_fetch_array($result);
        $name = $row['name'];
        $surname = $row['surname'];
        $address = $row['address'];
        $dept = $row['dept_id'];
        $mobile = $row['mobile'];
    }
    else
    {
        $name = '';
        $surname = '';
        $address = '';
        $dept = '';
        $mobile = '';
    }
}

$errormsg = "";

if($name == "") $errormsg = $errormsg. "Name<br/ >";

if ($surname == "") $errormsg = $errormsg. "Surname Please <br/ >";

if ($mobile != "" && !is_numeric ($mobile)) $errormsg = $errormsg. "Mobile No? <br/ >";

if ($errormsg != "") echo "Please fill the blank info: <br/ > $errormsg";

else
{
    $input_field = "";
    foreach ($_POST as $key => $val)
    {
        if ($key != 'goSubmit')
        {
            $_SESSION[$key] = $val;
        }
    }    
    header("Location: confirmPage.php");
}        
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Modify Document</title>
</head>

<body>
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
        <div align="center">
        <table width="300" border="1">
            <h1> Modifying A User </h1>
            <tr>
                <th scope="row">Name</th>
                <td><input type="text" name="name" value="<?php echo $name;?>" /></td>
            </tr>
            <tr>
                <th scope="row">Surname</th>
                <td><input type="text" name="surname" value="<?php echo $surname; ?>" /></td>
            </tr>
            <tr>
                <th scope="row">Address</th>
                <td><input type="text" name="address" value="<?php echo $address; ?>" /></td>
            </tr>
            <tr>
                <th scope="row">Department</th>
                <td>
                    <select name="dept">
                    <option value="">Select..</option>
                    <?php
                    $data = mysql_query ("SELECT * FROM dept ORDER BY `id` DESC") or die (mysql_error());
                    echo $data;
                    while($row_dept = mysql_fetch_array( $data ))
                    {
                        echo "<option value='$row_dept[id]'".(($row_dept['id']==$dept) ? ' selected="selected"' : '').">".$row_dept['dept_name']."</option>";            
                    }
                    ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th scope="row">Mobile</th>
                <td><input type="text" name="mobile" value="<?php echo $mobile; ?>" /></td>
            </tr>
        </table>
        <br/>
        <a href="indexPage.php"><input type="button" name="back" value="Back" /></a>
        <input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
        <input type="submit" name="goSubmit" value="Modify"/>
        </div>
    </form>
</body>

 

All the best

 

Keith

Link to comment
Share on other sites

First of all thanks guys, really appreciated of your inputs. The other thing that puzzle me is: How can we tell the user have click modify page or create new user link?

 

I have this index page  (index.php) in table format which have all the user details from database. And there are hyper-link for create user and modify user. These two links will take me to same form page say (newForm.php) which allow me to create a new user or modify the existing user.

 

I think on my main page (index page) hyper-link I need to do add some kind of query like:

<a href = "newForm.php?page = modify&id=$_GET['id']"> </a>

<a href = "newForm.php?page = create&id=-1"> </a>

to point and determine which link been clicked and which form should be perform? And on my newForm.php page I will have to add some query to tell that link is from create or modify. Any ideas guys?

Link to comment
Share on other sites

If your links look like:

<a href = "newForm.php?page=modify&id=<?php echo $_GET['id']; ?>">Edit</a>
<a href = "newForm.php?page=create">Create New</a>

Note that I removed the "id=-1" since it not necessary.

 

 

You can then build your PHP script around:

 

if(isset($_GET['page']) && $_GET['page'] == 'create') {
...
} elseif(isset($_GET['page']) && $_GET['page'] == 'modify') {
    //GET ID
    if(isset($_GET['id'])) {
        $id = trim($_GET['id']);
    }
    ...
}

Link to comment
Share on other sites

Thanks guy, well I have put the query on my main index so only the modify can call which id should be edited and for create it will just calling NULL as cyberRobot suggested.

 

The problem is now: when I clicked either one of these links:

 

<a href = "newForm.php?page=modify&id=<?php echo $_GET['id']; ?>">Edit</a>
<a href = "newForm.php?page=create">Create New</a>

 

it takes me to the same create page form. I use the code of post#reply 3 that kickstart suggested but whenever I clicked the link from my main page it both take me to the blank fill form (newForm page) with error checking display on them

 

"Please fill the blank info:

Name

Surname Please "

 

Do you think I need to add something on the newForm page? so that will indicates which form it should go to?

Link to comment
Share on other sites

For the create new option, I'm assuming that you want a blank form. But for the edit form, you'll want to get the data based on the ID and use it to populate the form. Hopefully this will be enough to get you started:

 

<?php
if(isset($_GET['page']) && $_GET['page'] == 'create') {
    //INITIALIZE VARIABLES
    $name = '';
    ...

} elseif(isset($_GET['page']) && $_GET['page'] == 'modify') {
    //GET ID
    if(isset($_GET['id'])) {
        $id = trim($_GET['id']);
    }
    ...
    
    //GET INFORMATION BASED ON THE ID
    ... //SQL query goes here
    
    //INITIALIZE VARIABLES BASED ON THE ID
    $name = $row['name'];
    ...
}

//DISPLAY THE FORM
?>
...
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
...
<th scope="row">Name</th>
<td><input type="text" name="name" value="<?php echo $name;?>" /></td>
...

 

 

FYI, you'll want to be careful with $_SERVER['PHP_SELF'] due to XSS vulnerabilities.

Link to comment
Share on other sites

I use the code of post#reply 3 that kickstart suggested but whenever I clicked the link from my main page it both take me to the blank fill form (newForm page) with error checking display on them

 

My fault. I missed a couple of quotes.

 

if (isset($_GET['id']))

 

All the best

 

Keith

Link to comment
Share on other sites

Thanks guys,

 

I've sort of worked that out but I still having one problem which is the confirmation page. When user edit or create a new user on the newForm page then it redirect to the confirmation page before submitting all the details to the main page. This confirmation page will be involved sessions and two queries which are UPDATE and INSERT.

 

Any ideas how this work?

Link to comment
Share on other sites

Thanks Keith,

 

Well I tried to come up with this confirmation page (confirmPage.php) but when user arrives at the new form page (newForm.php which is either modify the details or create a new user) and user click the button (Modify or Create) it will directly go to the main page (indexPage.php) with the current updated / new user details but it did not show or go to the confirmation page form. I don't understand why.

 

What I want is, from the main page user can choose two hyper-link either Create New User or Modify User both of these links will bring the user to the same page (newForm.php) depends on what they want to do, after that user will click the button either Modify or Create and the confirmation page form will appear then if they are happy with it then they can submit the details direct to the main page (indexPage.php).

 

Can you please assist me what I did wrong on the code?

 

confirmPage

<?php
session_start();
require 'includes/application.php';
   

  if (!isset($_SESSION['mode'])) {

    exit("Invalid session data");

  } else if ($_SESSION['mode'] == 'Modifying') {

   // We are modfying the DB
    $modify_sql = "UPDATE `persons` SET `name` = '".$_SESSION['name']."', `surname` = '".$_SESSION['surname']."', `address` = '".$_SESSION
['address']."', `mobile` = '".$_SESSION['mobile']."', `dept_id`= '".$_SESSION['dept']."' WHERE `id` = '".$_SESSION['id']."'";
    mysql_query($modify_sql) or die (mysql_error());    

    header("Location: http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/indexPage.php?id=".$_SESSION['id']."&page=modify");

  } else {

    // We are creating a new entry
    $create_sql = "INSERT INTO `persons` (`name`,`surname`,`dept_id`,`address`,`mobile`) VALUES ('".$_SESSION['name']."','".$_SESSION['surname']."','".$_SESSION['dept']."','".$_SESSION['address']."','".$_SESSION['mobile']."')";
    mysql_query($create_sql) or die (mysql_error());

    header("Location: http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/indexPage.php?id=".mysql_insert_id()."&page=create");
  }

?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Confirmation Page</title>
</head>

<body>

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<div align="center">
  <table width="200" border="1">
    <h1>Are You Happy With These Info?</h1>
    <tr>
      <th scope="row">First Name</th>
      <td><?php echo $_SESSION['name'];?> </td>
    </tr>
    
    <tr>
      <th scope="row">Surname</th>
      <td><?php echo $_SESSION['surname'];?></td>
    </tr>

<tr>
      <th scope="row">Address</th>
      <td><?php echo $_SESSION['address'];?></td>
    </tr>
    
   	
    <!--Department Modify Form-->

   <tr>
      <th scope="row">Department</th> 
	<td>         

  	<?php

	$data = mysql_query ("SELECT dept_name FROM dept WHERE id = '".$_SESSION['dept']."'") or die (mysql_error());
     
		$row_dept= mysql_fetch_array( $data );

      		$_SESSION['dept_name'] = $row_dept['dept_name'];
		echo $_SESSION['dept_name'];

	?>
	</td>
</tr>

<!--End Department-->
    <tr>
      <th scope="row">Mobile</th>
      <td><?php echo $_SESSION['mobile'];?> </td>
    </tr>

<tr>
<td colspan="2" align="center"><p>
<br/ >
    <input type="button" value="Back" onclick="history.go(-1)" />
    
	<?php 
	foreach ($_POST as $key => $val)
			echo $_SESSION[$key] = $val;
	?>
	<input type="submit" name="mode" value="<?php echo ($_SESSION['mode'] == "Modifying") ? 'Create' : 'Modify'; ?>"/>

        </td>
</tr>

</table>
  
</div>
</form>
</body>
</html>

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.