I am trying to learn PHP. I have set up a database, a table, and made a form that allows me to add new rows to the table when the submit button is clicked. The problem is that the form also submits any time the page is loaded or refreshed, which results in a bunch of empty rows in my database table.

How do I make it so that my PHP form only submits when the user clicks the submit button or clicks the enter key?

You can see the page for yourself here:

Here is my HTML form:

<form method="post" action="things-to-do3.php" class="form">
<div class="formfield">Person: <input type="text" name="person" /></div>
<div class="formfield">Task: <input type="text" name="task" /></div>
<div class="formfield">Time: <input type="text" name="time" /></div>
<div class="formfield">Completion Status: <input type="text" name="completed" /></div>
<div class="formfield"><input type="submit" /></div>

Here is my PHP which is located in the same .php file:

/*Connect to the database */
$connect = mysql_connect("**********","**********","**********");
if (!$connect)
	die('Could not connect to the database: ' . mysql_error());

/* Insert the data from the form into the database */
$sql = "INSERT INTO ThingsToDo (Person, Task, Time, Completed)

/*Notify user if data insertion was successful or not */
if (!mysql_query($sql,$connect))
  die('Error: ' . mysql_error());
echo "1 record added<br>";

$query = "SELECT * FROM ThingsToDo";
$result = mysql_query($query);
$num = mysql_num_rows($result);
while ($i < $num) {
	/*display something */
	$person		=mysql_result($result,$i,"person");
	$task		=mysql_result($result,$i,"task");
	$time		=mysql_result($result,$i,"time");
	$completed	=mysql_result($result,$i,"completed");
	// This will test TRUE if the integer is even
	/* */
	if (($i % 2) == 0)
		$state = "even";
		$state = "odd";
	//echo "<b>$person</b><br>$task<br>$time<br>$completed<br><hr><br>";
	echo "
		<div class='row $state'>
		<span class='person'>$person</span>
		<span class='task'>$task</span>
		<span class='time'>$time</span>
		<span class='completed'>$completed</span>
		<div style='clear:both;'></div>";


(I will worry about form validation later, I'm new to PHP so baby steps!)

Add a name and a value to your <input type=submit> in the first part (e.g. name=submit value=submit> . The second part then needs to be surrounded by an if and a closing bracket. The If needs to check $_POST.You only want to execute the second part if $_POST has a value of 'submit'.

In the current version, you execute the second part every time the module is executed (even the very first time) so that will give you a blank record in the database even if you don't refresh the page.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.