Jump to content

PHP FORM


hmiller73

Recommended Posts

I am having trouble with a form.

 

I am to have 1 script that will do the following:

 

Two form fields : Name, Email

1 Submit Button

 

On submit it should write the Name and Email to an SQL database

and it should return all the data in the database tables below the form.

 

When I load my script it shows all the data in the database tables, it is not waiting for me to hit submit.

 

here is my code: Please note I am just learning php.

 

Instructors notes:

 

Your form will be identical to the original form, it will have one submit button.

 

your script will do two actions (actually three)

1) get the POST data and put it in the DB -- if no data (because this isn't the result of a 'submit'), then skip this step.

2) display the form with the proper name and e-mail inserted

3) get the elements from the DB and display them below the form.

 

Yes, you will be able to do all this with one script.

 

<?php

/* your logic to process the POST data  including connecting to MySQL and putting it into the database */

 

// Receiving variables

@$ip= $_SERVER['REMOTE_ADDR'];

@$name = addslashes($_POST['name']);

@$email = addslashes($_POST['email']);

 

// Validation

//saving record to MySQL database

 

 

@$strQuery = "INSERT INTO `email`(`Name`,`email`)VALUES (\"$name\",\"$email\")" ;

@$host = "localhost";

@$user = "root";

@$pw = "";

@$db = "week3";

$link = mysql_connect($host, $user, $pw);

if (!$link) {

die('Could not connect: ' . mysql_error());

}

$db_selected = mysql_select_db($db, $link);

if (!$db_selected) {

die ('Can not use $db : ' . mysql_error());

}

 

//insert new record

$result = mysql_query($strQuery);

if (!$result) {

die('Invalid query: ' . mysql_error());

}

mysql_close($link);

 

$sql = "SELECT * FROM `email` WHERE 1 LIMIT 0, 30 ";

 

mysql_connect("localhost", "root", "") or die(mysql_error());

 

mysql_select_db("week3") or die(mysql_error());

 

 

// Retrieve all the data from the "email" table

$result = mysql_query("SELECT * FROM email")

or die(mysql_error()); 

 

// store the record of the "email" table into $row

$row = mysql_fetch_array( $result );

 

?>

 

<head>

 

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>myform</title>

 

</head>

 

<body>

<div id="apDiv1">

  <form id="form1" name="form1" method="post" action="working.php">

    <p>Name

   

      <input type="text" name="name" id="name" />

    </p>

    <p> </p>

    <p>Email

      <input type="text" name="email" id="email" />

      <input type="submit" name="submit" id="submit" value="Submit" />

    </p>

  </form>

</div>

</body>

</html>

<?php

echo "<table border='1'>";

echo "<tr> <th>Name</th> <th>Email</th> </tr>";

 

// keeps getting the next row until there are no more to get

while($row = mysql_fetch_array( $result )) {

// Print out the contents of each row into a table

echo "<tr><td>";

echo $row['Name'];

echo "</td><td>";

echo $row['email'];

echo "</td></tr>";

}

 

echo "</table>";

?>

Link to comment
Share on other sites

so whats the question, specifically

 

reposted using the code tags, its the button that looks like a pound sign #, please use it

<?php
/* your logic to process the POST data  including connecting to MySQL and putting it into the database */

// Receiving variables
@$ip= $_SERVER['REMOTE_ADDR'];
@$name = addslashes($_POST['name']);
@$email = addslashes($_POST['email']);

// Validation
//saving record to MySQL database


@$strQuery = "INSERT INTO `email`(`Name`,`email`)VALUES (\"$name\",\"$email\")" ;
@$host = "localhost";
@$user = "root";
@$pw = "";
@$db = "week3";
$link = mysql_connect($host, $user, $pw);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db($db, $link);
if (!$db_selected) {
die ('Can not use $db : ' . mysql_error());
}

//insert new record
$result = mysql_query($strQuery);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
mysql_close($link);

$sql = "SELECT * FROM `email` WHERE 1 LIMIT 0, 30 ";

mysql_connect("localhost", "root", "") or die(mysql_error());

mysql_select_db("week3") or die(mysql_error());


// Retrieve all the data from the "email" table
$result = mysql_query("SELECT * FROM email")
or die(mysql_error()); 

// store the record of the "email" table into $row
$row = mysql_fetch_array( $result );

?>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>myform</title>

</head>

<body>
<div id="apDiv1">
  <form id="form1" name="form1" method="post" action="working.php">
    <p>Name
   
      <input type="text" name="name" id="name" />
    </p>
    <p> </p>
    <p>Email
      <input type="text" name="email" id="email" />
      <input type="submit" name="submit" id="submit" value="Submit" />
    </p>
  </form>
</div>
</body>
</html>
<?php
echo "<table border='1'>";
echo "<tr> <th>Name</th> <th>Email</th> </tr>";

// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
   // Print out the contents of each row into a table
   echo "<tr><td>";
   echo $row['Name'];
   echo "</td><td>";
   echo $row['email'];
   echo "</td></tr>";
}

echo "</table>";
?>

Link to comment
Share on other sites

I would follow the links in my sig, not to pimp my own site, but my response would basically be what is written there...

 

basically what you need to do is create a series of functions and then organize them logically

 

read part one, it sets up part 2 so that part 2 makes sense, but part 2 is what your really need, especially the first code sample of part 2, the main page logic.

 

//hint: you can call show_form() inside of process_form(), or you can change the page logic to redisplay the form after submit

 

edit: your teacher will be blown away with your organizational skills from such a begining student if you use my method, and you will do well in your class if you understand it

Link to comment
Share on other sites

Thanks for the help, but I am totally lost on this. I don't know how to code this so that it works and I have no book to teach me. What I have in my code I have had to hunt and peck searching the Internet. I am pulling my hair out.

 

My teacher expected us to learn PHP on our own to no references to learn from. I wish I could understand what you were asking me to do, but I don't.

 

Thank you for attempting to help me

Link to comment
Share on other sites

you are on the right track, your code needs a bit of work, but I can see what you are trying to do, so it does have some form to it.

 

read : http://scriptingsource.com/2009/01/form-processing-made-easy-part-one/ and part 2 (its linked all over the place in there)

 

if you are piece mealing this thing together, this will give you some more pieces, in fact, based on what you already have, if you adapt to the above method, I think it will finish the job

 

but go get a book, my recomendation is learning php5, by david sklar

Link to comment
Share on other sites

any time that I mention "just include this file..." just copy that code directly into your php file... for instance, the html form you have right now, instead of using

show_form(){
require_once('form.html');
}

 

just replace the require_once with a HEREDOC of your form. that right there should get rid of the only include I used... assuming your not using pear db, go with phps mysql functions and there is now no need for any other documents

Link to comment
Share on other sites

I can only have one file. It has to be a php file extension and it had to include the html form coding within that file.

 

If I would use more thank one file I would have this fixed already,  but the instructor just wants one.

 

I am to the point of tears in frustration with this. I have spent 16 hr today alone trying to research code on the internet.

 

I have yet to find code that will do all of that I need to in one file.

 

 

Link to comment
Share on other sites

I have redone my script, but now it is not returning all the data in the database table. It is only returning what I just submitted.

 

here is my new code.

 

</html>

<head>

 

<title>myform</title>

 

</head>

 

<body>

 

  <form method="post" action="test.php">

 

    Name: <br />

   

      <input type="text" name="name" size="30" /><br />

   

    Email: <br />

      <input type="text" name="email" size="30" /><br />

     

      <input type="submit" value="Submit" />

 

  </form>

 

</body>

</html>

<?php

$databasename='week3'; // Name of the database

$tablename='email'; // Name of the table

$mysqladd='localhost'; // Address to the MySQL Server - Usually localhost or an IP address

$mysqluser='root'; // Your MySQL UserName

$mysqlpass=''; // Your MySQL Password

@$name = addslashes($_POST['name']);

@$email = addslashes($_POST['email']);

 

///CONNECT TO MYSQL working

$link=mysql_connect($mysqladd,$mysqluser,$mysqlpass) or die('Database Error: ' . mysql_error());

 

 

//CONNECT TO DATABASE working

mysql_select_db($databasename, $link) or die('Could not connect to table: ' . mysql_error());

 

//Get data from Text, Post data to database working

$strQuery = "INSERT INTO `email`(`name`,`email`)VALUES (\"$name\",\"$email\")" ;

$result = mysql_query($strQuery);

if (!$result) { die('Invalid query: ' . mysql_error());

}

 

// print data table from database

 

$result = mysql_query("SELECT * FROM email");

 

if($row = mysql_fetch_array($result))

  {

 

  echo $row['name'];

  echo $row['email'];

  echo "<br />";

    }

  // this doesn't return all the data in the table. It is only returning what I just entered.

 

?>

 

Link to comment
Share on other sites

can you please do us a favor and use


tags?

 

</html>
<head>

<title>myform</title>

</head>

<body>

  <form method="post" action="test.php">

    Name: <br />
    
      <input type="text" name="name" size="30" /><br />
    
    Email: <br />
      <input type="text" name="email" size="30" /><br />
      
      <input type="submit" value="Submit" />
   
  </form>

</body>
</html>
<?php 
$databasename='week3'; // Name of the database
$tablename='email'; // Name of the table
$mysqladd='localhost'; // Address to the MySQL Server - Usually localhost or an IP address
$mysqluser='root'; // Your MySQL UserName
$mysqlpass=''; // Your MySQL Password
@$name = addslashes($_POST['name']);
@$email = addslashes($_POST['email']);

///CONNECT TO MYSQL working
$link=mysql_connect($mysqladd,$mysqluser,$mysqlpass) or die('Database Error: ' . mysql_error());


//CONNECT TO DATABASE working
mysql_select_db($databasename, $link) or die('Could not connect to table: ' . mysql_error());

//Get data from Text, Post data to database working
$strQuery = "INSERT INTO `email`(`name`,`email`)VALUES (\"$name\",\"$email\")" ;
$result = mysql_query($strQuery);
if (!$result) { die('Invalid query: ' . mysql_error());
}

// print data table from database

$result = mysql_query("SELECT * FROM email");

if($row = mysql_fetch_array($result))
  {
  
  echo $row['name'];
  echo $row['email'];
  echo "<br />";
    }
  // this doesn't return all the data in the table. It is only returning what I just entered.

?>

Link to comment
Share on other sites

i jsut showed you up there

 

 <?php //some php code here ?>

 

anyway this is proborably what you want i also added in some error handling for you.

 

</html>
<head>

<title>myform</title>

</head>

<body>

  <form method="post" action="test.php">

    Name: <br />
    
      <input type="text" name="name" size="30" value="<?php if(!empty($_SESSION['name'])) { echo $_SESSION['name']; } ?>" /><br />
      <?php if(!empty($_SESSION['nameerror'])){ echo "The name field cannot be left empty!"; } ?>
    
    Email: <br />
      <input type="text" name="email" size="30" value="<?php if(!empty($_SESSION['email'])) { echo $_SESSION['email']; } ?>" /><br />
      <?php if(!empty($_SESSION['emailerror'])){ echo "The email field cannot be left empty!"; } ?>
      <input type="submit" value="Submit" />
   
  </form>

</body>
</html>
<?php 
$_SESSION['emailerror'] = ''; 
$_SESSION['nameerror'] = ''; 
$_SESSION['email'] = '';
$_SESSION['name'] = '';  

if($_POST['submit'])
{
 if(empty($_POST['email']) && empty($_POST['name']))
{
 	$_SESSION['emailerror'] = '1';
 	$_SESSION['nameerror'] = '1';
 	header("location: $_SERVER[php_SELF]");
}
elseif(empty($_POST['email']))
{
	$_SESSION['emailerror'] = '1';
	$_SESSION['name'] = $_POST['name'];
 	header("location: $_SERVER[php_SELF]");	
}
elseif(empty($_POST['name']))
{
	$_SESSION['nameerror'] = '1';
	$_SESSION['email'] = $_POST['email'];
 	header("location: $_SERVER[php_SELF]");	
}

$databasename='week3'; // Name of the database
$tablename='email'; // Name of the table
$mysqladd='localhost'; // Address to the MySQL Server - Usually localhost or an IP address
$mysqluser='root'; // Your MySQL UserName
$mysqlpass=''; // Your MySQL Password
@$name = addslashes($_POST['name']);
@$email = addslashes($_POST['email']);

///CONNECT TO MYSQL working
$link=mysql_connect($mysqladd,$mysqluser,$mysqlpass) or die('Database Error: ' . mysql_error());


//CONNECT TO DATABASE working
mysql_select_db($databasename, $link) or die('Could not connect to table: ' . mysql_error());

//Get data from Text, Post data to database working
$strQuery = "INSERT INTO `email`(`name`,`email`)VALUES (\"$name\",\"$email\")" ;
$result = mysql_query($strQuery);
if (!$result) 
{
	die('Invalid query: ' . mysql_error());
}

// print data table from database

$result = mysql_query("SELECT * FROM email");

while($row = mysql_fetch_array($result))
  	{
  
  		echo $row['name'];
  		echo $row['email'];
  		echo "<hr />";
    }
  	// this doesn't return all the data in the table. It is only returning what I just entered.
}
?>

Link to comment
Share on other sites

Sure,

 

the basics of what i changed was

see how everything after the

$_SESSION['emailerror'] = ''; 
$_SESSION['nameerror'] = ''; 
$_SESSION['email'] = '';
$_SESSION['name'] = ''; 

 

is encased in the

if(isset($_POST['submit'])) { }

 

youll notice your submit button is called submit so basically its saying only run the code if $_POST['submit'] is set.

which the only way this can get set is via pressing the submit button.

 

as for the error handling thats jsut an extra i added in.

basically you'll see that i have put

<?php if(!empty($_SESSION['nameerror'])){ echo "The name field cannot be left empty!"; } ?>

with the name changed for email). that basically says if the error session is NOT(!) empty then display the message.

 

These only get set if they are empty.

this is so that your users dont get confused as to why it is not submitting there details.

 

not youll notice ive added

value="<?php if(!empty($_SESSION['name'])) { echo $_SESSION['name']; } ?>"

(with the name changed for email again)

this is simply saying if the value is set the echo it there.

 

this means that if your user puts in the email but not the name then they will get the message saying they cant leave name blank, and email will already be filled out for them.

 

this part here

$_SESSION['emailerror'] = ''; 
$_SESSION['nameerror'] = ''; 
$_SESSION['email'] = '';
$_SESSION['name'] = ''; 

is after the form. because the values get shown in the form we cant clear it above the form.

 

and we have to clear it above the if statements because the value in the if statements will not get set.

 

any other questions just ask.

 

btw good on you for asking to get it explained, alot of people simply go ive got working code i dont need to know how it works and thats wrong, because then we end up with those same poeple asking the same questions again.

 

Matt

 

 

Link to comment
Share on other sites

after all that excitement I realize that the line pointing to the test.php was not the same as the file I named it. There for when It ran on submit it went to the other php file for the commands.

 

Which is why it returned the data on submit.

 

I can only have one file.

 

So when I changed that to the new file I create, I do not get any error statements when I submit blank info and I don't send the data I submit to the database.

 

So now I am really confused.

Link to comment
Share on other sites

oh sorry mate,

 

um here you go

 

</html>
<head>

<title>myform</title>

</head>

<body>

  <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">

    Name: <br />
    
      <input type="text" name="name" size="30" value="<?php if(!empty($_SESSION['name'])) { echo $_SESSION['name']; } ?>" /><br />
      <?php if(!empty($_SESSION['nameerror'])){ echo "The name field cannot be left empty!"; } ?>
    
    Email: <br />
      <input type="text" name="email" size="30" value="<?php if(!empty($_SESSION['email'])) { echo $_SESSION['email']; } ?>" /><br />
      <?php if(!empty($_SESSION['emailerror'])){ echo "The email field cannot be left empty!"; } ?>
      <input type="submit" value="Submit" />
   
  </form>

</body>
</html>
<?php 
$_SESSION['emailerror'] = ''; 
$_SESSION['nameerror'] = ''; 
$_SESSION['email'] = '';
$_SESSION['name'] = '';  

if($_POST['submit'])
{
 if(empty($_POST['email']) && empty($_POST['name']))
{
 	$_SESSION['emailerror'] = '1';
 	$_SESSION['nameerror'] = '1';
 	header("location: $_SERVER[php_SELF]");
}
elseif(empty($_POST['email']))
{
	$_SESSION['emailerror'] = '1';
	$_SESSION['name'] = $_POST['name'];
 	header("location: $_SERVER[php_SELF]");	
}
elseif(empty($_POST['name']))
{
	$_SESSION['nameerror'] = '1';
	$_SESSION['email'] = $_POST['email'];
 	header("location: $_SERVER[php_SELF]");	
}

$databasename='week3'; // Name of the database
$tablename='email'; // Name of the table
$mysqladd='localhost'; // Address to the MySQL Server - Usually localhost or an IP address
$mysqluser='root'; // Your MySQL UserName
$mysqlpass=''; // Your MySQL Password
@$name = addslashes($_POST['name']);
@$email = addslashes($_POST['email']);

///CONNECT TO MYSQL working
$link=mysql_connect($mysqladd,$mysqluser,$mysqlpass) or die('Database Error: ' . mysql_error());


//CONNECT TO DATABASE working
mysql_select_db($databasename, $link) or die('Could not connect to table: ' . mysql_error());

//Get data from Text, Post data to database working
$strQuery = "INSERT INTO `email`(`name`,`email`)VALUES (\"$name\",\"$email\")" ;
$result = mysql_query($strQuery);
if (!$result) 
{
	die('Invalid query: ' . mysql_error());
}

// print data table from database

$result = mysql_query("SELECT * FROM email");

while($row = mysql_fetch_array($result))
  	{
  
  		echo $row['name'];
  		echo $row['email'];
  		echo "<hr />";
    }
  	// this doesn't return all the data in the table. It is only returning what I just entered.
}
?>

 

youll nitoce i changed test.php to the php server variable PHP_SELF, this basically says use this file as the action

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.