• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 428
  • Last Modified:

Php Form writes to SQL Database

Im working a very simple form of 6 fields "html"
when the user fills the form and submits it
the info is saved on to a sql database

I have a great example of how to do that but everytime
the form is filled out and submited a new line on teh database is added
I just want the old line erased and replaced with the new info
and in my php i also have a validator for each field that i have no idea how to get rid of

Im new to php.

Thanx a mill
<?php print( '<?xml version = "1.0" encoding = "utf-8"?>' ) ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

<html xmlns = "http://www.w3.org/1999/xhtml">
      <title>Sample form to take user input in XHTML</title>
      <style type = "text/css">
         td          { padding-top: 2px;
                       padding-bottom: 2px;
                       padding-left: 10px;
                       padding-right: 10px }
         div         { text-align: center }
         div div     { font-size: larger }
         .name       { background-color: #ffffaa } 
         .email      { background-color: #ffffbb } 
         .phone      { background-color: #ffffcc } 
         .os         { background-color: #ffffdd } 
         .smalltext  { font-size: smaller }
         .prompt     { color: blue;
                       font-family: sans-serif;
                       font-size: smaller }
         .largeerror { color: red } 
         .error      { color: red; 
                       font-size: smaller }
         extract( $_POST );
         $iserror = false;

         // array of book titles
         $booklist = array( "book 1",
            "book 2", "book 3",
            "book4" );

         // array of possible operating systems
         $systemlist = array( "system 1", "system 2", 
            "system 3", "system 4", "system 5");

         // array of name values for the text input fields
         $inputlist = array( "fname" => "First Name",
            "lname" => "Last Name", "email" => "Email",
            "phone" => "Phone" );

         // ensure that all fields have been filled in correctly
         if ( isset ( $submit ) )
            if ( $fname == "" )                   
               $formerrors[ "fnameerror" ] = true;
               $iserror = true;                   
            } // end if

            if ( $lname == "" ) 
               $formerrors[ "lnameerror" ] = true;
               $iserror = true;
            } // end if

            if ( $email == "" ) 
               $formerrors[ "emailerror" ] = true;
               $iserror = true;
            } // end if			

            if ( !ereg( "^\([0-9]{3}\)[0-9]{3}-[0-9]{4}$", $phone ) ) 
               $formerrors[ "phoneerror" ] = true;
               $iserror = true;
            } // end if
            if ( !$iserror )  
               // build INSERT query
               $query = "INSERT INTO contacts " .
                  "( LastName, FirstName, Email, Phone, Book, OS ) " .
                  "VALUES ( '$lname', '$fname', '$email', " . 
                  "'" . quotemeta( $phone ) . "', '$book', '$os' )";

               // Connect to MySQL
               if ( !( $database = mysql_connect( "localhost", 
                  "zahi", "zahi" ) ) )
                  die( "Could not connect to database" );

               // open MailingList database
               if ( !mysql_select_db( "MailingList", $database ) )
                  die( "Could not open MailingList database" );
               // execute query in MailingList database
               if ( !( $result = mysql_query( $query, $database ) ) ) 
                  print( "Could not execute query! <br />" );
                  die( mysql_error() );
               } // end if

               mysql_close( $database );

               print( "<p>Hi<span class = 'prompt'>
                  Thank you for completing the survey.<br />

                  You have been added to the 
                  <span class = 'prompt'>
                  mailing list.</p>
                  <strong>The following information has been saved 
                  in our database:</strong><br />

                  <td class = 'name'>Name </td>
                  <td class = 'email'>Email</td>
                  <td class = 'phone'>Phone</td>
                  <td class = 'os'>OS</td>

                  <!-- print each form fields value -->
                  <td>$fname $lname</td>

                  <br /><br /><br />
                  <a href = 'formDatabase.php'>
                  Click here to view entire database.</a>
                  </div>This is only a sample form. 
                  You have not been added to a mailing list. 
                  </div></body></html>" );
            } // end if 
         } // end if 

         print( "<h1>Registration Form.</h1>
            Please fill in all fields and click Register." );
         if ( $iserror )                                              
            print( "<br /><span class = 'largeerror'>                 
               Fields with * need to be filled in properly.</span>" );
         } // end if

         print( "<!-- post form data to form.php -->
            <form method = 'post' action = 'dynamicForm.php'>
            <img src = 'images/user.gif' alt = 'User' /><br />
            <span class = 'prompt'>
            Please fill out the fields below.<br /> </span>

            <!-- create four text boxes for user input -->" );
         foreach ( $inputlist as $inputname => $inputalt )
            $inputtext = $inputvalues[ $inputname ];
            print( "<img src = 'images/$inputname.gif'                 
               alt = '$inputalt' /><input type = 'text'                
               name = '$inputname' value = '" . $$inputname . "' />" );
            if ( $formerrors[ ( $inputname )."error" ] == true ) 
               print( "<span class = 'error'>*</span>" );        
            print( "<br />" );
         } // end foreach

         if ( $formerrors[ "phoneerror" ] ) 
            print( "<span class = 'error'>" );
            print("<span class = 'smalltext'>");
         print( "Must be in the form (555)555-5555
            </span><br /><br />

            <img src = 'images/downloads.gif' 
               alt = 'Publications' /><br />

            <span class = 'prompt'>
            Which book would you like information about?
            </span><br />

            <!-- create drop-down list containing book names -->
            <select name = 'book'>" );
         foreach ( $booklist as $currbook ) 
            print( "<option" );
            if ( ( $currbook == $book ) )    
               print( " selected = 'true'" );
            print( ">$currbook</option>" );
         } // end foreach
         print( "</select><br /><br />
            <img src = 'images/os.gif' alt = 'Operating System' />
            <br /><span class = 'prompt'>
            Which operating system are you currently using?
            <br /></span>

            <!-- create five radio buttons -->" );

         $counter = 0;
         foreach ( $systemlist as $currsystem ) 
            print( "<input type = 'radio' name = 'os' 
               value = '$currsystem'" );

            if ( $currsystem == $os )        
                  print( "checked = 'checked'" );
            elseif ( !$os && $counter == 0 )            
               print( "checked = 'checked'" );

            print( " />$currsystem" );

            // put a line break in list of operating systems 
            if ( $counter == 1 ) print( "<br />" );
         } // end foreach

         print( "<!-- create a submit button -->
            <br /><input type = 'submit' name = 'submit'
            value = 'Register' /></form></body></html>" );

Open in new window

  • 10
  • 9
  • 3
1 Solution
zahimezherAuthor Commented:
This is the sql db



USE mailingList;




   LastName varchar(30),

   FirstName varchar(30),

   Email varchar(64),

   Phone varchar(13),

   Book varchar(60),

   OS varchar(30)


Neil RussellTechnical Development LeadCommented:
Firstly you would need your users to identify the line that they are going to change! Your Primary Key is just an Identity number and as you dont have that on your form you wouldnt be able to correctly identify what record to update.
You couldnt just rely on the fact that the Surname and Firstname where the same on the form, what if someone gets married? A typing error? etc...
You would realy need to have a search form or a grid selection form first for allowing the end user to identify the data row to be updated. THEN when you have that unique ID you can use a simple UPDATE query that has a WHERE ID = $selectedID.
Lots of work to alter that into a form that allows UPDATES rather than additions.
zahimezherAuthor Commented:
i want this to work as a cms . if they enter incorrect info they can just resubmit it again
so i dont want the user to choose a row i just want them to update on row
over and over again as many times as they wish.

the code i have now adds a new row everysingle time
i just want on row that can be overwritten by one user
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

Neil RussellTechnical Development LeadCommented:
So your database will ONLY have one single row???
zahimezherAuthor Commented:

and when the user submits the form that 1 row will be overwritten.
So i just need help with the code that i pated above. to do that :S

HELP! :(
Ray PaseurCommented:
Well, you have over 200 lines of code there and I cannot understand it all, but if you want to get this going as quickly as possible and you only want one row in the data base, you might want to add this query right before the insert.  It will have the effect of emptying the table.

DELETE FROM contacts

Just execute that near line 75.

Give it a try and let us know if you have any questions.

Best regards, ~Ray
if ( !$iserror )  
                // EMPTY THE CONTACTS TABLE
                mysql_query("DELETE FROM contacts");

Open in new window

zahimezherAuthor Commented:
Thanks Ray :S
Neil RussellTechnical Development LeadCommented:
It does beg the question......
What use is the database if the only record in it is overwritten by each and every update by any user anywhere?
Ray PaseurCommented:
@Neilsr: agreed, but out OP said this, so I took him at his word!  I think this is a learning exercise at this point in the PHP career.

"I just want the old line erased and replaced with the new info "
Neil RussellTechnical Development LeadCommented:
In that case i would still suguest he use an UPDATE statement with a WHERE ID = 1 clause, just so that he learns something from it rather just how to delete 1 record.
Ray PaseurCommented:
Yeah, I might do that if it were my app .  But you and I know better than to go into phpMyAdmin and accidentally change the auto_increment number!
zahimezherAuthor Commented:
hein ? :S

i didnt understand a word

Guys! think about as a cms !
Flash reads 1 table from sql and i want my client to over write this info at any time
Only one user "client"
only one row that can be over written through this form

Neil RussellTechnical Development LeadCommented:
I have NEVER heard of a CMS that ONLY stores ONE record and OVERRIGHTS it as soon as the NEXT customer comes along! You never want to store the data longer than until the next one comes along?
zahimezherAuthor Commented:
nope! for example the intro text on the home page!
if the client wants to update the text why would he want the old version
kept on the db?

thats exactly what i need it for text on the home page
one paragraph that can be updated through a php form and stored on my sql!


I hope this helps

Neil RussellTechnical Development LeadCommented:
So your having a table JUST for one single entry? Is the ONLY thing your managing in your CMS the home page title? NO other text? No intention of doing so in the future?
zahimezherAuthor Commented:
nope! just one field !

what i want is an html page with a text box and a submit btn
a php file that send the info from that html text box
and stores it on to a database that has one table one row and one cell!

the form that i have pasted at the very top does something very simillar but has too many fields and saves every submition as a row.

Neil RussellTechnical Development LeadCommented:
Why use a database for this? Why not just save it to a text file??? Far easier and saves a LOT of server resources for ONE text box.........
zahimezherAuthor Commented:
i wish it was up to me! :( i aready have a text file example of how to do this.
Neil RussellTechnical Development LeadCommented:
Well good luck :D
zahimezherAuthor Commented:
lol! if u cant do it why pretend to be the expert and waist my time? thanx anyway!
Im asking for the simplest thing ever (i guess) and all you can say is good luck! wahahahaha

Ur the expert
Neil RussellTechnical Development LeadCommented:
I dont understand, you've had several sugestions, different options of how to do it? Who's pretending here?
zahimezherAuthor Commented:
thanx for your time dude. never  mind. Z

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

  • 10
  • 9
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now