简体   繁体   中英

How to connect function to button?

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?

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.

<?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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM