Search code examples
phphtmlinputhidden

How to automatically put the value in an input while hidden after I click submit?


This is the input part:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">                                   
    <input type="hidden" name="ldbal" value="2000">
    <input type="submit" name="btn-signup" class="btnreg" value="Register">
</form>

Now this is where I am going to submit the data and I want the value "2000" in the ldbal input to be inserted in the database while hidden.

<?php
    if(isset($_POST['btn-signup']))
    {
        $Ldbal = $_POST['ldbal'];

        $ins="INSERT INTO customers (Cus_Loadbal) VALUES ('$Ldbal')";
        if($conn->query($ins)===TRUE)
        {
            <div class="alertinfo2">
                <strong>Congrats!</strong>
            </div>
        }
        else
        {
            ?>
                <div class="alertinfo2">
                    <strong>Sorry!</strong> Failed to insert. Please try again
                </div>
            <?php
        }
    }
?>

But when check the database, the value is always 0. Can you please help me?

PS: I removed parts of the code to reduce the length. I left what is essential.


Solution

  • You can do it like this:

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return updateHidden()" method="POST">                                   
            <input type="hidden" name="ldbal"  id="ldbal" value="2000">
            <input type="submit" name="btn-signup" class="btnreg" value="Register">
    </form>
    

    Create a JS function where you will set the value like this:

    function updateHidden(){
       $("ldbal").val("set whateve value you want to set");  
       // don't forget to define the id
       return true; // if you change it to false, the form won't get submitted.
    
    }
    

    PS. The way you are adding value into the database will lead to SQL Injection (read about it) and write secure code to avoid sql injection.