Reputation: 35
I have a little contact code for user to input like so:
First name:<br>
<input type = "text" name = "firstname"><br>
Last name:<br>
<input type = "text" name = "lastname"><br>
Email:<br>
<input type = "email" name = "email"><br>
Text:<br>
<textarea rows = "10" cols = "50" name = "textbox"></textarea>
<br>
<input type = "submit" name = "submit" value = "Submit">
<br>
and I have this php function to run if fields that user inputs are empty:
<?php>
if(!empty($_POST[firstname] && (!empty$_POST[lastname]) && (!empty$_POST[email]) &&
$_POST[textbox]))
{
}
?>
My question is how to connect this button "Submit" to this function and how to have a text above it saying "You need to not leave empty fields!" for example?
Upvotes: 1
Views: 59
Reputation: 11
<?php
if($_POST['submit']){
if( empty($_POST['firstname']) || empty($_POST['lastname']) || empty($_POST['email']) || empty($_POST['textbox']) )
{
echo "You need to not leave empty fields!";
}
}
?>
<form method="POST">
First name:<br>
<input type = "text" name = "firstname"><br>
Last name:<br>
<input type = "text" name = "lastname"><br>
Email:<br>
<input type = "email" name = "email"><br>
Text:<br>
<textarea rows = "10" cols = "50" name = "textbox"></textarea>
<br>
<input type = "submit" name = "submit" value = "Submit">
<br>
</form>
Upvotes: 1
Reputation: 74217
Your code is missing form tags with a post method and a few brackets.
Note: I removed the !
operator since that means "not", but you can put those back in if you want to use it another way and changing the echo message.
Also, quote the arrays since that could throw a few notices.
This is what your code should look like and using ||
(OR) instead of &&
(AND) to check if any are empty.
HTML:
<form action="handler.php" method="post">
First name:<br>
<input type = "text" name = "firstname"><br>
Last name:<br>
<input type = "text" name = "lastname"><br>
Email:<br>
<input type = "email" name = "email"><br>
Text:<br>
<textarea rows = "10" cols = "50" name = "textbox"></textarea>
<br>
<input type = "submit" name = "submit" value = "Submit">
<br>
</form>
PHP (handler.php):
<?php
if(empty($_POST['firstname']) || empty($_POST['lastname'])
|| empty($_POST['email']) || empty($_POST['textbox']))
{
echo "Some fields were left empty.";
}
?>
Side note: You need to run this off a webserver with PHP installed with a server protocol (HTTP/HTTPS) and not directly into your browser as file:///
since that will not parse any of the PHP directives.
Upvotes: 1