www.webdeveloper.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 31

Thread: php form to save to db for user to add more info later to be emailed when finished

  1. #1
    Join Date
    Oct 2007
    Posts
    175

    php form to save to db for user to add more info later to be emailed when finished

    Heres what I want to do:

    User creates new form using php with new file name "php/html".
    This form already populated with form elements once created... is opened.
    User enters information and needs to save to db(mysql) and came back later to finish and or correct earlier mistakes and email to me.

    Heres what I already know:

    I created a form using php to call up whats in db to display in text fields for editing. Saving the info to db is not the issue. Once I changed what needs to be changed, I submit/update db. I have another page which displays the resulting info. Emailing is also not the issue as I know how to do that as well.

    Here is the issue's in ():

    (User creating a new form with id/password with new name.)
    that new form must have the fields I require for user to fill in.
    once info is entered by user, they save to db.
    (User to come back later to enter a id and password to pull up earlier saved file for editing)
    After completing the form, user to save and email to me.
    if user wants, still can comback to update and re email to me using that same id/password.

    I know this can be accomplished, moreover user creating and retrieving forms to be send when ready.

    Can some one can point me in the right direction or show an example of how this would work?

  2. #2
    Join Date
    Apr 2007
    Posts
    1,664
    how do you mean?
    (User creating a new form with id/password with new name.)
    What are you trying to do? I'm totally lost, you want your users to create forms, not just fill in the information?

    that new form must have the fields I require for user to fill in.
    If the forms must have information that you require, why don't you create the forms?
    once info is entered by user, they save to db.
    OK that's a normal thing to do.
    (User to come back later to enter a id and password to pull up earlier saved file for editing)
    What saved file? The form they created? I thought you saved the info to the database. This would be data not a file. But are you editing in a user's custom form?
    After completing the form, user to save and email to me.
    What save the form contents to the database or the currently unknown file? Or send you a form via email or just the info they entered into the form they created.
    Can some one can point me in the right direction or show an example of how this would work?
    If you explain what you're trying to do, maybe.

    Perhaps this makes sense to someone else??


  3. #3
    Join Date
    Oct 2007
    Posts
    175
    Basically a login script in which the user will create, I dont know the code, everything they save goes under there new login to comback to later.

    Once login is comfirmed it redirects them to my form, which will have there login tied to it so they can save info specific to there login, I was thinking earlier they use a php form to create a new form, the php code on that form will create another form, but I guess it would be better to have just one premade form ready to the user tied to there login.

    Im just trying to make it so when multiple user's come to my site, they create there own login/registration, once logged in a form will appear, they fill in the form, lets say they dont complete it.....they want to come back to it later. So they save the <i>data</i> and log out. Then when any specific user comes back , they log in and select the form they were working on and complete it. Once completed, they have the option to save it again, print, and or email.

    I'm new to the whole login scripts, and tying the data entered on the forms to the users login. everything else I can do myself.

    I hope this makes more sense!

  4. #4
    Join Date
    Apr 2007
    Posts
    1,664
    OK, I think I've got you now.

    The easiest way to manage this is with database. MySQL an MSSQL work well with PHP and MySQL is free and comes on most Linux Apache hosting plans.

    There's only one shortcut to getting this working and that's paying someone to do it for you. If you want to learn it'll take some effort on your part.

    The very first thing to do is read and try some tutorials. google 'php tutorial' and 'php mysql tutorial' for something that makes sense to you. read them do them, and spend the next couple of weeks learning the basics. Post your questions here. Lots of people to help out.

    Read the tutorials and come back to this thread. Then it'll make much more sense.


    //
    two weeks later continue reading
    //


    To achieve what you want you simply have uses register which creates a unique userid for them. Then after that they can login with their registered details. Upon successful login you display your form and retrieve the data from the database for the unique userid. so you can store data like this

    SQL table users
    (data entered using a registration form)

    Code:
    userid	email		password	name
    1	bob@bo.com	1234		bob
    2	carl@c.com	asdf		carl
    3	jon@dsa.com	qwert		jon
    etc

    SQL table formfields
    Code:
    fieldid		label		inputname	
    1		Like red?	red
    2		Got milk?	gotmilk
    3		Like football?	likefootball	
    4		Drink beer?	drinkbeer
    5		Red or blue?	colorchoice
    The label/inputname values can be used to display your form and the ids used to store the data collected

    SQL table formdata
    //store any complete fields i this table

    Code:
    userid	fieldid		value
    1	1		no
    1	2		yes
    2	1		yes
    2	2		yes
    1	3		yes
    1	4		yes
    2	3		yes
    2	4		no
    2	5		blue	
    3	1		yes
    So now when you display your form you can get any data that was previously stored and display it in your form. If the users adds more data then you add it to the table when they save it. Or email it when you choose to send it.


    Using the data in the formdata table you can use the ids to refer to the other tables and get all the data.

    so the first row of data in table formdata:
    Code:
    userid	fieldid		value
    1	1		no
    userid 1 = bob
    field id 1 = like red
    value = no

    so bob doesn't like red

    and the last line of table formdata in the example
    Code:
    userid	fieldid		value
    3	1		yes
    userid 3 = jon
    field id 1 = like red?
    value = yes

    jon likes red.


    Using the ids from users and the ids from the form fields you can store repeated data and non repeated data ( the form answers) you can save them in a seperate table and use the ids to link it all together.

  5. #5
    Join Date
    Oct 2007
    Posts
    175
    Here's what I got so far:

    I found this peice of code and was able to make it work giving me the form "login1.php"

    login.html
    HTML Code:
    <html>
    <head>
    </head>
    <body>
    
    <form name="login" method="post" action="login.php">
    <table border="0" width="225" align="center">
        <tr>
            <td width="219" bgcolor="#999999">
                <p align="center"><font color="white"><span style="font-size:12pt;"><b>Login</b></span></font></p>
            </td>
        </tr>
        <tr>
            <td width="219">
                <table border="0" width="220" align="center">
                    <tr>
                        <td width="71"><span style="font-size:10pt;">Username:</span></td>
                        <td width="139"><input type="text" name="username"></td>
                    </tr>
                    <tr>
                        <td width="71"><span style="font-size:10pt;">Password:</span></td>
                        <td width="139"><input type="password" name="password"></td>
                    </tr>
                    <tr>
                        <td width="71">&nbsp;</td>
                            <td width="139">
                                <p align="right"><input type="submit" name="submit" value="Submit"></p>
                            </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td width="219" bgcolor="#999999"><font color="white">Not Registered? </font><a href="register.html" target="_self"><font color="white">Register</font></a><font color="white"> </font><b><i><font color="white">Now!</font></i></b></td>
        </tr>
    </table>
    </form>
    </body>
    </html>
    login.php

    PHP Code:
    <?php

    //Database Information

    $dbhost "localhost";
    $dbname "DBblah";
    $dbuser "userblah";
    $dbpass "passblah";

    //Connect to database

    mysql_connect $dbhost$dbuser$dbpass)or die("Could not connect: ".mysql_error());
    mysql_select_db($dbname) or die(mysql_error());

    session_start();
    $username $_POST['username'];
    $password md5($_POST['password']);

    $query "select * from users where username='$username' and password='$password'";

    $result mysql_query($query);

    if (
    mysql_num_rows($result) != 1) {
    $error "Bad Login";
        include 
    "login.html";

    } else {
        
    $_SESSION['username'] = "$username";
        include 
    "login1.php";
    }

    ?>
    register.html
    HTML Code:
    <html>
    <head>
    </head>
    <body>
    <form name="login" method="post" action="register.php">
    <table border="0" width="225" align="center">
        <tr>
            <td width="219" bgcolor="#999999">
                <p align="center"><font color="white"><span style="font-size:12pt;"><b>Registration</b></span></font></p>
            </td>
        </tr>
        <tr>
            <td width="219">
                <table border="0" width="282" align="center">
                        <tr>
                            <td width="116"><span style="font-size:10pt;">Name:</span></td>
                            <td width="156"><input type="text" name="name" maxlength="100"></td>
                        </tr>
                        <tr>
                            <td width="116"><span style="font-size:10pt;">Email:</span></td>
                            <td width="156"><input type="text" name="email" maxlength="100"></td>
                        </tr>
                    <tr>
                        <td width="116"><span style="font-size:10pt;">Username:</span></td>
                        <td width="156"><input type="text" name="username"></td>
                    </tr>
                    <tr>
                        <td width="116"><span style="font-size:10pt;">Password:</span></td>
                        <td width="156"><input type="password" name="password"></td>
                    </tr>
                    <tr>
                        <td width="116">&nbsp;</td>
                            <td width="156">
                                <p align="right"><input type="submit" name="submit" value="Submit"></p>
                            </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td width="219" bgcolor="#999999">&nbsp;</td>
        </tr>
    </table>
    </form>
    </body>
    </html>
    PHP Code:
    <?PHP

    //Database Information

    $dbhost "localhost";
    $dbname "dbblah";
    $dbuser "userblah";
    $dbpass "passblah";

    //Connect to database

    mysql_connect $dbhost$dbuser$dbpass)or die("Could not connect: ".mysql_error());
    mysql_select_db($dbname) or die(mysql_error());

        
    $name $_POST['name'];
    $email $_POST['email'];    
    $username $_POST['username'];
    $password md5($_POST['password']);

    // lets check to see if the username already exists

    $checkuser mysql_query("SELECT username FROM users WHERE username='$username'");

    $username_exist mysql_num_rows($checkuser);

    if(
    $username_exist 0){
        echo 
    "I'm sorry but the username you specified has already been taken.  Please pick another one.";
        unset(
    $username);
        include 
    'register.html';
        exit();
    }

    // lf no errors present with the username
    // use a query to insert the data into the database.

    $query "INSERT INTO users (name, email, username, password)
    VALUES('
    $name', '$email', '$username', '$password')";
    mysql_query($query) or die(mysql_error());
    mysql_close();

    echo 
    "You have successfully Registered";
        
    // mail user their information

    $yoursite ‘www.blahblah.com’;
    $webmaster ‘yourname’;
    $youremail ‘youremail’;
        
    $subject "You have successfully registered at $yoursite...";
    $message "Dear $name, you are now registered at our web site.  
        To login, simply go to our web page and enter in the following details in the login form:
        Username: 
    $username
        Password: 
    $password
        
        Please print this information out and store it for future reference.
        
        Thanks,
        
    $webmaster";
        
    mail($email$subject$message"From: $yoursite <$youremail>\nX-Mailer:PHP/" phpversion());
        
    echo 
    "Your information has been mailed to your email address.";

    ?>
    PHP Code:
    <?

    // members page

    session_start();

    if ( empty( 
    $username ) ) {

        print 
    "Please login below!";

        include 
    'login.html';

    } else {
    ?>

    <html>
    <head>
    </head>
    <body>

    //now I need the code to create a form unique to users login for coming back later

    <form name="save" method="post" action="saved.php">
    <input type="text" name="n1" id="n1" value="">

    <input type="radio" name="r1" id="r1" value="val1">
    <input type="radio" name="r1" id="r2" value="val2">
    <input type="radio" name="r1" id="r3" value="val3">

    <input type="submit">
    </form>


    </body>
    </html>

    <?}
    ?>
    How do I direct the users answers that are save to mysql to there unique username to be saved for later editing. I can create the edit page no problem, its connecting the edit page and form to there unique login. I hope this makes sense, I do want to do this on my own so I will post what I have found as I go, any help much appreciated tho.

  6. #6
    Join Date
    Apr 2007
    Posts
    1,664
    If your users have a unique id and your form fields have a unique id then a 3rd table can store both. One row in table 3 for each userid/formfieldid combination.

    I spent a consideable amount of time writing the above response. Then you've asked the question I just answered.

    If you've read it and don't understand it then please be more specific, otherwise please read the my response again.

  7. #7
    Join Date
    Oct 2007
    Posts
    175
    Ok, I managed to echo the userid into the form per user login:

    login.php
    PHP Code:
    <?php

    //Database Information

    $dbhost "localhost";
    $dbname "xx";
    $dbuser "xx";
    $dbpass "xx";

    //Connect to database

    mysql_connect $dbhost$dbuser$dbpass)or die("Could not connect: ".mysql_error());
    mysql_select_db($dbname) or die(mysql_error());

    session_start();
    $username $_POST['username'];
    $password md5($_POST['password']);

    $query "select * from users where username='$username' and password='$password'";

    $result mysql_query($query);

    if (
    mysql_num_rows($result) != 1) {
    $error "Bad Login";
        echo 
    "<font color='red'>Error, Please re-enter or register!</font>";
        include 
    "login.html";

    } else {
        
    $_SESSION['username'] = "$username";

    while(
    $row mysql_fetch_array($result))
      {
      echo 
    Welcome " " $row['name'];
      echo 
    "<br />";
      echo 
    "<input type='text' value='$row[userid]' readonly>";
      }

        include 
    "sample.php";

    }

    ?>
    sample.php:
    HTML Code:
    <html>
    <head>
    </head>
    <body>
    
    <form name="sample" method="post" action="save1.php">
    <table>
    <tr>
    <td>
    
    Like Red? Yes:<input type="radio" name="red" id="red1"> No:<input type="radio" name="red" id="red2"><br>
    
    Got Milk? Yes:<input type="radio" name="gotmilk" id="gotmilk1"> No:<input type="radio" name="gotmilk" id="gotmilk2"><br>
    
    Like football? Yes:<input type="radio" name="likefootball" id="likefootball1"> No:<input type="radio" name="likefootball" id="likefootball2"><br>
    
    Drink beer? Yes:<input type="radio" name="drinkbeer" id="drinkbeer1"> No:<input type="radio" name="drinkbeer" id="drinkbeer2"><br>
    
    <input type="submit" name="submit" value="Submit">
    
    </td>
    </tr>
    </table>
    </form>
    
    
    </body>
    </html>
    and then from here I need to save, I was reading on JOIN but I still cant figure out how to input the fieldid and value in the table formdata using the formfield table.

    Here's what I have for an incomplete start:

    save1.php
    PHP Code:
    <?PHP

    //Database Information

    $dbhost "localhost";
    $dbname "x";
    $dbuser "xx";
    $dbpass "xxx";

    //Connect to database

    mysql_connect $dbhost$dbuser$dbpass)or die("Could not connect: ".mysql_error());
    mysql_select_db($dbname) or die(mysql_error());
    PHP Code:
    $query "SELECT formfield.fieldid, users.userid "." FROM userid, fieldid "." WHERE inputname.fieldid = userid.fieldid";
    //I figure this is as close as I can get for now, I know it may be wrong somewhere "but where?" 
    PHP Code:
    $userid $_POST['userid'];
    $fieldid $_POST['fieldid'];
    $value $_POST['value'];    


    $query "INSERT INTO formdata (userid, fieldid, value)
    VALUES('
    $userid', '$fieldid', '$value')";
    mysql_query($query) or die(mysql_error());
    mysql_close();


    ?> 

  8. #8
    Join Date
    Apr 2007
    Posts
    1,664
    first thing is name="likefootball" id="likefootball1"
    name and id should be the same.

    You'll need to build a dynamic query. It's pretty simple when you understand concatenation. Concatenation is simple adding data to an existing variable. So first add some data to the $query var

    PHP Code:
      $query "INSERT INTO formdata (userid, fieldid, value)
    VALUES"

    now using .= (dot equals) you can add more data (concatenate) to the variable $query.

    PHP Code:
     $query "INSERT INTO formdata (userid, fieldid, value)
    VALUES "
    ;
     
    $query .="('$userid', '$fieldid', '$value')"
    this is the same as

    PHP Code:
    $query "INSERT INTO formdata (userid, fieldid, value)
    VALUES('
    $userid', '$fieldid', '$value')"
    Why is this useful? Now you can build the query in aloop and insert all your form field data in one go.

    PHP Code:
     $query "INSERT INTO formdata (userid, fieldid, value)
    VALUES "
    ;
    doaloop(){
        
    $q.=" ('$userid', '$fieldid', '$value') ";

    so for what ever condition calls a loop you can insert as many values as you need. Just build the query dynamically and insert the data in a single statement. It's really easy to get syntax errors doing this so you need to echo the query out to check it.


    So you have a POST array. It consists of the key as the field name and the value. Have a look to see what is contains using print_r($_POST) after submitting the form.

    You have some choices. You could have an array of filed names and only dynamically build the query if the $_POST key is in your array or prepend the fileds you want to submit with a common name like insertme_filedname. You can then preg teh key for insertme and explode the key on the _ and take the second half as the key name to insert. Either works as well as the other. I'll use the array method in this example.

    You could build the array form the form fields table if you have one.

    PHP Code:
    //build fileds to insert array
    $fieldstoinsert=array('red','gotmilk','likefootball','drinkbeer');

    //start building query
    $query "INSERT INTO formdata (userid, fieldid, value) VALUES "

    //loop through the post array
    foreach($_POST as $fieldid => $value){
        if(
    in_array($fieldid,$fieldstoinsert)){
            if(
    trim($value)!=""){//only basic validation here
                
    $q.="('$userid', '$fieldid', '$value')";
            }
        }

    You'll now have multiple records in formdata.

    You're right you'll need to join to get all the data in a single query. You dont have to join though. You could select the user info then select the formdata, build the array and compare the field names and echo the data if it exists.

    if you wanted to join you could do this
    PHP Code:
    select from users 
    INNER JOIN formdata on users
    .userid=formdata.userid 
    Read wikipedias excellent explanation on joins
    http://en.wikipedia.org/wiki/Join_(SQL)

  9. #9
    Join Date
    Oct 2007
    Posts
    175
    Your right, I keep getting syntax errors for the foreach statement. I understand most how everything is supposed to work but being a newbie in the php/mysql area is a little convoluting to say the least. I'm just having a problem putting everything together, I'd say another week of learning, and I should beable to figure it out. till then any other help or ideas to help me understand would be great!!

    Thanks for your help thus far!

  10. #10
    Join Date
    Apr 2007
    Posts
    1,664
    When you get error it would help a lot if you copy them in here. When you do there's usually a line number associated with the error so point out which line has the error in the script. The line numbers wont tally if you've posted an extract from the script.

    If you have problems the write a test script to deal with just that issue untill you get the concept. I do that all the time trying to work stuff out.

    Lot of short specific questions are much better learning tools then questions like 'here's my script why doesn't it work?'. I rarely get involved in threads like that.

  11. #11
    Join Date
    Oct 2007
    Posts
    175
    PHP Code:

    //Connect to database

    mysql_connect $dbhost$dbuser$dbpass)or die("Could not connect: ".mysql_error());
    mysql_select_db($dbname) or die(mysql_error());

    $query "SELECT * FROM users, formfields, formdata WHERE users.userid=formdata.userid and formfields.fieldid=formdata.fieldid";

    $fieldstoinsert=array('red','gotmilk','likefootball','drinkbeer');

    $query "INSERT INTO formdata (userid, fieldid, value) VALUES ";

    foreach(
    $_POST as $fieldid => $value){
        if(
    in_array($fieldid,$fieldstoinsert)){
            if(
    trim($value)!=""){
                
    $q.="('$userid', '$fieldid', '$value')";
                echo 
    "Data Entered!!";
             }
        }
    }   


    ?> 
    ok, I found the syntax error, it was missing ";" at the end of:
    Code:
    $query = "INSERT INTO formdata (userid, fieldid, value) VALUES ";
    k, now I added an echo saying "data entered!!", it echos 4 times and nothing is put in the db. Im thinking somehow I need to match to the formfields table to use the fieldid.

    Why is it not entering in the db?

  12. #12
    Join Date
    Apr 2007
    Posts
    1,664
    I added an echo saying "data entered!!", it echos 4 times and nothing is put in the db
    That's exactly what your telling it to do. (prepare to slap your forehead)

    PHP Code:
    $query "INSERT INTO formdata (userid, fieldid, value) VALUES ";

    foreach(
    $_POST as $fieldid => $value){
        if(
    in_array($fieldid,$fieldstoinsert)){
            if(
    trim($value)!=""){
                
    $q.="('$userid', '$fieldid', '$value')";

    //           >>Still inside foreach loop<<
                
    echo "Data Entered!!"

             }
        }
    }   

    // >> missing mysql_query($q) << 
    Doh!

    And .... slap now


    I would advise you echo the query to the screen before running it to check you've built it right.

  13. #13
    Join Date
    Oct 2007
    Posts
    175
    ok, SLAP!

    I already figured that one out and figured I'd test it using the print_r($_POST);

    when I do that, I get:
    Array ( [userid] => 2 [red] => Yes [gotmilk] => Yes [likefootball] => Yes [drinkbeer] => Yes [submit] => Submit )

    But thanks, I forgot to run it!! another slap!

    PHP Code:
    mysql_connect $dbhost$dbuser$dbpass)or die("Could not connect: ".mysql_error());
    mysql_select_db($dbname) or die(mysql_error());

    $query "SELECT * FROM users, formfields, formdata";

    $fieldstoinsert=array('red','gotmilk','likefootball','drinkbeer');

    $query "INSERT INTO formdata (userid, fieldid, value) VALUES ";

    foreach(
    $_POST as $fieldid => $value){
        if(
    in_array($fieldid,$fieldstoinsert)){
            if(
    trim($value)!=""){
                
    $query.="('$userid', '$fieldid', '$value')";
             }
        }
    }   

    mysql_query($query) or die(mysql_error());
    mysql_close();

    ?> 
    now if it runs I get:
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

  14. #14
    Join Date
    Apr 2007
    Posts
    1,664
    lol

    and the last line of my previous post says...

  15. #15
    Join Date
    Oct 2007
    Posts
    175
    WOOPS!!

    mysql_query($q) or die(mysql_error());
    mysql_close();

    $q instead of $query right?

    I still get:
    Code:
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2', 'red', 'Yes')('2', 'gotmilk', 'Yes')('2', 'likefootball', 'Yes')('2', 'drin' at line 1

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles