Olasunkanmi Adeniji
Olasunkanmi Adeniji

Reputation: 81

validating a form field from 2 tables using php and mysql

I have an issue.. I created a php script that generates random number: the script goes thus:

</head>
<div id="inner-content">
<form action="" method="post" name="form1">
<fieldset>
<legend>Please click on the button to generate a random number</legend>
<input type="submit" value="Generate" /><br />
<?php
$length = 10;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX‌​YZ"), 0, $length);
echo "$randomString";
?>
<p>
<input type="button" name="button1" value="Save" />
</div>
</fieldset>
<body>
</body>
</html>

Now i have have two serious worries: 1) How do i trap the generated number and save it into a database owing to the fact that the submit button is the one generating the random number. I want a situation whereby when we click save, the number goes into the database.

2) I have two tables,(table A and table B, table A saves all the information being entered and submitted by the user, table B has the generated codes, table A will love to validate a particular field from the form and validate the code in table B, then if codes matches, the user can submit, else the user gets an error and asked to fill in the correct code which resides in table B.also, i have the controller from table A which saves the form. here's the form.

Upvotes: 0

Views: 719

Answers (1)

linkboss
linkboss

Reputation: 676

The problem here is, like the comments on your post pointed it out, that your code is executed all the way before being sent to the browser. It implies that your random string (and not number with what I see) is generated and shown directly before the client has clicked on any button.

To solve this problem, you have to do this in 2 steps : first, if the user hasn't entered anything yet, show the form. Then, if the user has already submitted the form (making it reload the page), you can generate your random number and show it.

Here is how it can be solved (I did not include HTML headers, just relevant code) :

<?php

//Checking if the user has already validated the form we show the string
if(isset($_POST["submit"]))
{
    $length = 10;
    $randomString =  substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX‌​YZ"), 0, $length);
    echo "$randomString";
}
else //If he hadn't show the form
{
    ?>
    <form method="post" action="">
        <input type="submit" name="submit" value="Generate string" />
    </form>
    <?php
}
?>

Then you can save it in your database (you can make it optional for example by adding a checkbox in your form and checking after your generation if it is checked, then saving into database if it is).

Upvotes: 1

Related Questions