Subscribe to our rss feed

Inserting Data Into a MySQL Database using PHP

Posted in PHP Tutorials by John Ward on the February 4th, 2008

This tutorial is a continuation on the “How to Access a MySQL Database Using PHP” tutorial that showed you how to setup a database using phpMyAdmin and how to read data from the database using PHP. In the tutorial I will show you how to write data to the database directly through a from on your website. This is going to be a very basic writing tutorial. We will get into more advanced stuff later on.

You will need to follow the first part of the the “How to Access a MySQL Database Using PHP” tutorial to setup the database and user permissions. After you do that you can continue with this tutorial.

At this point you should have the database setup with some test data in it. I am going to show you how to update the date by using a form on a website. First we will create the form. You can use any editor you would like. Sometimes I use notepad, but for this tutorial I will be using cPanel’s web base editor. It allows me to edit the files directly on my server and also color codes the lines nicely.

First we will create our form. We will name it “form.php”.
Inserting Data Into a MySQL Database using PHP

Now we will create the form using some basic html, nothing fancy. Start with the form tag. Notice that the form action is set to update.php, that is the script that will update the database.
Inserting Data Into a MySQL Database using PHP

Now we will add 3 input boxes for our 3 columns in the database. FName, LName, and PHON. There is a 4th column in the database we created, the ID field. That field is auto generated so we do not need to update it.
Inserting Data Into a MySQL Database using PHP

We created the input boxes for each field in the database. You will notice that the size of each input is limited to the size of our fields in the database. Each field is a text because we want a text box.
Next we need to add a submit button.
Inserting Data Into a MySQL Database using PHP

A submit button is also an input field. The type is submit, which will create a button and the value gives the button a label that you will see from your browser.
That is it for form.php. I might as well mention that there is no reason that I named this with a .php extension. It could have been called form.html and it would have functioned the same way because there is no php code on the form. Save the fiel and open it in your browser. It should look like this.
Inserting Data Into a MySQL Database using PHP

The next step is to create the update.php file. This file will update the database with the new information. Create a new file called update.php.
Inserting Data Into a MySQL Database using PHP

Now to start coding a php file we always start with the open and close php tags.
Inserting Data Into a MySQL Database using PHP

The first thing we are going to do is capture the data that was sent from the form.php file and store the info as variables. Because the form method was set to post, we can use the post variable function to collect the data. You will notice that the names in the post function will match the names we used on the form.
Inserting Data Into a MySQL Database using PHP

Now we will make a connection to the database. You will have to replace:
“localhost” with the location of your server
“projectc_testuse” with your username
“password” with your password
Then we are selecting the “projectc_Test” database you will change that to whatever you named the database in the first tutorial.
Inserting Data Into a MySQL Database using PHP

Next we are going to create the query that will insert a new row in the database. As you can see we are inserting in the table called TestTable and were are inserting the fields ID, FName, LName, and PHON. The actual values are coming from the variables. The ID fields is left NULL because it is auto generated by the database.
Inserting Data Into a MySQL Database using PHP

Now all we have to do is have the query execute. Then if the query fails we will print an error. If it is successful we will print the info that was added to the database.

Inserting Data Into a MySQL Database using PHP

Now you can test out the form.
Inserting Data Into a MySQL Database using PHP

When you submit the form you should see your results displayed.
Inserting Data Into a MySQL Database using PHP

Now if you run the php file from part one of this tutorial you should see you updated info in displayed along with everything else that was in the database.
Inserting Data Into a MySQL Database using PHP

So that is a very basic way of writing to a MySQL database using PHP. Now you should be able to create a database, write data to the database, and read from the database. I hope to create some more advanced PHP/MySQL tutorials in the future.

Popularity: 28% [?]

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Reddit

Other Related Tutorials


120 Responses to 'Inserting Data Into a MySQL Database using PHP'

Subscribe to comments with RSS or TrackBack to 'Inserting Data Into a MySQL Database using PHP'.

  1. Jalaj said,

    on February 4th, 2008 at 1:29 am

    Good post for those new to php/mysql. Glad to see regular posts after a long inactivity. Please continue posting regularly if not frequently.

  2. janaka said,

    on February 26th, 2008 at 2:30 am

    That is a great help

  3. Enlamsweawn said,

    on February 29th, 2008 at 4:21 am

    Hello there.
    Just found your site. Great job!
    I like it much.
    look here http://live.com

  4. gabr said,

    on February 29th, 2008 at 10:55 am

    dasdasdasd

  5. upendra said,

    on March 11th, 2008 at 5:31 am

    Hello
    Just found your site. !
    I like it and thanks .

  6. Hunter said,

    on March 15th, 2008 at 1:32 am

    I run the script and it echos it was updated but the table doesnt show any info was inserted, what could i have possibly one wrong?

  7. John Ward said,

    on March 15th, 2008 at 5:09 am

    Do you have any info in the table at all. For some reason if I do not enter the first row of data manually using php my admin, then the table will not update from the php file.

  8. Hunter said,

    on March 15th, 2008 at 9:20 pm

    i entered data myself through phpmyadmin and then tried to with the script and it did squat

  9. John Ward said,

    on March 15th, 2008 at 10:19 pm

    It’s hard to tell what could be happening. I would check the code one more time. It is strange that it is not throwing a MySQl error. Make sure the query is right.

  10. Hunter said,

    on March 16th, 2008 at 8:27 pm

    i checked it but i also found a friends script and its doing what i need but not exactly i need to code a script that pulls info from a database but can also put it in and yeah theres to much to explain in this lol, i just need to find someone to talk mono on mono on like a chat thing or something and see if they can help me

  11. Zeek said,

    on March 17th, 2008 at 6:50 pm

    Thank you very much for the training lesson above. It has come in handy close to a deadline.

  12. web pix said,

    on March 25th, 2008 at 2:32 pm

    Thanks a lot….it clears my doubts :)

  13. astravie said,

    on March 31st, 2008 at 11:17 am

    Thanx a lot!
    I’ll be waiting for the next script, the one that will searching the database :)

  14. rifas said,

    on April 16th, 2008 at 11:45 pm

    thank a lot…

    it is very helpful for me to do assignment..

  15. moored said,

    on April 27th, 2008 at 6:38 pm

    I tried you’re code and no matter what i did it would not work

  16. Shah said,

    on May 5th, 2008 at 6:28 am

    Hi!
    I need to extract data from mysql by using php….and I want as a link; so user can click to see details of that link (more info)

    can u give me a hand pls!!!!!

  17. Phil said,

    on May 17th, 2008 at 7:06 am

    hello

    Thanks for the tips, but why do firefox & ie both return this parse error:

    “syntax error, unexpected ‘;’ in /home/gypsy/public_html/update.php on line 10″

    ? please help

  18. Phil said,

    on May 17th, 2008 at 9:30 am

    ok dont worry, figured it out, I think I am on a slightly newer version of php or something, because changing my syntax slightly fixed the error.

    instead of
    echo “updated with: ” .variable. ;

    I wrote
    “updated with: “, variable ;

  19. sayed Mujahed Hussaini said,

    on May 24th, 2008 at 2:10 am

    Thank you very much

  20. sundar said,

    on June 12th, 2008 at 1:58 am

    hi
    i want set a update and view buton

  21. sanae said,

    on June 16th, 2008 at 10:35 am

    if you please help me! i am a student and i have web project
    if i have a page in html with checkbox and i want to select one or more
    pieces how can i write the php page to add the selected pieces to the invoice!

    with my thanks

  22. Mike Maguire said,

    on June 17th, 2008 at 7:18 pm

    @ sanae

    There is an easy way to do this. I am going to do a tutorial on this that will post next week some time. For starters you would need to make all the checkboxes be in an array.

    eg:

    Box 1
    Box 2
    Box 3

    You receiving file should then contain a for next loop that will take each box and if they were checked and if they were to run a query to enter them into the database like so:

    foreach($cats as $key => $value) {
    if ($value > 0) {
    $sql = sprintf(”insert INTO value_table(row1,rrow2) VALUES(’%s’,'%s’);”,
    $value, $old_no);
    mysql_query($sql);
    }
    }

    That should do what you need to do. Let us know if you have issues and thanks for the great tutorial idea.

  23. Mike Maguire said,

    on June 17th, 2008 at 7:22 pm

    (HTML not allowed in comments) Here is what Box1, Box2, and Box3 should be.

    input type=’checkbox’ name=’boxes[]‘ value=’1′ />Box 1
    input type=’checkbox’ name=’boxes[]‘ value=’2′ />Box 2
    input type=’checkbox’ name=’boxes[]‘ value=’3′ />Box 3


  24. on June 27th, 2008 at 10:45 am

    Nice tutorial, syntax highlight really helps in understanding the code

  25. long4hort said,

    on June 28th, 2008 at 10:00 am

    nice tutorial

  26. IJ said,

    on June 30th, 2008 at 10:01 am

    I tried it and it did not update…not sure why.
    I typed the exact thing you have

  27. IJ said,

    on June 30th, 2008 at 10:12 am

    Here is my code:
    when ran, it gives the error “error updating database”
    Please help!!

    html file
    ————–
    Members Search

    Enter Member Information:
    ID:

    First Name:

    Last Name:

    Phone Number:

    Php file
    ————-
    $fname = $_POST['FirstName'];
    $lname = $_POST['LastName'];
    $phone = $_POST['PhoneNumber'];

    mysql_connect(”localhost”, “bookorama”, “bookorama123″) or die (’Error: no db connection ‘ . mysql_error());
    mysql_select_db(”test”);

    $query=”INSERT INTO members (id, firstname, lname, phone)VALUES (’NULL’, ‘”.$fname.”‘, ‘”.$lname.”‘, ‘”.$phone.”‘)”;
    mysql_query($query) or die (’error updating database’);
    echo “database was updated with: ” .$fname.” “.$lname.” “.$phone;

    // close connection
    mysql_close();

  28. John Ward said,

    on June 30th, 2008 at 2:01 pm

    @IJ

    Can you give us the exact error message? That will make troubleshooting much easier.

  29. IJ said,

    on July 2nd, 2008 at 10:09 pm

    @John
    the error is :
    error updating database

  30. Mahadia Tunga said,

    on July 16th, 2008 at 12:26 am

    your way is the best way of teaching for people who need to learn faster.

  31. mahadia said,

    on July 19th, 2008 at 6:45 am

    hi!
    when i submit the form a blank page appear and nothing is being updated in mysql database,where could i be wrong

    thanx!

  32. ian said,

    on July 23rd, 2008 at 3:57 am

    tnx but i didnt get it

  33. fil mcrackin said,

    on July 28th, 2008 at 2:20 am

    keep getting error database not updated, any suggestions?
    Here’s my code, seems right?

  34. paul said,

    on July 30th, 2008 at 5:49 am

    Thanks for this simple article about inserting to database

  35. Ritesh said,

    on July 30th, 2008 at 6:46 am

    Nice code.
    It works very well.

  36. JyRnZa said,

    on August 7th, 2008 at 1:16 am

    a big help

  37. Charles said,

    on August 7th, 2008 at 12:03 pm

    Great article, one more thing can u plz show me how to use a login form to get data from mysql…. would be of immense help….thanx yet again…!

  38. Charles said,

    on August 7th, 2008 at 1:32 pm

    oh, oh?! it does not return Fname, but shows lname and PHON… deleted everything and started again from the very beginning still d same… please help me u can reply to my mail addy…

  39. Smith said,

    on August 8th, 2008 at 3:38 am

    Where can i download the whole code?????

  40. joel said,

    on August 14th, 2008 at 3:28 am

    pliz guy, I wanted to register members but when I clicked at submit button it displays a blank page.my code is:

  41. Christian said,

    on August 31st, 2008 at 2:03 am

    I am trying this out and getting a blank page too. My form is at:

    http://www.tccnotary.com/newclients.php

    Right now my script is only attempting to write the submitted order date (the first field) to the database. Once I know that works I can work on the other fields. My script, insert.php, is:

  42. Christian said,

    on August 31st, 2008 at 2:03 am

    $orderDate = $_POST['orderDate'];

    mysql_connect (”localhost”, “tcc”, “cameronTom”) or die (’Error: ‘ . mysql_error ());
    mysql_select_db (”neworder”);

    $query=”INSERT INTO clientsopennew (orderID, orderDate)VALUES (’NULL’,'”$orderDate.”‘)”;

    mysql_query($query) or die (’Error updating database’);

    echo “Database updated with: ” .$orderDate ;

  43. Christian said,

    on September 4th, 2008 at 2:43 am

    Anyone? Anyone?

  44. Martijn said,

    on September 9th, 2008 at 10:54 am

    Can anyone help why this is not working. The database is not updated.

    All help is more than welcome.

    Thanks

    $connectionID=mysql_connect(’localhost’,'test’,”);
    $dbname=mysql_select_db(’testdb’);

    if($action==”INS”)
    {
    $Poule1 = $_POST['Poule1'];
    $Poule2 = $_POST['Poule2'];
    $datumtijd = $_POST['datumtijd'];
    $team = $_POST['team'];
    $thuis = $_POST['thuis'];
    $uit = $_POST['uit'];
    $Locid = $_POST['Locid'];
    $scheidsr1 = $_POST['scheidsr1'];
    $scheidsr2 = $_POST['scheidsr2'];
    $tafel = $_POST['tafel'];
    $klok = $_POST['klok'];
    $sec = $_POST['sec'];
    $zaalw = $_POST['zaalw'];

    $query=”INSERT INTO NS_wedstrijden (Poule1, Poule2, datumtijd, team, thuis, uit, Locid, scheidsr1, scheidsr2, tafel, klok, sec, zaalw) VALUES (’”.$Poule1.”‘, ‘”.$Poule2.”‘, ‘”.$datumtijd.”‘, ‘”.$team.”‘, ‘”.$thuis.”‘, ‘”.$uit.”‘, ‘”.$Locid.”‘, ‘”.$scheidsr1.”‘, ‘”.$scheidsr2.”‘, ‘”.$tafel.”‘, ‘”.$klok.”‘, ‘”.$sec.”‘, ‘”.$zaalw.”‘)”;
    $result = mysql_db_query(”Wedstrijd”,$query,$connectionID) or die (”Error updating database” . mysql_error() . “\n$query\n”);

  45. Christian said,

    on September 9th, 2008 at 8:57 pm

    All the helpers appear to have left.

  46. John Ward said,

    on September 9th, 2008 at 9:05 pm

    The code looks like it should work.

  47. Christian said,

    on September 11th, 2008 at 3:37 pm

    Do you mean Martijn’s code or my code? Or both?

  48. Chase said,

    on September 12th, 2008 at 9:03 pm

    :Martijn:

    Try something more along the lines of this coding instead, if you prefer to use the mysql_db_query command.

    <?php
    $connectionID = mysql_connect (’localhost’, ‘test’, ‘password’);
    $dbname = mysql_select_db(’testdb’);

    mysql_connect ($connectionID)
    or die (”Could not connect to the MySQL server.”);

    $query = “INSERT INTO NS_wedstrijden (Poule1, Poule2, datumtijd, team, thuis, uit, Locid, scheidsr1, scheidsr2, tafel, klok, sec, zaalw) VALUES (’”.$Poule1.”‘, ‘”.$Poule2.”‘, ‘”.$datumtijd.”‘, ‘”.$team.”‘, ‘”.$thuis.”‘, ‘”.$uit.”‘, ‘”.$Locid.”‘, ‘”.$scheidsr1.”‘, ‘”.$scheidsr2.”‘, ‘”.$tafel.”‘, ‘”.$klok.”‘, ‘”.$sec.”‘, ‘”.$zaalw.”‘)”;

    $result = mysql_db_query ($dbname, $query)
    or die (”Query ‘$query’ failed with error message: \”" . mysql_error () . ‘”‘);

    // Display the data returned by the query
    while ($temp = mysql_fetch_row ($mysql_result)) {
    echo $temp[0], ”;
    }
    ?>

  49. Sasha said,

    on September 20th, 2008 at 7:54 am

    Hi there,
    I’m desperatly looking for help so hope you guys could really help me out.

    I’d need something very simple in which a user can insert data to the DB (like this) and then have a search field per one of the fields (example name) and have everyone of that name pop out.

    How would this be done?
    Thanks!

  50. Mike Maguire said,

    on September 21st, 2008 at 10:05 pm

    Sasha:

    Check out this tutorial that I wrote a while ago:

    http://teamtutorials.com/photoshop-tutorials/web-graphics/sql-select-based-on-text-inserted-into-a-text-box

    I think it is what you are looking for. Thanks.

  51. Christian said,

    on September 30th, 2008 at 2:41 pm

    Still no answer for my question.

  52. John Ward said,

    on September 30th, 2008 at 3:17 pm

    Christian, try to echo your sql variable after you create it. Seems it is not creating a valid update.

  53. John Ward said,

    on September 30th, 2008 at 3:23 pm

    Try either of these:

    $query = ‘INSERT INTO clientsopennew (orderID, orderDate)VALUES (NULL,”$orderDate”)’;

    $query = “INSERT INTO clientsopennew (orderID, orderDate)VALUES (NULL,’”.$orderdate.”‘)”;

  54. Christian said,

    on September 30th, 2008 at 3:59 pm

    Okay, I have an update and clarification. When I use:

    the database does get populated. But when I use:

    The database does not get populated and a blank screen appears.

  55. Christian said,

    on October 2nd, 2008 at 4:20 pm

    Thanks, John, for the response. Okay, I basically have it working now. You can fill out all the fields and it’ll populate the database. Only two problems remain (and they are minor compared to what I was facing before but still important):

    1. If the user uses a character such as an apostrophe it prevents the database from populating.

    2. It’s not populating the product field, which is the only field in this form that utilizes radio buttons.

  56. John Ward said,

    on October 2nd, 2008 at 4:28 pm

    Christina look up sanitizing database inputs. This will gt you started http://xkcd.com/327/ . Not sure about the radio buttons, echo the query and see if the value is being sent.

  57. Christian said,

    on October 2nd, 2008 at 6:04 pm

    “sanitizing database inputs”

    Okay, got it. Thanks . . . and funny cartoon.

  58. Sanjeev said,

    on October 7th, 2008 at 4:03 am

    this is sanjeev
    i have written that code but i am not able to update data in my sql ,
    i am getting the error.

    Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\sandeep\update.php on line 9

    pls help me

  59. Thabiso Chizwe said,

    on October 10th, 2008 at 4:50 am

    when i click submit the whole contents of my php file are displayed in the html page

    here is my script

    <?php

    $Title= $_POST['Title'];
    $FirstName= $_POST['FirstName'];
    $Surname= $_POST['Surname'];
    $JobTitle= $_POST['JobTitle'];
    $Company=$_POST['Company'];
    $Department= $_POST['Department'];
    $Office= $_POST['Office'];
    $BusinessPhone= $_POST['BusinessPhone'];
    $HomePhone= $_POST['HomePhone'];
    $Fax= $_POST['Fax'];
    $Cell =$_POST['Cell'];
    $Email = $_POST['Email'];
    $WebPageAddress= $_POST['WebPageAddress'];
    $PhysicalAddress= $_POST['PhysicalAddress'];
    $MailingAddress= $_POST['MailingAddress'];
    $Birthday= $_POST['Birthday'];
    $month= $_POST['month'];
    $year = $_POST['year'];

    $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (”Error connecting to MySQL”);
    mysql_select_db($dbname, $conn) or die (”Could not open database”);

    $query=”INSERT INTO contacts(Title,FirstName,Surname,JobTitle,Company,Department,Office,BusinessPhone,HomePhone,Fax,Cell,Email,WebPageAddress,PhysicalAddress,MailingAddress,Birthday,month,year)VALUES(’”.$Title”‘, ‘”$FirstName”‘,’”$Surname”‘,’”$JobTitle”‘,’”$Company’”,’”.$Department’”,’”.$Office”‘,’”.$BussinessPhone’”,’”.$HomePhone’”,’”.$Fax”‘,’”$Cell”‘,’”.$Email”‘,’”.$WebPageAddress”‘,’”.$PhysicalAddress”‘,’”.$MailingAddress”‘,’”.$Birthday”‘,’”.$month”‘,’”.$year”‘)”;
    mysql_query($query);
    echo “Record Addedclick hereto return to contacts”;

    $result = mysql_query($query);

    mysql_close($db1);
    mysql_close($conn);
    echo “”;

    ?>

  60. Amir said,

    on October 20th, 2008 at 3:49 pm

    Hi
    I need help please.
    I keep trying and get the messege: Error Updating Database.
    Any suggestions?
    Many thanks in advance.

    Amir

    The codes:

    form:

    First Name:

    Last Name:

    Phone-Numbe:

    update:

    table:
    <?php
    // Connects to Database
    mysql_connect(”localhost”, “xxx”, “xxx”) or die(mysql_error());
    mysql_select_db(”friends”) or die(mysql_error());

    //collects data from “friends” table
    $data = mysql_query (”select * from tablename “) or die (mysql_error(Error));

    //puts the “tablename” info into the $info_array
    $info=mysql_fetch_array($data);
    //print out the contents of the entry
    Print “”;
    Print “”;
    Print “Family Name:”.$info['FName'].”";
    Print “Last Name:”.$info['LName'].”";
    Print “Phone No.:”.$info['PHON'].”";
    Print “”;
    ?>

  61. Henry said,

    on October 22nd, 2008 at 6:32 am

    Please can you kindly send the query for insserting into the database using php? because i tried the one written here but the report that I got was that there was an error in line 7 which I tried all tha I could but it still dosent work.

  62. Henry said,

    on October 22nd, 2008 at 6:36 am

    I will be Very greatful if someone can kindly help solve my TRASH

    Thanks

  63. Henry said,

    on October 22nd, 2008 at 7:02 am

    Please is there a web site or page that I can download the whole code????????????????????????

  64. John Ward said,

    on October 22nd, 2008 at 9:50 am

    Please post lines 6 and 7 from your code. Most likely you forgot a semicolon.

  65. John Ward said,

    on October 22nd, 2008 at 9:51 am

    Also these comments are getting pretty long. Maybe we should launch a forum for these types of questions?

  66. John Ward said,

    on October 22nd, 2008 at 10:26 am

    Thiboso are you saving these files with a .php extension and is php running on your server??

  67. Henry said,

    on October 22nd, 2008 at 10:31 am

    Please take a good look at this query that I wrote.

    Is there anything missing?? Yet I still recieve this (Parse error: parse error, unexpected ‘;’ in C:\wamp\www\root\update.php on line 7).

    Please I need your help Here …thanks so Far

  68. John Ward said,

    on October 22nd, 2008 at 12:07 pm

    I don’t see the code you posted, but that error message is telling you exactly what is wrong. Unexpected semicolon, which means you have an extra one or you forgot something else in the line before it. If you post lines 6 &7 I will tell you what is wrong with them.

  69. John Ward said,

    on October 22nd, 2008 at 12:10 pm

    Amir there is no update statement in the code you posted. The code you posted cannot result in the error you are stating.

  70. Amir said,

    on October 25th, 2008 at 5:33 am

    Hi All

    Thank you.
    Got my mistake and fixed it.
    Working now.

    Many thanks!!

    And I think a forum for that sort of questions would be very helpfull.

    Amir

  71. Alee said,

    on November 6th, 2008 at 7:20 am

    very nice and useful example gud work keep it up …

  72. Priya said,

    on November 24th, 2008 at 3:18 am

    Hi,

    Very helpful site.
    I have a problem .. could any ine pls help me.
    I’m using php,MySql.
    In my code there is a checkbox. I want to update that checkbox value in the database.. whether it is checked or not. How to capture that value in the database.

  73. Paul said,

    on November 27th, 2008 at 12:53 am

    I cannot seem to get the database to update or post. Please Help. Here’s my code.

    [
    <?php
    //Verrify Session
    session_start();
    if(!session_is_registered(myusername)){
    header("location:index.php?id=accessdenied");
    }

    // Rest of Page
    require_once ("functions.php");
    connect();
    mysql_select_db("news")or die("cannot select DB");

    // Table Selection - Via URL
    $table = $_GET['table'];

    // Defining The Form Data
    $form_subject = $_GET['subject'];
    $form_date = $_GET['date'];
    $form_column = $_GET['column'];
    $form_preview_post = $_GET['preview_post'];
    $form_full_post = $_GET['full_post'];

    // Defining Who It Was Posted By
    $session_name = $_SESSION['myusername'];

    $sql=”INSERT INTO `$table`(`subject`, `date`, `category`, `preview`, `post`)VALUES(`$form_subject`, `$form_date`, `$form_column`, `$form_preview_post`, `$form_full_post`)”;
    mysql_db_query($sql);

    /*
    if($result){
    echo “Successful”;
    echo “”;
    echo “Back to main page“;
    }
    else {
    echo “ERROR”;
    }*/
    ?>
    ]

  74. k0s said,

    on December 1st, 2008 at 11:29 am

    Hi,
    perfect tutorial :D
    thank you,..

    a small advanced question.. i would like to fill out “radiobuttons names” with categorys which should be read out from a database and insert values like names description etc into the given and by radiobutton selected category.

    could you point me to a similar tutorial ?
    thank you very much!

    have a nice day

  75. Patrick said,

    on December 7th, 2008 at 9:01 pm

    Hey I am having the same problem as Amir, I keep getting the “die” message “error updating database”.

    I’m guessing mismatched column names with the database? but I’ve double checked about a zillion times lol. sorry to be a pain…

    Thanks for your help.

  76. Patrick said,

    on December 7th, 2008 at 9:15 pm

    sorry! i got it working! yay :)

    stupid commas…

  77. ashish said,

    on December 28th, 2008 at 4:12 pm

    hi..thanks for the code..while i m clicking on ‘Update database’ button, the output is
    $Fname=$_Post['Fname']; $Lname=$_POST[['Lname']; mysql_connect(”localhost”,”abcd”,”1234″) or die(’Error’ .mysql_error()); mysql_select_db(”test1″); $query=”INSERT INTO test1(ID,Fname,Lname) VALUES (’NULL’,'”.$Fname.”‘, ‘”.$LName”)”; mysql_query($query)or die (’Error updating database’); echo “Database Updated with: “.Fname.” “.LName.; mysql_close();

    My code for update.php( i m using the same code as mentioned above: -

    Untitled Document

    $Fname=$_Post['Fname'];
    $Lname=$_POST[['Lname'];
    mysql_connect(”localhost”,”abcd”,”1234″) or die(’Error’ .mysql_error());
    mysql_select_db(”test1″);
    $query=”INSERT INTO test1(ID,Fname,Lname) VALUES (’NULL’,'”.$Fname.”‘, ‘”.$LName”)”;
    mysql_query($query)or die (’Error updating database’);

    echo “Database Updated with: “.Fname.” “.LName.;
    mysql_close();

  78. shakir said,

    on January 26th, 2009 at 2:40 pm

    how to display the data in a table from the database using select query

  79. Shalom said,

    on February 18th, 2009 at 10:28 am

    The code you palced really help. I also wanted to know How you merge several List/menu options into one when writting php code. Lets say u have a drop down list for day another one for month and year. But the database entry is a single entry.

  80. Jack said,

    on February 19th, 2009 at 2:29 am

    I’m just trying to add one record on my database. Unfortunatley it just says ‘Error updating database’ everytime I try to add a valid record. Here is my code. Please help. Very Urgent.

    <?php

    $country_name = $_POST['country_name'];

    // Initiating a MySQL connection
    $db_host = “localhost”;
    $db_username = “testuser”;
    $db_passwd = “testpass”;
    $db= mysql_connect($db_host, $db_username, $db_passwd) or die (”Could not connect to database”);
    echo “Connection established.”;

    // Connecting to database
    $db_name = “country”;
    mysql_select_db(”$db_name”) or die (”Could not select the database gurung”);
    echo “Database country is selected.”;

    $query=”INSERT INTO country (countryID, country_name) VALUES (’NULL’, ‘”.$country_name”‘)”;

    mysql_query($query) or die (’Error Updating database’);

    echo “Database Updated With: ” .$country_name. “”;
    ?>

  81. John Ward said,

    on February 19th, 2009 at 6:02 am

    Jack. I lied in the tutorial above. You don’t have to use . if you use double quote it will echo the variable. Try this:

    $query=”INSERT INTO country (countryID, country_name) VALUES (’NULL’, ‘$country_name’)”;

  82. John Ward said,

    on February 19th, 2009 at 6:03 am

    Or if you want to do it the other way:

    $query=”INSERT INTO country (countryID, country_name) VALUES (’NULL’, ‘”.$country_name.”‘)”;

    You forget a period

  83. Jack said,

    on February 19th, 2009 at 9:17 pm

    John, thanks for the reply. I tried removing the double quote in $country_name but it still comes with ‘Error updating database’ error. When you mentioned “You forget a period”. What do you mean by that. The $query you wrote in your second comment is same as the one I wrote! Please help.
    Many thanks, Jack.

  84. Jack said,

    on February 20th, 2009 at 12:12 am

    Hey folks,

    If anyone of you out there is struggling, use the following code:

    This code works perfect. Put your thumbs up.

    Cheers,
    Jack


  85. on February 20th, 2009 at 3:16 am

    [...] Creating a Form that will Search a MySQL Database [...]

  86. vivek kumar said,

    on February 28th, 2009 at 3:06 pm

    sir,what you did above doesn’t work for me……………
    nothing is entered in my data base
    please help me

    its urgent…….
    reply soon

  87. sivagami said,

    on March 3rd, 2009 at 2:39 am

    <?php
    // Connects to your Database
    $host=”localhost”; //Host Name
    $username = ” root”; //mysql user name
    $password =” sivagami”; //mysql password
    $db_name =”tms” ;//database name
    $tbl_name =”employee” ; //Table Name

    mysql_connect(”localhost”, “root”, “sivagami”) or die(mysql_error());
    mysql_select_db(”tms”) or die(mysql_error());

    $emp_id = $_POST['emp_id'];
    $emp_name = $_POST['emp_name'];
    $address = $_POST['address'];
    $phone = $_POST['phone'];
    $date_of_birth = $_POST['date_of_birth'];
    $date_of_join = $_POST['date_of_join'];
    $designation = $_POST['designation'];

    $query =”INSERT INTO $tbl_name (emp_id, emp_name,address,phone,date_of_birth,date_of_join,designation) VALUES ( ‘”.$emp_id.”‘, ‘”.$emp_name.”‘,’ “.$address.”‘,’”.$phone.”‘,’”.$date_of_birth.”‘, ‘”.$date_of_join.”‘,’”.$designation.”‘ )”) or die(mysql_error());
    $result = mysql_query($query) or die(’Error updating database’);
    if($result)
    {
    echo “successfull”;
    echo “”;
    }
    else {
    echo “ERROR”;
    }
    mysql_close();
    ?>

    is this correct or not. i doesn’t work properly. i am not able to insert data to table through forms in php
    please anybody help me.

  88. John Ward said,

    on March 3rd, 2009 at 2:19 pm

    Why are you trying to add the die() function to the $query VARIABLE.

    Also if you are using php 5 there is no need for concatenation of a string if you use double quotes (meaning no need to use “.” just simple put the $variable in like below) I wrote this a long time ago and have learned a lot since. Maybe I will write some kind of updated version if I get a chance.

    Anyway try this and if it doesn’t work you are going to have to figure it out. This isn’t a code writing service, though I could probably make a pretty penny if I charged for it ;)

    <?php
    // Connects to your Database
    $host=”localhost”; //Host Name
    $username = ” root”; //mysql user name
    $password =” sivagami”; //mysql password $db_name =”tms” ;//database name $tbl_name =”employee” ; //Table Name

    mysql_connect(”localhost”, “root”, “sivagami”) or die(mysql_error());
    mysql_select_db(”tms”) or die(mysql_error());

    $emp_id = $_POST['emp_id'];
    $emp_name = $_POST['emp_name'];
    $address = $_POST['address'];
    $phone = $_POST['phone'];
    $date_of_birth = $_POST['date_of_birth']; $date_of_join = $_POST['date_of_join']; $designation = $_POST['designation'];

    $query =”INSERT INTO $tbl_name (emp_id, emp_name,address,phone,date_of_birth,date_of_join,designation) VALUES ( ‘$emp_id’, ‘$emp_name’,'$address’,'$phone’,'$date_of_birth’, ‘$date_of_join’,'$designation’)”;

    $result = mysql_query($query) or die(’Error updating database’);

    if($result){
    echo “successfull”;
    echo “”;
    }
    else {
    echo “ERROR”;
    }
    mysql_close();
    ?>

    Also in your code I don’t think mysql_close() is actually doing anything. You need to set a variable equal to your connect and then close it. Something like $conn = mysql_connect(whatever you want here); mysql_close($conn);

    If the code outputs an error try to Google it. If it doesn’t out put anything echo $query to verify it is valid.

  89. Charles Scott said,

    on March 3rd, 2009 at 2:48 pm

    Works perfectly. Thank you

  90. sivagami said,

    on March 5th, 2009 at 1:58 am

    i have a poblem in inserting data into table. i am puting dateof birth as select oprion as month, year,date. the user select this and post to table. but i create only date_of birth field as date data type. hoe i insert these there input into one field in table. please anybosy help me. the following coding only use. is ther eany error suggesstion please reply me.

  91. sivagami said,

    on March 5th, 2009 at 2:07 am

    Thanks mr.john ward. i try as you said. i have further confusion i am putting date of birth as select option in form user enter three inout date,month,year. but i am using dateof birth as single field in mysql table. now how i put my date into table. the following code only i tried. but it also doesn’t work. what to do sir.

  92. John Ward said,

    on March 6th, 2009 at 6:09 am

    sivgavin you hav three fields day month year, just format them into a date before you insert it into the database. $date = $_POST[''year"].”/”.$_POST_['month''].”/”.$_POST['day'] or whatever format you want ot use. THen insert $date.


  93. on March 13th, 2009 at 1:03 pm

    [...] If you haven’t taken a look at the past tutorials you may want to: How to Access a MySQL Database Using PHP Inserting Data Into a MySQL Database using PHP [...]

  94. sivagami said,

    on March 14th, 2009 at 12:20 pm

    how i pass my dropdown menu & radiobutton selected item into database mysql . please reply me . i am in deadline of my final year project work. i am a student.

  95. John Ward said,

    on March 15th, 2009 at 8:50 pm

    sivagami it sounds like you need to read the tutorial again. I tell you exactly how to do this with an input box. Set the name on your drop down box and that will be the variable passed.

  96. sivagami said,

    on March 16th, 2009 at 4:09 am

    thanks sir. it works correctly. sorry i am poor in php. thats why i am querying here. i am using separate function for getting date month and year. that’s why i am finding very difficult. here is my coding.

    function createYears($start_year, $end_year, $id=’year_select’, $selected=null)
    {

    /*** the current year ***/
    $selected = is_null($selected) ? date(’Y') : $selected;

    /*** range of years ***/
    $r = range($start_year, $end_year);

    /*** create the select ***/
    $select1 = ”;
    foreach( $r as $year )
    {
    $select1.= “$year\n”;
    }
    $select1 .= ”;
    return $select1;
    }

    from this which one is id of select option. either year_select or return value select1.

  97. Rod said,

    on March 23rd, 2009 at 5:33 pm

    hey there!

    everything was working proper until the update.php part or the 3rd part!

    it works half way thou,

    it send info to the info to the server, but only the field, not the info shows either on the server or in the update.php
    example name: john

    on my server and .php file will show name: “empty or blank”

    that start to happen i was trying to fix the update.php file, i went to server and add two more names as in the beginning of the tutorial and then when i used the database.php file to see if updates the only filed showing was the phone number , first and last name was “black”

    what went wrong?

  98. Rod said,

    on March 23rd, 2009 at 5:35 pm

    ah also when it updates the info below will show blank!
    Database Updated With: “blank”

  99. John Ward said,

    on March 23rd, 2009 at 7:38 pm

    Seems like your variables aren’t getting passed. Echo your update statement and see if it is correct.

  100. Rod said,

    on March 23rd, 2009 at 11:11 pm

    by the way how do i echo my update statement ?

  101. John Ward said,

    on March 24th, 2009 at 3:38 am

    $query=”INSERT INTO TestTable (ID, FNAME, LNAME, PHON)VALUES (’NULL’,'”.$FNAME.”‘,’”.$LNAME.”‘,’”.$PHON.”‘)”;
    mysql_query($query) or die (’Error Upadating Database’);
    echo “Database Updated With: “.$FNAME.” “.$LNAME.” “.$PHON;

    echo $query;

    You probably aren’t passing the variables correctly. Are you using the get or post method?

  102. Rod said,

    on March 24th, 2009 at 11:04 am

    hey john,
    i find out what was wrong with it!

    $FNAME = $_POST['FNAME'];
    $LNAME = $_POST['LNAME'];
    $PHON = $_POST['PHON'];

    i typed post instead POST ops!

    but sitll not completely right! its not passing the phone data! it does not show any error , just dont add to “Database Updated With: “.$FNAME.” “.$LNAME.” “.$PHON; either the database itself

    i know it was a post before with similar problem not sure if was a solution for it! i’ll go back there and read again!

    also i add

    echo $query;

    to my code and it didnt worked to well!

    i’m postin my whole update.php file so you can take a look!

    update

  103. Rod said,

    on March 24th, 2009 at 11:05 am

    update

  104. Rod said,

    on March 24th, 2009 at 11:06 am

  105. Rod said,

    on March 24th, 2009 at 6:51 pm

    Hey John,

    thankx so much! it works perfectly now,
    just for future developers i will add this,
    my code wasnt working first, instead
    POST
    i typed
    post

    second!
    on my form.php i mistyped again,
    instead PHON i typed FHON;

    problem solved now! thanks John code is great!
    now moving to Log in part…hehe

  106. Rod said,

    on March 24th, 2009 at 11:09 pm

    Hey john.
    me again!
    one more question, how do i display my data in row and colomn like this

    mysql> DESCRIBE employee_data;
    +——–+——————+——+—–+———+—————-+
    | Field | Type | Null | Key | Default | Extra |
    +——–+——————+——+—–+———+—————-+
    | emp_id | int(10) unsigned | | PRI | 0 | auto_increment |
    | f_name | varchar(20) | YES | | NULL | |
    | l_name | varchar(20) | YES | | NULL | |
    | title | varchar(30) | YES | | NULL | |
    | age | int(11) | YES | | NULL | |
    | yos | int(11) | YES | | NULL | |
    | salary | int(11) | YES | | NULL | |
    | perks | int(11) | YES | | NULL | |
    | email | varchar(60) | YES | | NULL | |
    +——–+——————+——+—–+———+—————-+

  107. John Ward said,

    on March 25th, 2009 at 1:31 am

    <table>
    <tr>
    <th>field 1</th>
    <th>filed 2</th>
    <tr>

    <?php while $row = mysql_fetch_array($query){
    ?>
    <tr>
    <td>
    <?php echo $row['field1'];?&gt
    </td>
    <td>
    <php echo $row['field2'];>
    </td>
    </tr>

    <?php } ?>
    </table>

  108. Rod said,

    on March 25th, 2009 at 11:55 am

    Thanks Johne once again!

    so that is how my code should looks like adding that to my tutorial?

    mysql_error());
    mysql_select_db (”necrose66″);

    //build query
    $query = mysql_query(”SELECT * FROM TestTable”);

    // display results

    ?>

    Name
    Last

    <?php while $row = mysql_fetch_array($query)) { echo ” ID: ” .$row['ID']. ” First Name: “.$row['FNAME']. ” Last Name: “.$row['LNAME'].” Phome: “.$row['PHON'].” “;}

    ?>

    <?php echo $row['FNAME'];?&gt

  109. jason1 said,

    on March 26th, 2009 at 6:34 pm

    I did this, but i get

    No Database Selected. as my error.

    What could the problem be? I have checked my PHPmyAdmin and the correct db_xxxxx is there, as is the table.

    I checked the process log in phpmyadmin as well, and it shows database ‘none’ in the ‘Kill’ process.

    :(

  110. Jay K said,

    on April 7th, 2009 at 12:26 pm

    Hi Guys, Great tutorial, however keep coming up with an error:

    The following is for update.php but i have used filename newcustomer.php
    Parse error: parse error on line 11 (begins with $query=”INSERT INTO)

  111. Jay K said,

    on April 7th, 2009 at 12:27 pm

    Hi Guys, Great tutorial, however keep coming up with an error:

    The following is for update.php but i have used filename newcustomer.php
    Parse error: parse error on line 11 (begins with $query=”INSERT INTO)

  112. Jay K said,

    on April 7th, 2009 at 12:59 pm

    Dont worry…. got it sorted!

  113. Cory James said,

    on April 9th, 2009 at 11:45 pm

    Hi Guys, I need a little help.

    I am trying to do something “simple” that is collect emails for an e-bulletin signup with the form post method in flash to write to a mysql database using php.

    MYSQL version is 5.0.32
    PHP Version is 5.2.6
    I am using Action Script 2.0 in Flash

    Here is my php:

    And here is my actionscript:

    function sendEmail(email)
    {
    var _loc1 = new LoadVars();
    _loc1.email = email;
    _loc1.onLoad = function (ok)
    {
    submit_btn.enabled = true;
    };
    _loc1.sendAndLoad(”http://realityla.com/form.php”, _loc1, “POST”);
    gotoAndStop(2);
    } // End of the function
    stop ();
    userPath = email_txt;
    userPath.onSetFocus = function ()
    {
    userPath.text = “”;
    };
    submit_btn.onRelease = function ()
    {
    indexOfAt = email_txt.text.indexOf(”@”);
    lastIndexOfDot = email_txt.text.lastIndexOf(”.”);
    if (indexOfAt != -1 && lastIndexOfDot != -1)
    {
    if (lastIndexOfDot < indexOfAt)
    {
    message.text = “please verify your email.”;
    }
    else
    {
    var _loc2 = email_txt.text;
    this.enabled = false;
    sendEmail(_loc2);
    } // end else if
    }
    else
    {
    message.text = “please enter correct email address”;
    } // end else if
    };

    MYSQL version is 5.0.32
    PHP Version is 5.2.6
    I am using Action Script 2.0 in Flash

    Maybe I am just tired, but it’s not working. Help please!!!

  114. Cory James said,

    on April 9th, 2009 at 11:48 pm

    Sorry, here is my php, geesh….

    Email Post

  115. Cory James said,

    on April 9th, 2009 at 11:49 pm

    // Connects to your Database
    $host=”mysql.realityla.com”; //Host Name
    $username = ”coryjames”; //mysql user name
    $password =”mark1045”; //mysql password $db_name =”tms” ;//database name $tbl_name =”employee” ; //Table Name

    mysql_connect(”mysql.realityla.com”, “coryjames”, “mark1045”) or die(mysql_error());
    mysql_select_db(”ebulletin”) or die(mysql_error());

    $email = $_POST['email'];

    $query =”INSERT INTO $email (email) VALUES (‘$email’)”;

    $result = mysql_query($query) or die(’Error updating database’);

    if($result){
    echo “successfull”;
    echo “”;
    }
    else {
    echo “ERROR”;
    }
    mysql_close();
    ?>

  116. leo said,

    on April 15th, 2009 at 3:08 am

    Hi
    is there any way that i can create user by assigning privilleges by just clicking on the check boxes {check boxes for assigning privilleges}
    i can create the database with textboxes but don’t have an idea about the check boxes
    Help needed!

  117. Daniel said,

    on April 16th, 2009 at 10:28 am

    I’m trying to write data and time using PHP but am not having any luck. This is the code I use:

    $sql = “update contacts set ” . “address=’$address’, ” . “address2= ‘$address2′,” . “city= ‘$city’,” . “state= ‘$state’,” . “zip= ‘$zip’,” . “country= ‘$country’,” . “officephone= ‘$officephone’,” . “homephone= ‘$homephone’,” . “fax = ‘$fax’” . “whensubmitted= NOW(),” . “WHERE id LIKE ‘$recordid’ “;

    I get an error with the whensubmitted= NOW() command.

    Can anyone help?

  118. John Ward said,

    on April 16th, 2009 at 10:37 am

    $sql = “update contacts set address=’$address’, address2= ‘$address2′, city= ‘$city’, state= ‘$state’, zip= ‘$zip’,country= ‘$country’, officephone= ‘$officephone’, homephone= ‘$homephone’, fax = ‘$fax’, whensubmitted= NOW() WHERE id LIKE ‘$recordid’ ;

    there was no comma before when submit. Other than that I’m not sure, Post the error next.

  119. soumya said,

    on May 29th, 2009 at 12:29 pm

    hi! everyone i have made a register page in php which will collect data in a form from user and store it in mysql db .My prob is that on clicking the submit button i get a blank page n a blank record is created in db .
    i hav checked the code so many times but to no gud please help me iam a newbie.iam posting the code below:<?php
    if(isset($_POST['user'])&&isset($_POST['pass']))
    {

    if(strlen($_POST['user'])<4)

    echo”Username Must Be More Than 4 Characters.”;

    elseif(strlen($_POST['pass'])<6)

    echo”password must be more than 6 characters.”;

    elseif($_POST['user']==$_POST['pass'])

    echo”username and password cannot be same”;

    else
    {
    include(”register.php”);

    $firstname=$_POST['fname'];
    $lastname=$_POST['lname'];
    $username=mysql_real_escape_string($_POST['user']);
    $password=$_POST['pass'];
    $sex=$_POST['sex'];
    $occupation=$_POST['occupation'];
    $city=$_POST['city'];
    $state=$_POST['state'];
    $country=$_POST['country'];
    $phno=$_POST['phno'];
    $emailid=$_POST['email'];
    $comment=$_POST['comment'];

    $sqlcheckforduplicate=”SELECT user FROM userinfo WHERE user=’$username’;”;

    if(mysql_num_rows(mysql_query($sqlcheckforduplicate))==0)
    {

    $sqlreguser=”INSERT INTO userinfo(firstname,lastname,user,pass,sex,occupation,city,state,country,phno,eid,comment)VALUES(’”.$firstname.”‘,’”.$lastname.”‘,’”.$username.”‘,’”.$password.”‘,’”.$sex.”‘,’”.$occupation.”‘,’”.$city.”‘,’”.$state.”‘,’”.$country.”‘,’”.$phno.”‘,’”.$emailid.”‘,’”.$comment.”‘);”);

    $query= mysql_query($sqlreguser) or die(”error in query:$sqlreguser”.mysql_error());

    $dbh=”register”;
    mysql_close($dbh);

    echo”$query”;
    if($query)
    {
    echo”You are Registered and can now Login”;
    $formusername=$username;

    header(”location:home.php”);
    }
    }

    else
    {
    echo”The username you have choosen is already taken.please try another one.”;

    $formusername=$username;
    }

    }
    }

    else
    {
    echo”You could not be registered because of missing data.”;
    }
    ?>

  120. JC said,

    on June 17th, 2009 at 6:08 am

    This is the code that I have used:

    However whenever I submit my form I always get the ‘error updating database’ message.

    Anyone any ideas as to what I’m doing wrong?

    Thanks in advance!!!!!!!

Leave a Comment