Jump to content

Post info from form, then add to mySQL Db - where do I position the php code


Recommended Posts

I'm learning php & sql.  I can do the programming and logic, but how to put it all together is where I get confused.   I have copied, from the w3 tutorial, the php form validation complete, and it worked fine.  I have also used the php/sql database tutorial to copy the 'insert into' code and it works fine with a Db I set up on the local host.   Now I would like to save the info in the form to a database table, but I'm not sure where to insert the code to connect to the database.  I tried just adding the code at the bottom of the 'Form Complete' code but it didn't seem to take - no error codes but didn't get saved to the table.   If I should keep it as a separate file, how and where do I call that file with the parameters I want to insert into the database?   Is there anything on the w3 site that deals with this 'real life' situation.   The tutorials are very good, but (everybody's got a big butt) the examples all use literals and they don't relate to a problem like I've explained here.   I mean, why else would you have somebody fill in a form except to save the info in a table for future reference??   Any help going forward would be greatly appreciated.  I didn't post the code here to save space, so if you're not sure what code I'm talking about, it's at w3schools and under PHP tutorial goto PHP forms 'Form Complete'  and just below that in the SQL section is the code for Inserting data into a mySQL database.   If I need to, I will post it.   Thanx,  Gil

 

Edited by Gilbert
Link to post
Share on other sites

It does not matter because this is processed server side and done in background, all it requires is the data (post or get) from the form to exist before processing and inserting into database.

The php coding could be on a separate php page OR on the same php page the form was submitted on itself, the action attribute url determines where it is sent.

On the form page itself, it would check if all required data from form exists before triggering the insert into database code using isset() or !empty(), until this happens the insert coding is bypassed with just the form showing and waiting to be filled out. This exact same insert code can easily placed on a separate php page, with action attribute of form url pointing to this page.

Link to post
Share on other sites

To build a more complex program out of a lot of simpler parts, you first make a general outline of what the program should do as a collection of simpler steps. The following list is probably similar to the structure of the program you want to make, but you can tweak it if necessary:

1. If the form was submitted:
  1.1 Collect the form data
  1.2 Validate the form data
  1.3a If the form data is valid:
    1.3a.1 Save to database
    1.3a.2 Redirect to another page
    1.3a.3 End
  1.3b If the form data is not valid:
    1.3b.1 Show error messages
2. Show the form

Now, for each step in the list you can write the PHP code for that step. This example uses just one form field for demonstration:

<?php
// 1. If the form was submitted
if(!empty($_POST)) {
  // 1.1 Collect the form data
  $first_name = isset($_POST['first_name']) ? $_POST['first_name'] : '';
  
  // 1.2 Validate the form data
  $is_valid = true;
  $errors = [];
  if(strlen($first_name) < 2) {
    $is_valid = false;
    $errors[] = 'First name is too short';
  }
  
  // 1.3a If the form data is valid:
  if($is_valid) {
    // 1.3a.1 Save to database
    $pdo = new PDO("...");
    $stmt = $pdo->prepare('INSERT INTO `table` (`first_name`) VALUES(?)');
    $stmt->execute([$first_name]);
    
    // 1.3a.2 Redirect to another page
    header("Location: http://example.com/complete.php");
    
    // 1.3a.3 End
    exit;
  } else { // 1.3b If the form data is not valid:
    // 1.3b.1 Show error messages
    echo 'Form errors:';
    echo '<ul>';
    foreach($errors as $error) {
      echo '<li>' . $error . '</li>';
    }
    echo '</ul>';
  }
}

// 2. Show the form
?>
<form method="POST">
  ... ...
</form>

 

  • Like 1
Link to post
Share on other sites
  • 2 weeks later...

Thank you, dsonesuk and ingolme,  for some reason I'm not getting alerted when replies comes in - I've even checked my spam & junk folders.

Thanks for your replies - helped a lot in my understanding - I do remember seeing some code where the action reference was to the same page- I think it was $_SELF?

The code is great - I used something very similar on the w3 site.  It solidified it in my brain to see the thought process.  Thanks a lot,  Gil

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...