Forum Moderators: coopster
I have a page with a form, a statement and a query. This page is called:
form.php
When a user enters data into the form and presses submit, that data is inserted into a database, and the user is presented with a success message.
However, the problem is, whenever I access (form.php?action=add) without pressing submit it also runs the query which inserts blank data into the database.
Is there an easy and simple way to stop this from happening, either by adding a checkform or somehow rearranging the codes to work properly? I would like to keep all these codes on one page without calling up anything else...
<?php
if ($action == add) {
echo "Success!";
mysql_query("INSERT INTO database (data) VALUES('$data') ");
}
?>
<form action="form.php?action=add" method="post">
<input type="text" name="data">
<input type="submit" value="submit">
</form>
<?php
if(($_POST["action"] == "submit") &&!empty($_POST["data"]))
{
echo "To return to form click <a href=\"form.html\">here</a>";
mysql_query("INSERT INTO database (data) VALUES('$data') ") or die("Sorry, couldn't insert data to database.");
echo "Success!";
}
else
{
?>
<form action="form.php" method="post">
<input type="text" name="data">
<input type="submit" name="action" value="submit">
</form>
<?php
}
?>
I took both suggestions and created a customized version, but there is one last problem. If the user doesn't enter either a name or text, nothing is inserted into the database, however, there is also no error message letting them know the form failed. Everything else works as planned! Here's the code so far
__________________
<?php
if (($_POST["c_name"]!="") &&($_POST["c_text"]!=""))
{
mysql_connect("x", "x", "x");
mysql_select_db("x");
mysql_query("INSERT INTO x (c_name, c_text) VALUES('$c_name', '$c_text') ");
echo "Success!";
}
?>
<br>
<form action="test.php" method="post">
<input type="text" name="c_name" size="10">
<input type="text" name="c_text" size="50">
<input type="submit" name="submit" value="submit">
</form>
<?php
if (($_POST["c_name"]!= "") && ($_POST["c_text"]!= ""))//all correct
{
mysql_connect("x", "x", "x");
mysql_select_db("x");
mysql_query("INSERT INTO x (c_name, c_text) VALUES('$c_name', '$c_text') ");
echo "Success!";
}
elseif($_POST["submit"])//submited form, but empty values
{
echo "Missing name or text!<br>Please fill in the form before submiting.";
}
?>
<br>
<form action="test.php" method="post">
<input type="text" name="c_name" size="10">
<input type="text" name="c_text" size="50">
<input type="submit" name="submit" value="submit">
</form>
The elseif will do the job!
Michal Cibor