Is there any procedure where I can ask the form action in html to load a function in PHP instead of loading another PHP file? My problem goes like this, I want to insert data into a database table with $_POST. I wrote the script in the same page where the form is. But each time I access the file in browser, it is creating a empty field in the database table. So I wrote the insert code in another file and sending form action to that file. Now the problem is, the browser goes and stays at newfile.php I want it to come back to the main page where my form is. How can I fix the problem?
Lots of ways: Ajax--use javascript to call newfile.php while staying on the same page. Validation--keep your current set up, but add a test to see if someone is really trying to insert data or just seeing the page for the first time. If not submitting the form, don't run that code. Redirect--have the newfile.php redirect back to where you want it to go after it inserts the data.
here is the problem. use the same file as the form as your target. now you look at your submit button. f.e. it is named "submit", so we do a check in our form file: $submit = isset($_POST['submit']) ? true : false; Code (markup): Now we know if someone submits the form and make this to our switch: if ($submit) { // insert data } Code (markup): In addition you should add some more checks. Maybe someone needs to write a name in the form and this name needs to be 4 chars long in minimum: $name = isset($_POST['name']) ? trim($_POST['name']) : ''; $name = strlen($name) > 3 ? $name : ''; Code (markup): Now we can ask for $submit && $name before adding data. Later you could add some error messages f.e.: if ($submit && !$name) { echo('Please add your name!'); } Code (markup): Hope this helps a litte bit to understand how using form actions. Don't use AJAX (Javascript) before your script doesn't run clean in php.
mgutt has got it but it doesn't have to be as complicated... basically you want to add an entry to you database only when somebody submits so you're looking at something like such: <?php //Check if Submit Button Is Pressed if (isset($_POST['send_form'])) { //Before you add information to you database //you want to verify data is filled out and //filtered - do it here //Add to Table } ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> //Fields <input name="send_form" type="submit" value="Send Form" /> </form> PHP: