Pages Navigation Menu
No Risk, No Contracts! - Learn coding, Web Design and More!

Inserting Data Into a MySQL Database using PHP

Beautiful WordPress Themes

You should not use this code on a production website.

Warning: This tutorial uses old techniques. It is insecure and will leave your server vulnerable to SQL Injection attacks.This tutorials also uses mysql_ functions that are no longer support. For updated tutorials look for a PDO or MySQLi tutorial.This post will be delete or revised in the future.

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.

  • http://jalaj.net/ Jalaj

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

    • Arun

      really helpfull.. thanks for making foundation strong…

  • http://MyFile janaka

    That is a great help

    • http://gggggg sunita

      hello

      • http://shubh.tk shubh

        hi..
        can we be friends..????

        reply me soon..

      • http://gmail santhosh

        ok………..

      • http://evershine.99k.org Mohamed Asif

        Hello Sunita

      • http://www.gmail.com kms

        hiiiiii

  • http://live.com Enlamsweawn

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

  • http://www.dadssa.com gabr

    dasdasdasd

  • http://www.paradigminfosystem.com upendra

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

  • http://citadelstudios.net Hunter

    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?

  • http://www.teamtutorials.com John Ward

    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.

    • Hafiz Haseeb Ali

      hello
      john……
      how are u?
      john plz send me information of php date() using database if possible then plz send me mail……..plz

    • Ashwini Jain

      how to generate a auto exectable code in php need to do corn job

      • http://w3school fff

        khabar hoy to su joiy e bhai

  • http://citadelstudios.net Hunter

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

  • http://www.teamtutorials.com John Ward

    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.

    • http://d ds

      dssa

  • http://citadelstudios.net Hunter

    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

    • G-Unit

      sup yo ?

  • http://www.e-medipay.com Zeek

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

  • http://www.webpixindia.com web pix

    Thanks a lot….it clears my doubts :)

  • astravie

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

  • http://grownsafir.multiply.com rifas

    thank a lot…

    it is very helpful for me to do assignment..

  • moored

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

  • Shah

    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!!!!!

  • Phil

    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

  • Phil

    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 ;

  • sayed Mujahed Hussaini

    Thank you very much

  • http://databasewebsite sundar

    hi
    i want set a update and view buton

  • sanae

    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

  • http://www.teamtutorials.com Mike Maguire

    @ 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.

  • http://www.teamtutorials.com Mike Maguire

    (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

    • http://carminesolutios.com ramesh

      sir i want to full format of how much chekbox colum are create in table and how insert it

  • http://www.qualitycodes.com Junaid Shabbir

    Nice tutorial, syntax highlight really helps in understanding the code

  • long4hort

    nice tutorial

  • http://. IJ

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

  • http://. IJ

    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();

  • http://www.teamtutorials.com John Ward

    @IJ

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

  • http://. IJ

    @John
    the error is :
    error updating database

  • Mahadia Tunga

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

  • mahadia

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

    thanx!

  • ian

    tnx but i didnt get it

  • http://www.nauticaldog.com fil mcrackin

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

  • paul

    Thanks for this simple article about inserting to database

  • Ritesh

    Nice code.
    It works very well.

  • JyRnZa

    a big help

  • Charles

    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…!

  • Charles

    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…

  • http://www.qualitycodes.com/tutorials.php Smith

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

  • http://www.ku.ac.ke joel

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

  • http://cmziebarth@gmail.com Christian

    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:

  • http://cmziebarth@gmail.com Christian

    $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 ;

  • http://cmziebarth@gmail.com Christian

    Anyone? Anyone?

  • Martijn

    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”);

  • http://cmziebarth@gmail.com Christian

    All the helpers appear to have left.

  • http://www.teamtutorials.com John Ward

    The code looks like it should work.

  • http://cmziebarth@gmail.com Christian

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

  • Chase

    :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], ”;
    }
    ?>

    • jerimy

      the codes that you post is use for connecting mysql in your database!
      can you give me some codes of creating database of banks using my sql?

  • Sasha

    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!

  • http://www.teamtutorials.com Mike Maguire

    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.

  • Christian

    Still no answer for my question.

  • http://www.teamtutorials.com John Ward

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

  • http://www.teamtutorials.com John Ward

    Try either of these:

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

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

    • jerimy

      i thougt using ” or ‘ is the same.
      i think thats not the error

      • http://happyturtledesigns.com Feck

        Single quotes will not parse variables. Double quotes will. This is the MONUMENTAL difference.

  • Christian

    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.

  • Christian

    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.

  • http://www.teamtutorials.com John Ward

    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.

  • Christian

    “sanitizing database inputs”

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

  • Sanjeev

    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

  • Thabiso Chizwe

    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 “”;

    ?>

  • http://www.amir2000.nl Amir

    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 “”;
    ?>

    • wujira

      please join me

  • Henry

    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.

  • Henry

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

    Thanks

  • Henry

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

  • http://www.teamtutorials.com John Ward

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

  • http://www.teamtutorials.com John Ward

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

  • http://www.teamtutorials.com John Ward

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

  • Henry

    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

  • http://www.teamtutorials.com John Ward

    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.

  • http://www.teamtutorials.com John Ward

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

  • http://www.amir2000.nl Amir

    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

  • Alee

    very nice and useful example gud work keep it up …

  • Priya

    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.

  • Paul

    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”;
    }*/
    ?>
    ]

  • http://none k0s

    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

  • Patrick

    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.

  • Patrick

    sorry! i got it working! yay :)

    stupid commas…

  • ashish

    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();

    • http://www.creativegroup.co.cc Omkar Joshi

      hey u have not installed Apache or any server package …because of that its showing u entire code….install XAMPP or LAMP pakage and then run the code.

      Thank You

      Omkar Joshi

  • shakir

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

  • Shalom

    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.

  • Jack

    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. “”;
    ?>

  • http://www.teamtutorials.com John Ward

    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’)”;

  • http://www.teamtutorials.com John Ward

    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

  • Jack

    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.

  • Jack

    Hey folks,

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

    This code works perfect. Put your thumbs up.

    Cheers,
    Jack

  • Pingback: Convert a MySQL date field using PHP Functions | Team Tutorials

  • vivek kumar

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

    its urgent…….
    reply soon

  • sivagami

    <?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.

  • http://www.teamtutorials.com John Ward

    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.

  • Charles Scott

    Works perfectly. Thank you

  • sivagami

    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.

  • sivagami

    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.

  • http://www.teamtutorials.com John Ward

    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.

    • http://NA Dorjee

      Hi Sir John!

      May I please request you to kindly send me a code for php feedback form so that I will received a feedback on my mail..I have search on internet but its not working..I don’t know what I am doing .. I am new to PHP but I really need of feedback/contact code.. Thanking you …

      Regards
      Dorjee

  • Pingback: Editing MySQL Data Using PHP | Team Tutorials

  • sivagami

    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.

  • http://www.teamtutorials.com John Ward

    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.

  • sivagami

    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.

  • Rod

    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?

  • Rod

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

  • http://www.teamtutorials.com John Ward

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

  • Rod

    by the way how do i echo my update statement ?

  • http://www.teamtutorials.com John Ward

    $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?

  • Rod

    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

  • Rod

    update

  • Rod
  • Rod

    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

  • Rod

    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 | |
    +——–+——————+——+—–+———+—————-+

  • http://www.teamtutorials.com John Ward

    <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>

  • Rod

    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

  • jason1

    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.

    :(

  • Jay K

    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)

  • Jay K

    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)

  • Jay K

    Dont worry…. got it sorted!

  • http://realityla.com Cory James

    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!!!

  • http://realityla.com Cory James

    Sorry, here is my php, geesh….

    Email Post

  • http://realityla.com Cory James

    // 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();
    ?>

  • leo

    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!

  • Daniel

    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?

  • http://www.teamtutorials.com John Ward

    $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.

  • soumya

    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.”;
    }
    ?>

  • JC

    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!!!!!!!

  • Maldave

    Hi,

    I was wondering if there is a way to merge the php code and the form into 1 single php code ? The reason why I ask is that I want to put the update dabase funtion into a php block for smf/tinyportal. Is this doable ?

    Thank you ^^

  • http://www.teamtutorials.com John Ward

    Maldave,

    I’m not going to give you the code to do that, but I can give you the basic concept. You will learn more if you figure it out on your own. Basically you set the page up to check the variables you pass in the form (as post variables). So if they are not set, echo the form to enter the data else update the database with whatever that database is set to. Ok here is somewhat of an example. Let’s say the only variable you are pass is called $item.

    //echo header info, etc

    if (!isset($_POST['item'])){
    echo “form to enter item. form action should point back to the same form and method should be post”;
    }else{
    //update database
    }

  • Sunny

    Well !!!
    Very good post …………….
    Please please Please post it’s sequels too……….

  • Harman Malhi

    Its of great use, this website really help me a lot.

    i think every body should use this website for reference.

  • haritha

    Hi,

    I have a doubt in uploading image to database and also in retriew. Plz send any example or any reference site

    Thank you

  • http://www.spiralteck.com web

    how do you insert date into mysql

  • NDEREBEZA PIERRE BENIT

    very fine !

  • sajith

    Thanks thanks a lot.

  • AJ

    Hi – I am totally new to PHP. I am taking an on-line class and have an assignment to create a form with a customer number and current meter reading. Once the user hits ‘submit’ I add this data to my table. Problem is I am getting a “Null values not allowe in column or variable” error. There is a date field and another text field I am not filling. Do I need to put something in the other two fields? Any help would be appreciated.

  • http://www.teamtutorials.com John Ward

    Yes you need ot enter data in the other fields. Either that or change the database to allow null values in those columns.

  • RANIEL

    the ECHO STATEMENT is WRONG………………BULL SHET!!!!!

    this is the right ECHO statement just Copy and paste!

    echo “Database Updated Width: “.$Fname.”,”.$Lname.”,”.$Phon;

    I am also an idiot.

  • http://www.teamtutorials.com John Ward

    Raniel, there is nothing wrong with the original echo statement. All you did was add commas instead of a blank space. Congrats, you are awesome.

  • Paras

    It didnt worked out i m still struck in inserting data in sql table using php……..

  • http://www.pika.me Clay

    F’ ya! I found everything I needed on this site tonight!

  • E. Tung’ande

    I have a table in the database which records the grades a student has scored. I need the rows from this table to be like columns on the output. Please help Iam stack.

    The table is like this

    Student_ID Course_code Assessment_grade End_of_semester Avg

    So what i need is to take the Course_code field contents and output them as fields. and the averages to be under their respective courses.

    for example

    Student_ID ICT2301 ICT2302 ICT2303

    BICTQW90 67 67 89

  • Pingback: Writing to database? - x10Hosting Community

  • Simon

    Fonud this really very usefull however when I add info and hit the submit button to test it comes up with “error updating database” Im guessing this is something to do with my database?
    Can anyone help?

    Thank you

  • tinaweena

    i tried about 10 sites before i could figure out what was wrong with my code. your site helped me figure it out. thx

  • lori

    i cannot figure out what im doing wrong here.. i keep getting error updating database.. please help

  • lori

    // my code
    //

  • lori

    well code isnt posting the link is http://lddenterprise.com/test/test.php

  • nice

    have database update error too

  • Meanpoog

    Thanks very much!!

  • Amin Dad Shah

    Dears,
    i need the way how to insert images & video clips into mysql database & then to retrieve the images & video clips on an html page in separate tags. Please if someone can help me please help me out.
    Thankx in advance.

  • http://www.cypherconcepts.co.ke mutitu

    hi i am having a problem with retrieving data from the database using a php code will someone send me a trial code that i can use

  • http://www.owtravels.com RickyG

    Thanks for the tutorial. Learned a lot! Next thing I want to learn is how to email the data from the form and at the same time put it in the database. Do you have a sample of this in php?

  • Arun

    very helpfull….Thanks very much!!

  • http://www.owtravels.com RickyG

    I’m trying to put make the date look like 2010/02/22. But this error keeps popping up.

    Warning: Division by zero in /home3/oneworo2/public_html/update.php on line 5

    Warning: Division by zero in /home3/oneworo2/public_html/update.php on line 5
    Thank you Ricardo. One of our staff will contact you to finalize your booking on 201020. For inquiries, please note your booking reference number: . You can contact us at 00971 4 3372010.

    This is the code I use.

    <?php
    $Name = $_POST['Name'];
    $Email = $_POST['Email'];
    $Phone = $_POST['Phone'];
    $TourDate = $_POST['year'].”/”.$_POST_['month'].”/”.$_POST['day'];
    $Adults = $_POST['Adults'];
    $Children = $_POST['Children'];
    $Tours = $_POST['Tours'];
    $Others = $_POST['Others'];
    $Comments = $_POST['Comments'];

  • http://www.teamtutorials.com Mike Maguire

    RickyG,
    Not sure what you are doing wrong…How are you setting those values in the previous form? This code works; try this to see if it works for you;

    //Creates the form for input
    <form method=”post” action=”index.php”>
    <input type=”text” name=”year”></input>
    <input type=”text” name=”month”></input>
    <input type=”text” name=”day”></input>
    <input type=”submit” value=”submit”></input>
    </form>
    //echos the values if they are present
    < ?php
    if(isset($_POST['year']) && isset($_POST['month']) && isset($_POST['day']))
    {
    $TourDate = $_POST['year']."/".$_POST['month']."/".$_POST['day'];
    echo $TourDate;
    }
    ?>

  • http://easyifyoucan.com budget

    thank you for sharing, this is just what i was looking for.

  • http://www.owtravels.com RickyG

    Mike Maguire,

    The date worked like a charm! Thanks!

    Is it also possible for you to come up with a how-to article on checkboxes in webforms and how to put the data in mysql and display it using the echo command. i’m not really a programmer so I don’t know if the process I’m asking is correct.

    Thanks for your articles!!!!

  • Pingback: PHP Tutorials » Using PHP to update a database

  • Pingback: Using PHP to update a database « Tutorials

  • Jeremy

    Hi! This script is excatly what i need; however, it doesn’t work for me.. i get a 500 Internal Server Error!! (i replaced all my hosting/db info with ****) here’s my save_data.php code:

    <?php
    $TicketID = $_POST['TicketID'];
    $TicketType = $_POST['TicketType'];
    $FirstName = $_POST['FirstName'];
    $LastName = $_POST['LastName'];
    $DateTicketBought = $_POST['DateTicketBought'];
    $Location = $_POST['Location'];
    $Events = $_POST['Events'];
    $Arena = $_POST['Arena'];

    mysqli_connect ("********", "*******", "********") or die ("Unable to connect, Sorry. Try again later.")
    mysqli_select_db ("20010722009-1")

    $query="INSERT INTO r2m_tickets (TicketID, FirstName, LastName, DateTicketBought, Location, Events, Arena)VALUES ('".$TicketID."', '".$FirstName."', '".$LastName."', '".$DateTicketBought."', '".$Location."', '".$Events."', '".$Arena."')";
    mysqli_query($query) or die ('Error Updating Database. Try Again Later');

    echo "Successful! Database updated with the following information: “.$TicketID.” “.$FirstName.” “.$LastName.” “.$DateTicketBought.” “.$Location.” “.$Events.” “.$Arena.””;
    ?>

    Here’s my form.php code:

    Update Database

    Update info in Database ‘*********’, Table ‘******’

    Ticket ID:

    Ticket Type:

    First Name:

    Last Name:

    Date Ticket Was Bought

    Location:

    Event(s):

    Arena(s):

       

  • http://mybiz4all.iklan-power.com john

    Easy, but very complex to understand

  • JuineP

    this was very helpful thanks. straight forward for a beginer like me to follow

  • Pingback: Using PHP to update a database || Tutorials

  • Pingback: PHP Code » Blog Archive » Using PHP to update a database

  • Pingback: PHP Code : Using PHP to update a database

  • Pingback: Using PHP to update a database « Computer Help Tutorials and Tips

  • Pingback: phpcode » Using PHP to update a database

  • Pingback: Tutorials » Blog Archive » Using PHP to update a database

  • Pingback: Tutorials » Using PHP to update a database

  • Pingback: programmingandcomputertutorials

  • Pingback: Computer Help Tutorials and Tips » Blog Archive » Using PHP to update a database

  • Pingback: Using PHP to update a database | PHP Code

  • Pingback: Using PHP to update a database | Tutorials

  • Pingback: Balıkesir Üniversitesi Tutorials

  • Pingback: PHP Code » Using PHP to update a database

  • Pingback: CW Connect — Blog — Using PHP to update a database

  • Pingback: Using PHP to update a database « phpcode

  • Pingback: Programming and Computer Tutorials » Using PHP to update a database

  • Pingback: » Using PHP to update a database

  • Pingback: Using PHP to update a database

  • Pingback: Using PHP to update a database « computerhelptutorialsandtips

  • Pingback: tutorials

  • Pingback: Learn Computer Tutorials » Using PHP to update a database

  • Pingback: phpcode › Using PHP to update a database

  • Pingback: Tutorials » Using PHP to update a database :: iBlog

  • Pingback: Computer Help Tutorials and Tips » Using PHP to update a database

  • Pingback: Using PHP to update a database « Programming and Computer Tutorials

  • Pingback: Booned — Blog — Using PHP to update a database

  • Pingback: Using PHP to update a database « Learn Computer Tutorials

  • Pingback: Learn Computer Tutorials » Blog Archive » Using PHP to update a database

  • Pingback: programmingandcomputertutorials » Blog Archive » Using PHP to update a database

  • Pingback: Using PHP to update a database « computerhelp

  • Pingback: Using PHP to update a database – phpcode

  • Pingback: Using PHP to update a database @ PHP Code

  • Pingback: Using PHP to update a database « learncomputertutorials

  • Pingback: tutorials › Using PHP to update a database

  • Pingback: phpcode » Blog Archive » Using PHP to update a database

  • Pingback: » Using PHP to update a database tutorials

  • Pingback: Programming and Computer Tutorials » Blog Archive » Using PHP to update a database

  • Pingback: Tutorials » Archiwa bloga » Using PHP to update a database

  • Pingback: Using PHP to update a database - Learn Computer Tutorials

  • Pingback: learncomputertutorials

  • Pingback: Using PHP to update a database

  • Pingback: Computer Help Tutorials and Tips » Blog Archive » Using PHP to update a database

  • Pingback: programmingandcomputertutorials » Blog Archive » Using PHP to update a database

  • Pingback: Using PHP to update a database « Tutorials

  • Pingback: Using PHP to update a database « Learn Computer Tutorials

  • Pingback: Learn Computer Tutorials » Using PHP to update a database

  • Pingback: Balıkesir Üniversitesi Tutorials

  • Pingback: tutorials

  • Pingback: Using PHP to update a database « PHP Code

  • Pingback: PHP Code » Using PHP to update a database :: iBlog

  • Pingback: CW Connect — Blog — Using PHP to update a database

  • Pingback: Learn Computer Tutorials » Blog Archive » Using PHP to update a database

  • Pingback: Tutorials » Archiwa bloga » Using PHP to update a database

  • Pingback: Programming and Computer Tutorials - Using PHP to update a database

  • Pingback: tutorials › Using PHP to update a database

  • Pingback: phpcode » Using PHP to update a database

  • Pingback: Tutorials » Using PHP to update a database

  • Pingback: Using PHP to update a database « phpcode

  • Pingback: Using PHP to update a database « Computer Help Tutorials and Tips

  • Pingback: Using PHP to update a database « learncomputertutorials

  • Pingback: » Using PHP to update a database learncomputertutorials

  • Pingback: Booned — Blog — Using PHP to update a database

  • Pingback: Tutorials » Blog Archive » Using PHP to update a database

  • Pingback: Tutorials » Using PHP to update a database :: iBlog

  • Pingback: Programming and Computer Tutorials » Using PHP to update a database

  • Pingback: Using PHP to update a database « Programming and Computer Tutorials

  • Pingback: Computer Help Tutorials and Tips » Using PHP to update a database

  • Pingback: PHP Code » Using PHP to update a database

  • Pingback: PHP Code : Using PHP to update a database

  • Pingback: Using PHP to update a database @ PHP Code

  • Pingback: programmingandcomputertutorials

  • Pingback: » Using PHP to update a database

  • Pingback: Using PHP to update a database « computerhelptutorialsandtips

  • Sacen

    Hi Thanks for the tutorial.

    I having the same problem alots of people having on the top. Enter data to the form return blank page and data not updating. Here is my code :

    Please help, Thanks in advance

  • Sacen
  • mehmet

    i can insert data in mysql by php but i want add two releation table with same id fore example user will have two table firstli he add information in a table from a form after that he can add any information in second table in different time.how can i use same id in two table andthats id can be unique for thats users?

  • Pingback: Using PHP to update a database « PHP Code

  • Pingback: Using PHP to update a database « PHP Tutorials

  • Colin

    There is an error on line 11 and after a few hours i would like someone else help please :)

  • Colin
  • Muhammad Akseer

    It is vert helpful website for problem solving
    thanks,

  • mehmet

    anyone can help me to insert data in tables from different forms to different tables with same id?

  • rafael

    Nice tutorial!
    really helped me!!
    thanks a lot!!

  • http://www.owtravels.com RickyG

    I was trying to insert data from a form but it is not inserting the entry to the database.

    Here’s the code

    $Tours = $_POST['Tours'];
    if (is_array($Tours)) {
    foreach ($Tours as $key=>$val);
    $content = $content . count($Tours);
    for ($i=0;$i<count($Tours);$i++) {
    $content = $content . "$Tours[$i]\n";
    }

    }

    I made Tours a set with 4 selections but the entry is just blank. When i changed the type of Tours into a varchar, the word array is in the database not the selections made from the form.

    I use the code above to display the selection and there's a number which appears before the selections like below. How do i get rid of the number?

    4FirstChoice SecondChoice ThirdChoice FourthChoice

  • Pingback: PHP Code » Blog Archive » Using PHP to update a database

  • Pingback: Using PHP to update a database – Tutorials

  • rose

    hello

    i have a student regstration in groupes
    i want to ensure if that student who write his information to insert is already exist in any groupe or not
    if he exist display a form of the groupes to change his groupe to any group he wants

    i need your help plz

  • Suchi

    hi i did a form with select, which need to choose multiple options, but when i connect the php code to database the selected options were not been displayed…. the column itself is not accepted whereas othr fields get submitted. kindly help me to insert datas into database for php using tag, multiple options.I am a beginner.

  • Suchi

    hi i did a form with select tag, which need to choose multiple options, but when i connect the php code to database the selected options were not been displayed…. the column itself is not accepted whereas othr fields get submitted. kindly help me to insert datas into database for php using tag, multiple options.I am a beginner.

  • Irtesam

    v nice posts…

    its really helpful

  • http://www.anotherdailydeal.com jcalvin

    Hey, John.

    I followed your tutorial, and everything was perfect, however, after clicking submit nothing appears in mySQL database. A new row appears as though their SHOULD be the data there, but the tables cells are empty.. WHAAAAATTTT could possibly be making me want to vomit??? haha.. help me out, man..

    heres my source:


  • http://www.anotherdailydeal.com jcalvin

    actually, heres my source:


  • nood

    there is a bug in your code.. i find it unprofessional.. because after i reload the page after submitting the form, the page seems to re-enter the same data into my database.. can u give me a solution? without involving session token? Thank you.

    • http://www.johnathanward.com John Ward

      This is sample code for beginners and should not be used in production. We do not use any session tokens. You can check for referral that would stop the page on reload, but since you are such a professional you can figure that one out ;)

  • Kazmi

    line 8 : mysql_connect (“localhost”, “admin”,”admin321”) or die (‘I cannot connect to the database because: ‘ . mysql_error());

    ERROR: Parse error: syntax error, unexpected T_STRING in /home/onlinedo/public_html/DBUpdate.php on line 8

    Can anyone please figure out what that error points to.

    Thanks in advance.

  • tech7

    Hey, Thanks for this tutorial, it is just exactly what I needed. That doesn’t happen often. Thanks a lot!!!!

  • http://www.theinfostrides.com Adewale

    Thank you for the guidelines above. It is indeed helpful.

  • http://www.munchfest.org.uk Richard

    Hello. I am a noob with mySQL and PHP really and have found you tutorials extremely helpful.
    However, i am having trouble with the update. I have checked and double checked the form and the update files and they all seem to be ok, and i am recieving an error message (Error updating database) but it doesn’t add any information to the database at all. I was wondering if there was anything basic i may have overlooked?
    Thank you for your time.

  • http://null Victor

    thanks for all the high light in this page, plz i need a little favor in here.

    i designed a website that has different forms in it, like the contact page, booking page, make reservation page.

    i just only want to know if it requries creating different data base for all?

  • Halim

    when i run the script, this error appear

    “Error updating database”.How can i trace what type of error?

    • Juan

      If you look at the part that talks about $query, it says:
      mysql_query($query) or die(“Error updating database”);
      That means ‘run the variable query, and if it doesn’t go well show the text Error updating database’. Therefore, your problem is with the database.

      • Juan

        Sorry, I meant your problem is with the $query variable. Oops.

  • http://arpan14.0fees.net Cyberster

    thank you very much ! @John Ward

  • Rics

    Hi, I have just started learning PHP and MYSQL.
    created three comoboxes using createdays(), createyear(), createmoths() functions in PHP. It placed the combos well on the page. Now, how do I transfer the values selected by the user in dateofbirth field of MySql table.

  • Rics

    This is the part of code i have used:

    Day
    Month
    Year

  • Rics

    Oops!!! I pasted the code here, and where has it vanished? But it is showing the required thing on my page.

  • Rics

    The code is here…..
    <?php

    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 ***/
    $select = '’;
    foreach( $r as $year )
    {
    $select .= “$year\n”;
    }
    $select .= ”;
    return $select;
    }

    function createMonths($id=’month_select’, $selected=null)
    {
    /*** array of months ***/
    $months = array(
    1=>’January’,
    2=>’February’,
    3=>’March’,
    4=>’April’,
    5=>’May’,
    6=>’June’,
    7=>’July’,
    8=>’August’,
    9=>’September’,
    10=>’October’,
    11=>’November’,
    12=>’December’);

    /*** current month ***/
    $selected = is_null($selected) ? date(‘m’) : $selected;

    $select = ”.”\n”;
    foreach($months as $key=>$mon)
    {
    $select .= “$mon\n”;
    }
    $select .= ”;
    return $select;
    }

    function createDays($id=’day_select’, $selected=null)
    {
    /*** range of days ***/
    $r = range(1, 31);

    /*** current day ***/
    $selected = is_null($selected) ? date(‘d’) : $selected;

    $select = “\n”;
    foreach ($r as $day)
    {
    $select .= “$day\n”;
    }
    $select .= ”;
    return $select;
    }

    ?>

    DayMonthYear

  • http://none tom

    LOOK ELSEWHERE THIS TUTORIAL WILL JUST WASTE YOUR TIME.

    well another nice try but the update.php and form.php do not work at all. I get a blank page after submission, no error and records are not updated, or inserted. I just wasted two hours of my life coping your code from pictures none the less for failure. you sould at least have made the code so it could be copy and pasted so i would have only wasted 2 minutes, not two hours.

    • frank

      If you learnt to communicate without spelling and grammar errors while you were wasting time at school, perhaps you would have less problems with your scripts. Stop blaming others for your own obvious inadequacies.
      Keep on wasting!

      • Kevin

        I think it works perfectly well try checking if your values are being stored in the variables or may be the submit button is sending the data to the correct PHP page
        or there would be some error in your code I was getting the blank page as well
        but after this tutorial the values were being dtored in the database

  • http://blog.seo-mart.com Alam

    Clarify explanation thanks for sharing

  • Juan

    I don’t see a need to make the ‘NULL’ part for the ID, because with every new entry to the db, the ID field is incremented by one regardless if the NULL is there or not.
    Also, instead of making the query variable, you could just do:
    mysql_query(“INSERT INTO TestTable (ID, FName, LName, PHON)VALUES (“$FName”, “$LName”, “$PHON”)”);

    I’ve used it before with that kind of code [more of less], and it still functioned well.

  • http://www.seointexas.com jerrylee

    I am able to insert into mysql okay, and I am able to email form results okay, but how do I do both when someone inserts their info. For instance, I have a client who I put a form on their site, they want to store the info, but also be alerted with an email when it comes in. I know this is simple, but being self taught, sometimes we miss the most simple things.

  • Kevin

    This tutorial was really usefull for me Thanks a lot, I really need it

  • Jatinder Singh

    Thank you so Much , gr8 work

  • http://teamtutorials.com shoun

    I have a query regarding license manager. I am developing site, in there when user fill payment form i want to give(send) license certificate imediatly through php code. can any one help me with example?

    Thanks.
    Shoun

  • mohammed

    i want you to tell me how to write equation into mysql code for example:
    $query=”INSERT INTO r2m_tickets (TicketID, FirstName, LastName, DateTicketBought, Location, Events, Arena)VALUES (‘”.$TicketID.”‘, ‘”.$FirstName.”‘, ‘”.$LastName.”‘, ‘”.$DateTicketBought.”‘, ‘”.$Location.”‘, ‘”.$Events.”‘, ‘”.$Arena.”‘)”;
    in the above code if i have field “total salary” calculated from many field how can i add this equation field?

  • Dave

    Hi I am fairly new to MySQL and Php, I would be greatful if you could advise as to why the following is not working.

    I have my form named dataentryform.php, this form is made up of textfields and List/Menu fields, action is dataentryform.php.

    My connect file is working fine

    However my write to dbase script is not, could you point out where I have gone wrong please, script as below.

    Thanks for any help.

  • Dave
  • Dave

    It will not lt me post my script

  • http://n/a kdkd

    Way to go idiot! Publish your tutorial using images, so we can’t copy/paste the code. Then we can all make mistakes with simple character omissions and never figure it out. What a wasted of time.

    • http://www.johnathanward.com John Ward

      I apologize for providing you with free help… Just so you know the newer tutorials have the source code available.

    • Bugsy

      PLEASE! You snivelling whiner. It’s a-holes like you who deter people from actually trying to help…like John said….YOU’RE GETTING FREE HELP!!!
      If you’re so lazy that you can’t type in the code needed, then you need to go PAY someone to help you…otherwise sit down and shut up because you’re only ending up looking like an a-hole. If you run into a problem with the code, just ASK…eventually you’ll get the help you need.

  • Polo

    When clicking submit button it just show me the code in another page, why?!?!?!?!

  • Adrian

    I’m a student working on making a small application page, very basic, and I put this code in word for word in html, then made the separate file in php and uploaded both of them, when you click the ‘submit’ button I get this:

    “Page not found

    The page you requested was not found on this web server. This could be for a variety of reasons, including:
    You followed a broken or out-of-date link.
    You entered the URL for the page incorrectly.
    The page no longer exists.
    If you followed a broken link, please inform the owner of the referring page.
    If you have any queries about this error, please e-mail webmaster@this.domain.”

    I looked at my html tables and they are spot on and perfect, my php script is looking fine and I just can’t get it to work, help?

  • http://www.webtechplanet.in Narinder

    hello sir I am new to php. I tried you code to save data and its working only there is one problem that in my database it automatically add blank row without pressing submit button. So please tell me how stop adding rows in runtime in Mysql.

    • Cain

      Did you get this sorted?

      I am having the same problem.

  • http://www.peterod.co.uk Peter

    Hi. Done the above, whats next in the series?? Very good tutorials

  • http://www.wvector.com David

    Great tutorial, thank for sharing

  • RayChuks

    That’s a nice one John, thanks a lot.

  • http://www.jmbalpha.com Wilfred Cooray

    I get error message in my update.php as follows

    Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/jmbecoo4/public_html/testmysql/update.php on line 10

    Can you help me please.

    My program is as follows.

    Table editing

    • jerimy

      declare a variable first!

      • jerimy

        sir im just kidding!
        do you know how to connect database in my php files.
        our project seems like a networking site.
        users that register in my site need to appear in my database.
        can you help me sir!
        im a first year colle?e (bachelor of science in computer science)

  • vijay

    hi im also face with the wilfred’s problem
    this is my code

    in my form i have create like this for example temperature

    and this is the my php code ,it says syntax error in $query section

  • RAHUL

    i get this error PLEASE HELP !!!
    Parse error: parse error, expecting `’,” or `’;” in C:\wamp\www\update.php on line 8

    and here is my code:

    • RAHUL

      $query=”INSERT INTO testtable (FName, LName, PHON)VALUES (‘”.$FName.”‘,’”.$LNAme.”””.$PHON.”‘)”;
      echo “Database Updated with: ” .Fname.” “.LName.” “.$PHON ;

  • jerimy

    is there somebody can help me how to connect php in my database using wamp server?
    im such a freshmen in this industry!
    pls help me i need it for my final examination!

  • mohan

    how can i fetch the values of mysql database and dump into checkbox field and which ever field are checked and then those values has to dump into another table. Can anyone please let me know, how this is possible.

  • http://nothave Ram

    I wont ot ask how can i create table in my database….can u help me

  • Abdul

    I have a dynamic table which created from database… i have check box in this table, now i want to insert values into database from this dynamic table where check box is checked… please help… as soon s possible.

  • Jeganathan

    I searched more then 100 pages. But this is the best one.
    Thank u.

  • Jeganathan

    <?php

    $Uname = $_POST['Uname'];
    $mail = $_POST['mail'];
    $Uploaded_file = $_POST['Uploaded_file'];

    $con = mysql_connect("localhost","root");

    mysql_select_db("jegan_db", $con);

    $query = "INSERT INTO Persons (ID, Uname, mail, Uploaded_file) VALUES ('NULL', '".$Uname."', '".$mail."', '".$Uploaded_file."')";
    mysql_query($query) or die ('Error updating database');

    echo $Uname;
    echo "”;
    echo $mail;
    echo “”;
    echo $Uploaded_file;

    mysql_close($con);

    ?>

    My First Project in PHP

    PHP MySQL

    Name :
    Email :
    Attachements:

    Plz tel whats my error in insert command..

    • Beraki

      after every echo comand
      like
      echo “blahblah”;

      thats all I can see

  • http://www.logicsoice.com prabhat

    sgfsdgfgg

    • http://www.johnathanward.com John Ward

      I totally agree with you

  • http://clubazucar.co.uk Alvaro

    When I press submit i just get this from my php file:

    >?php $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $contactnumber = $_POST['contactnumber']; $email = $_POST['email']; $booking = $_POST['booking']; mysql_connect (“localhost”,”******”,”*******”) or die (‘Error: ‘ . mysql_error()); mysql_select_db(“clubaz_azucar”); $query=”INSERT INTO bookings (id, firstname, lastname, contactnumber, email, booking) VALUES (‘NULL’,’”.firstname.”‘,’”.lastname.”,’”.contactnumber.”‘,’”.email.”‘,’”.booking.”‘)”; mysql_query($query) or die (‘Error updating database’); echo “Database Update With: “.$firstname. ” “.$lastname.” “.$contactnumber.” “.$email.” “.$booking. ; ?>

    and nothing is update in mysql database

    My code is:
    >?php

    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $contactnumber = $_POST['contactnumber'];
    $email = $_POST['email'];
    $booking = $_POST['booking'];

    mysql_connect (“localhost”,”clubaz”,”ginu1964″) or die (‘Error: ‘ . mysql_error());
    mysql_select_db(“clubaz_azucar”);

    $query=”INSERT INTO bookings (id, firstname, lastname, contactnumber, email, booking) VALUES (‘NULL’,’”.firstname.”‘,’”.lastname.”,’”.contactnumber.”‘,’”.email.”‘,’”.booking.”‘)”;

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

    echo “Database Update With: “.$firstname. ” “.$lastname.” “.$contactnumber.” “.$email.” “.$booking. ;

    ?>
    SOMEBODY CAN HELP ME? I DON’T KNOW WHAT I DOING WRONG…thanks

    • http://none morz

      try to removed the “id” in your query,, also the ‘NULL’ at the values,,,

  • phil

    First the code work great thank for the great tutorial.

    I want to use it to store serial number and other information, could you please write a tutorial to check the database for duplicate for storing to database.

    Thank

    • raju

       hi i am raju

      my problem s ,i get input as date in seperately means month day year get individually.but i dont know how to insert this three input(year,month,date) to one field in database.plz tell code to help me .(my email id:grajtheking@gmail.com)

  • gowtham

    really thanks it helped me alot

  • http://none morz

    anyone can help me with my database?

    when i’m going to add data, no error found it is successful but no data entered to my database,

    here’s my html and php code..

    Add Bank Account
    NOTE: Fields marked with asterisk (*) are required.

    *Bank Name:

    *Bank Account Number:

    *Bank Account Code:

    Month of Bank Account Created:

    JANUARY
    FEBRUARY
    MARCH
    APRIL
    MAY
    JUNE
    JULY
    AUGUST
    SEPTEMBER
    OCTOBER
    NOVEMBER
    DECEMBER

     
     

    /////////////////////////////////////////////////////
    <?php
    require_once("../connection.php");

    if(isset($_POST['addbank']))
    {
    $bankname = $_POST['bankname'];
    $bankaccountnumber = $_POST['bankaccountnumber'];
    $bankaccountcode = $_POST['bankaccountcode'];
    $date = $_POST['bankdate'];

    if($bankname=="" or $bankaccountnumber=="" or $bankaccountcode=="")
    {
    $output = "

    Error: Please fill out all required fields.

    “;
    echo $output;

    } else {

    $sql = mysql_query(”
    INSERT INTO bank(bank_name,bank_account_code,bank_account_number,bank_date)
    VALUES(‘$bankname’,’$bankaccountcode’,’$bankaccountnumber’,’$date’)”);

    $output = ”

    Successful:Account successfully added.
    Add another Bank Account?

    “;

    echo $output;

    }
    }

    ?>

    /////////////////////////////////////////////////
    my datadase:

    tablename: bank
    fieldname: id,bank_name,bank_account_number,bank_account_code,bank_date
    /////////////////////////////////////////////////////

    anyone could help me?

    • http://www.johnathanward.com John Ward

      No error but the data is not being inserted? I have seen a weird issue when I was using php myadmin where I couldn’t insert data before I inserted a row using phpmyadmin. Maybe try that. I can’t explain the logic behind it though.

      • http://none morz

        tnx JOHN,,,
        i’ve found no errors in my project…

  • matt

    Thank you! I have a little HTML experience, but not with building forms/PHP. This is exactly what I needed.

    • http://none morz

      i will teach you php forms…
      create an html forms and insert php tags..
      look like this.. —->

      <form action="” method=”post”>

      ——————————————————–

  • http://none morz

    <?php
    require_once("../connection.php");

    if(isset($_POST['addbranch']))
    {
    $branchname = $_POST['branchname'];
    $branchstatus = $_POST['branchstatus'];
    $branchcode = $_POST['branchcode'];
    $date = $_POST['branchdate'];

    if($branchname=="" or $branchstatus=="" or $branchcode=="" or $date=="")
    {
    $output = "

    Error: Please fill out all required fields.

    “;

    echo $output;
    } else {

    $sql = mysql_query (”
    INSERT INTO branch ( branch_name,branch_status,branch_code,branch_date )
    VALUES ( ‘$branchname’,’$branchstatus’,’$branchcode’,’$date’ )
    “);

    /* $sql2=”select * from branch”;*/

    $output = ”

    Successful:Branch successfully added.
    Add another Branch?

    “;
    echo $output;

    }
    }

    ?>

  • oscardy baba

    help me out!!!!!
    <?php include("dbconnect.php");
    $connect=mysql_pconnect($host,$user,$password) or die (include ("error.php"));
    mysql_select($data_base) or die ('cannot select data base'.mysql_error());
    $name_1=addaslashes($name);
    $phone_1=addaslashes($phone);
    $query="INSERT INTO medisam (name,phone) VALUES ('".$name."','".$phone."')";
    $result=mysql_query($query) or die (include ("error.php"));
    …………………………………..
    i used the code above and is not working.

    • http://www.johnathanward.com John Ward

      Do you get an error message?

  • Cain

    I tried you code to save data and its working only there is one problem that in my database it automatically add blank row without pressing submit button.

    How do I stop the code adding blank rows without a user hitting the submit button on my form.

  • Alex

    THIS DATABASE UPDATE WORKS!!! AND WILL SOLVE THE ISSUE OF NO RECORD BEING WRITTEN TO DB!!!
    NOT SURE WHY JOHNS DIDNT WORK FOR ME EITHER :s
    USE http://WWW.W3SCHOOLS.COM ASWELL (VERY HELPFUL)

    THANKS JOHN HELPED ME BIG TIME WITH MY UNI CW!!!! =] =]

  • Alex
  • Alex
  • Allen

    Thanks John,

    I struggled a bit with Syntax etc but it is working now :)

    , and ; and “. are all so important in the right places :))

    Thanks very much for this tutorial. Much Appreciated.

  • keith

    Does not work. I get:
    Parse error: syntax error, unexpected T_STRING in /var/www/eq/update.php on line 13

    But your other tutorial works. I was able to get a csv file of data into the table and dynamically display it. It’s this updating part that I cannot get.

  • wfjanjua

    Helpful. Very Easy.
    Thanks John

  • chazykate

    hi there… may i ask how to get the values from a single column of the database, i am using postgres. I want to show the values into checkboxes. is it the same as the dropdown box?…dropdown can only select one vallue while i need to select multiple data from that column and insert multiple data to another table. My main problem for now is retrieving the data from the db where per checkbox value is equal to per column item. the data in that column is changeable in a way where if a user adds an item, it will automatically generate another checkbox. or is it that i could not apply checkboxes for this problem?

  • Haywood Jablowme

    I just fixed the code a little and this works for me. There was missing code at the end of the echo but im assuming php5 needs the extra piece at the end.

  • Haywood Jablowme

    sorry forgot to add code

    $FName = $_POST['FName'];
    $LName = $_POST['LName'];
    $PHON = $_POST['PHON'];

    // make connection
    mysql_connect (“localhost”, “greenbox_kevin”,”Casillas1″) or die (‘I cannot connect to the database because: ‘ . mysql_error());
    mysql_select_db (“greenbox_kcny”);

    $query=”INSERT INTO kcnytable (ID, FName, LName, PHON)VALUES (‘NULL’, ‘”.$FName.”‘, ‘”.$LName.”‘, ‘”.$PHON.”‘)”;
    mysql_query($query) or die (‘error updating database’);
    {
    echo “Database Updated With: “.$FName.” “.$LName.” “.$PHON.” “;}

  • http://www.emavens.com Pooja

    Really helpfull page. Please post these kinds of posts regularly. Thanks

    • Olaosebikan Abiodun

      I will say kudos for this post

  • medhat

    it agood

  • medhat

    it’s a good nice

  • medhat

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

  • http://yep method12

    In this line $query=INSERT INTO “TestTable

    what am i suppose to put instead of TestTable ?
    Thanks for ur time

  • http://www.kigalicement.webs.com NKURUNZIZA

    please.I want to insert the data in my table which has a similar field as the other table of my database both tables are in the same database so I want the code which will help me to check if the data entered is the equal/the same as the other which is in the other table.
    thanks

  • shiji

    hi,if i inputing data in selection type,how selected data insert into database..??
    Condition :
    USED
    REFURBISHED

    • http://www.johnathanward.com John Ward

      shiji, if you are using a select box the variable is still passed to the form the same way a text box is. Meaning on your option tag the name attribute will be the variable. This will contain whatever field is selected.

      • vinay kumar

        Dear Sir

        I have write the quote below and it is executed and i have one small problem i.e when i click on the submit button with out entering values in the data base it is showing 0 in the database. Please help me when i not entered data i want to close the db connection.

        function checkit(evt)
        {
        evt = (evt) ? evt : window.event
        var charCode = (evt.which) ? evt.which : evt.keyCode
        if (charCode > 31 && (charCode 57))
        {
        alert(“This field accepts numbers only.”);
        return false
        }
        }
        function chkpwd()
        {
        pwd=frm1.txtpwd.value;
        cpwd=frm1.txtcpwd.value;
        if(pwd!=cpwd)
        alert(“Mismatch Password, Please Enter Same Password”);
        }
        function chkmail(str)
        {
        err=false;
        var dot=”.”;
        var at=str.indexOf(“@”,at+1);
        if(at==-1)
        err=true;
        atat=str.indexOf(dot,at+3)
        if(dot==-1)
        err=true
        fc=str.charCodeAt(0)
        if(fc122)
        err=true
        lc=str.charCodeAt(str.length-1)
        if(lc122)
        err=true
        for(i=0;i<str.length;i++)
        {
        chr=str.charAt(i)
        if(chr=="" || chr== " " || chr== "/")
        err=true
        }
        if(err==true)
        alert("invalid email id");
        }
        function fun1()
        {
        if(frm1.txtsno.value=="" )
        {
        alert("Please Enter Values");
        }
        }
        function fun2()
        {
        if(frm1.txtuname.value=="" )
        {
        alert("Please Enter Values");
        }
        }
        function fun3()
        {
        if(frm1.txtpwd.value=="" )
        {
        alert("Please Enter Values");
        }
        }
        function fun4()
        {
        if(frm1.txtemail.value=="" )
        {
        alert("Please Enter Values");
        }
        }
        function fun6()
        {
        if(frm1.txtsno.value=="" || frm1.txtuname.value=="" || frm1.txtpwd.value=="" || frm1.txtcpwd.value=="" || frm1.txtemail.value=="")
        {
        alert("Textboxes Not Empty");
        }
        }

        Registration Form

        S.No
        Username
        Password
        Confirm Password
        Email-Id

        please help me, Thanks in advance Vinay

  • Tiffney

    John,
    this is my code and I am getting an error on the closing ?> could you help me

  • Tiffney

    well I guess I cant publish it but please email me about the situation I really need help

    • http://www.johnathanward.com John Ward

      Hello, If you are trying to paste code try changing your opening < to &lt; this should allow you to post snippets. I really need to add that ability to these comments.

  • Hitesh Patel

    Help ME…When I am Display a Value in Label from Database..than when I am Click on Insert Button Than This Label Value is insert into a Databse Permanently stored ..So This Operation is Not Working Properly..So Send Me a Code Of this Operation…..PLEASE Sir..

  • Hitesh Patel

    Help ME…When I am Display a Value in Label from Database..than when I am Click on Insert Button Than This Label Value is insert into a Databse Permanently stored ..So This Operation is Not Working Properly..So Send Me a Code Of this Operation…..PLEASE Sir..

    • http://www.johnathanward.com John Ward

      I don’t understand what the problem you are having is.

  • Vimal

    hello, i keep getting this error….

    Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in C:\xampp\htdocs\website\update.php on line 11

    line 11 is:

    $query=”INSERT INTO property (idProperty, propertyName, propertyType, propertyDescription, propertyPrice, roomsAvailable) VALUES (‘”.$propid”‘, ‘”.$propname”‘, ‘”.$proptype”‘, ‘”.$propdescri”‘, ‘”.$propprice”‘, ‘”.$propavail”‘)”;

    what am i doing wrong? :S
    any help would be really appriciated.

    • http://www.johnathanward.com John Ward

      Actually if you are using magic quotes (” “) around your query you can insert the variables without breaking out of quotes like this:

      $query=”INSERT INTO property (idProperty, propertyName, propertyType, propertyDescription, propertyPrice, roomsAvailable) VALUES (‘$propid’, ‘$propname’, ‘$proptype’, ‘$propdescri’, ‘$propprice’, ‘$propavail’)”;

      the problem you are having is that you are breaking the quotes, but not using another period (.) after your variables. For examples if you wanted to break quotes and add a variable you need to do this: $query =”insert into table values(‘”.$myvar.”‘) “;

      Magic quotes are easier in my opinions, but keep in mind this is example is not secure. Meaning if someone was to pass malicious code to your variables you could end up losing a lot of data. To protect against SQL injections please look into using something like PDO to do database update. This is meant to give you are good starting point to understand how to use PHP with a database.

  • Vimal

    sorry…i’ve figured it out.

    excellent script tho..its been alot of help :)

    thanks

  • Vimal

    John thanks mate….i just saw your reply!

  • Vimal

    John, this is totally of what above is about…but i was wondering if you could help…im trying to delete a property from my database which you can select from a dropbox…but it just doesnt come up with any properties in my box and i dont know what im doing wrong? again any help would be greatly appriciated…ill paste both files.

    thanks in advance!

    ———————removeprop.php form—————

     
    Select Property:

     

    <option value="”>

     

    ————————————-removeproperty.php—————–

    <?php
    require ("mysql_connect.php");

    //check if submit button was pressed
    //if($_GET['propertyname']){
    //}

    //to protect from mysql injections
    $remove=mysql_real_escape_string($_GET['propertyname']);
    $remove = stripslashes($remove);

    $sql = "DELETE FROM property WHERE propertyName=$remove";

    //declare in the sql variable
    $result = mysql_query($sql); //order executes
    if($result){
    echo("Property Deleted”);
    }
    else{
    echo(“Failed to delete Property”);
    }
    ?>

  • Vimal

    —–removeprop.php which is the form which displays the drop box.————————–

     
    Select Property:

     

    <option value="”>

     

  • http://sdafljk AHMAD

    YOUR CODE ENTERS BLANK INTO DATABASE AS WELL……. IF I PRESS SUBMIT AND DO NOT FILL OUT ALL FIELDS IT STILL ENTERS BLANK IN DATABASE.

  • Jorgen

    Hi, I followed your tutorial. It was very easy to follow, but.. When i executed the first test to insert something into my database, i got an error:

    “Server Error

    An error have occured when the website should recive …/movie_list/insert.php. It could be shutdown or down for maintainence or could be wrong configurated”

    (its a rough translation from my language, but should give you an idea…)

    Thanks in advance,
    Jörgen

  • santy

    Hey ya wazz up everybody ???
    Umm… nice site

  • floris

    Hi
    i am using an ODBC connection and table insertion is not done but brings the error. any help there
    the code i use:
    $sqlQuery = “INSERT INTO prodlist($code, $name, $desc, $price) VALUES ( ‘” . $code . “‘, ‘” . $name . “‘, ‘” . $desc . “‘, ‘” . $price . “‘) “;

    $dbResult = odbc_exec($dbConn,$sqlQuery) or die(“Error, Product update failed …. use the browsers BACK button”);
    echo “database updated with:” . $code . ” ” . $name . ” ” . $desc . ” ” . $price;

    any help pls someone

  • ExHeart

    Hye, really great tutorial.. but do u have a tutorial inserting radio button data to the database? can u give me the link? thx =)

  • http://www.google.com sumit

    hi dear

  • kmkmahesh

    i just want to add more records at a single time

    i mean i use name, phone no, email input fields

    i just want a button “Add another” which has to add one more set of all input fields

    plz help me abt this i am waiting for the solution

    plz provide code also i am beginner to programming

    Thnx in advance

  • Ranjeet Singh

    your tutorial is very helpful for me. thanx

  • http://- noobie

    Question:

    How do I insert a very simple value from drop down list into my sql table? I have done it with text fields (input type=text). Here’s the code:

    Movie title:
    <input type="text" name="Title" size="15" maxlength="15" value="”> 

    Production Year:
    <input type="text" name="Year" size="15" maxlength="4" value="”>

    Runtime (mins.):
    <input type="text" name="PlayTime" size="15" maxlength="4" value="”> 

    Genre:
    <input type="text" name="Genre" size="15" maxlength="15" value="”> 

    Disc format:
    <input type="text" name="DiscFormat" size="15" maxlength="15" value="”> 

    <option value="”>DVD”
    <option value="”>BlueRay
    <option value="”>DVD/BlueRay

  • http://- noobie

    Question: How to insert very simple value from drop down list to sql table?

    Movie title:
    <input type="text" name="Title" size="15" maxlength="15" value="”> 

    Production Year:
    <input type="text" name="Year" size="15" maxlength="4" value="”>

    Runtime (mins.):
    <input type="text" name="PlayTime" size="15" maxlength="4" value="”> 

    Genre:
    <input type="text" name="Genre" size="15" maxlength="15" value="”> 

    Disc format:
    <input type="text" name="DiscFormat" size="15" maxlength="15" value="”> 

    <option value="”>DVD”
    <option value="”>BlueRay
    <option value="”>DVD/BlueRay

    • http://www.jesleepitajen.webs.com JESLEE

      Birthday:
      Month:Jan
      Feb
      Mar
      Apr
      May
      Jun
      Jul
      Aug
      Sep
      Oct
      Nov
      Dec

  • http://www.sysmic.co.in Jasvinder

    Hi Team,
    I am new with PHP and still trying to master it.
    I have a few projects if interested please do contact me at jasvinder27@yahoo.com

  • http://www.yahoo.com Shawn

    This code sample and tutorial does not work. Don’t waste your time with it.

  • kruthika

    hi
    i want to insert a multiple checkboxs,radio button & textbox in my datatable .am totally new to mysql some body plz help me
    am thinking i got for checkbox plz clarify it
    create table mode (a1 tinyint(1),a2 tinyint(1),a3 tinyint(1));

    thank you inadvance

  • http://www.upi50097.com Nurmohammad

    Dear All Programmar

    Please help me for some command Use Bye PHP and SQL or PhpMyAdmin
    I want one Table from all rows call whene i search
    My command now use
    case “Inbox”:
    $Maddress=$_POST['Maddress'];
    $bodyPanText=array(“$Maddress”);
    $SQL=”select * from massage_upi where maddress=’$Maddress’ “;
    $result=mysql_query($SQL,$con);
    if($result):

    if (mysql_num_rows):
    $bodyPanText=array(“massage/massage_show.php”);

    else:
    $bodyPanText=array(
    “Invalid user ID ; Push Carret ID”,
    “”,”id_from.inc.tpl.php”);
    endif;

    else:
    $bodyPanText=array(“Fail to execute query :”.mysql_error($con));;

    endif;
    break;
    But when use this command this time show one rows and one information
    i want when search this time all information show this table

    Please Help me

    With Thanks
    Nurmohammad

  • Dale

    Hi John,

    A client has asked that I gather the information from his contact form and save it in a database. Your tutorial gives me a good start on posting the info to the database, but how do I get the comments from the contact form sent to the client’s email as well?

    Simply put, I want to gather the data and still send the email.

    Thanks,
    ~Dale

    • dinesh nemiwal

      hi jhon what going on

      • dinesh nemiwal

        hi

  • dinesh nemiwal

    thanks now i have to test it

  • sunny

    hii, i am trying to insert data in databse using php but
    i cann’t be successful yet, it only print a ERROR message, please help me. my code are

    “text.html”

    Untitled Document

    Enter the details

    First Name
    Fathers name
    City

    “text.php”

    Untitled Document

    please sir reply me that what are the error in my code, i m waiting for your answer.

  • Plam

    Hi John and all the coders and newbies here,
    i would like to know if this form could enter also together with the text, a blob entry (picture). Did someone try it? And should the “enctype” attribute of the form be changed in this case.

  • nithya

    sir,i want to retrieve the data from mysql by getting the value(by variable) from the user instead of giving the value in code.

  • ali

    I am having problem in inserting data .. php show successful enty but when i go to mysql phpmyadmin ..there is no data inserted … any one can tell the problem? i have recently installed ODBC plugin for mysql

  • DJ

    Enter Name
    Enter address
    Enter number
    add to database

    my code isnt working…der is a error showing undefined variable name, address & number..
    i tried directly putting $_POST['name'] in d values field..

    • Malti yadav

      you shoud declare the variable before using that variable.
      May be your proble solve
      i.e

      like thaat

  • newrocker

    thank u my dear…..

  • Rachel

    Hey John, I have been using your tutorials over the last few days. Thank you so much, they are so helpful. However, I have now gotten everything working and rather than echoing the fields entered once the user presses submit, I would like to redirect to another page. Is there a quick fix to do this or another tutorial you could send me to? I would really appreciate it. Thanks for all your help :)

  • Tom

    My host’s server is running php 5.2.16, apache 2.2.17, and mysql 5.0.92-community. I keep getting an error….gone over it too many times….changed things…tried sooo many things I found on a bunch of sites to try to help. I am new, so it’s prob an easy error….I just want it to work!!!! Here is mu code:

    <?php

    $host="localhost";
    $username="username";
    $password="password";
    $db_name="database";
    $tbl_name="table";

    mysql_connect("$host", "$username", "$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $jobID = $_POST['jobID'];
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $serial = $_POST['serial'];
    $mfrDate = $_POST['mfrDate'];
    $hdmi = $_POST['hdmi'];
    $sealed = $_POST['sealed'];
    $origDriveType = $_POST['origDriveType'];
    $driveKey = $_POST['driveKey'];
    $keyFileLink = $_POST['keyFileLink'];
    $jobType = $_POST['jobType'];
    $dropOffDate = $_POST['dropOffDate'];
    $completionDate = $_POST['completionDate'];
    $pickUpDate = $_POST['pickUpDate'];
    $charge = $_POST['charge'];
    $comments = $_POST['comments'];

    $sql="INSERT INTO $tbl_name (jobID, name, phone, email, serial mfrDate, hdmi, sealed, origDriveType, driveKey, keyFileLink, jobType, dropOffDate, completionDate, pickUpDate, charge, comments) VALUES ('$jobID', '$name', '$phone', '$email', '$serial', '$mfrDate', '$hdmi', '$sealed', '$origDriveType', '$driveKey', '$keyFileLink', '$jobType', 'dropOffDate', '$completionDate', '$PickUpDate', '$charge', '$comments')";
    $result=mysql_query($sql);

    if($result){
    echo "The database has been updated";
    echo "”;
    echo “Back to main page“;
    }

    else {
    echo “ERROR”;
    }

    mysql_close();
    ?>

    of course in the real code I have my username, password etc in it. Any help is appreciated.

  • http://noun Hasnain

    i am using this code but i have erroy
    tell me what is problam?
    in my browsere:
    Error update database

  • http://www.swin.edu.au/hosting/hairhousewarehouse/forum/profile.php?id=8709 Gwyneth Furlow

    Helpful information. Fortunate me I discovered your site accidentally, and I am shocked why this twist of fate didn’t took place in advance! I bookmarked it.

  • http://Website neha

    i like
    very usefull in my page

  • http://Website madiha

    hey..

    have installed xampp for database apache is running..but when i gonna click on apache admin..
    then here is the error on ma browser. Couldnt view even the xampp frst page to get started or login..
    plzz any one tht can help..!!!

  • http://Website madiha

    Server error!

    The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script.

    If you think this is a server error, please contact the webmaster.
    Error 500
    localhost
    8/16/2011 11:34:34 AM
    Apache/2.2.17 (Win32) mod_ssl/2.2.17 OpenSSL/0.9.8o PHP/5.3.4 mod_perl/2.0.4 Perl/v5.10.1

  • http://Website CoopNET

    simple, but great stuff! thx

  • http://Website vinod

    this post is only for inserting new values not for updating existing data..existing data will b updated using “update table_name set…… “

  • http://Website MIke

    I’d be remiss if I didn’t offer a personal thank you for this. I got mine working.

  • http://n/a i’mHere
  • http://hi Suraj paul

    Really it’s easy n basic code thnx I enjoyed by using dis code.

  • http://www.pstsnshah.orfree.com shabir

    plz help me to retriev data in brozer correct my following code.
    <?php
    include 'connection.php';

    $v_name=$_POST['name'];
    $v_email=$_POST['email'];
    $v_cellph=$_POST['cellph'];
    $v_address=$_POST['address'];
    $v_msg=$_POST['msg'];

    $sql="select name,email,cellph,address,msg from pst";
    $stmt=mysql_query($sql)
    echo "”;
    echo “”;
    echo”name”;
    echo”email”;
    echo”cellph”;
    echo”address”;
    echo”msg”;
    echo””;
    $n=0;
    while($res=mysql_fetch_array($stmt))
    {
    $n++;
    echo “”;
    echo “$res[0]“;
    echo “$res[1]“;
    echo “$res[2]“;
    echo “$res[3]“;
    echo “$res[4]“;
    echo “”;
    }
    echo “$ressql[0]“;
    if ($ressql[0]!=0)
    {
    echo “ID Already Exists”;
    }
    else
    {
    $sql=”INSERT INTO pst(name,email,cellph,address,msg)
    values(‘$v_name’,’$v_email’,’$v_cellph’,’$v_address’,’$v_msg’)”;
    mysql_query($sql)
    }
    echo””;
    echo “”;

    ?>

  • http://krules.net Kenneth

    Wow Great.. thank you..

  • http://Website simon

    Thanks man, this tutorial really helped. i have no IT background but i was able to create and connect to a database and add records. Thanks man

  • http://nowebsite Dinesh

    Material and discussion above is very fruitful. I am new in web site development. Can you guide me about initial steps and how to start writing code and what is the platform to writing code.

    • http://waqasuow.hostzi.com waqas ahmed qureshi

      hi danesh plz visit:
      these both are web tutorials
      tizag.com
      w3schools.com

      and i have devlop amy persnal website after learning frm both of these

      • Gadiano dina

        i agree with you waqas ahmed qureshi, w3schools.com is very helpful in all kind of programming languages. So explore and explore!

      • Mr Choclate222

        waqasuow.hostzi.com/project1

  • http://waqasuow.hostzi.com waqas ahmed qureshi

    any one of u guyz can send me cmplete code of inserting data run time into localhost database.
    using php and sql queries.
    plzzzzzzzzzzz its urgent.
    03328009279

    • http://techsparx.in/ sana
  • http://techsparx.in/ sana

    Thanks…
    Good one..

  • http://kaoskuliah.com/ Baharsan

    this very nice, complete, clear tutorial…thanks dude…

  • Muhammadusman Anwar

    it’s good.

  • Gardianodina

    Thank you a lot, it help me so much in making my own database.

  • lordzeref

    nice one :))

    really helps me with my assignment so basic and simple yet so good for starters..

  • LOLA

    THANK YOU SO MUCH! But how to check if a duplicate data? I mean, a data which has already been saved!

  • Toum_chivann

    I have feel so happy after looked this statement. And I think that this statement of this code will help another people if they want. finally I to say that thank you.

  • Craiglovelock

    Thanks for this, however this is inserting blank content into my database.

    The content in the form boxes does not get written to the database, any ideas?

  • Cristy

    Thank you so much…I’m very happy to following your tutorial.
    It’s vary helpful for me. Nice tutorial..Keep it up..! :)

  • Maliking143

    Thank you very much . This help me a lot .:))

  • appreciation

    Thank you for  simplifying php data insertion. Please keep up the good work.

  • Linkswapnil

    madhar code copy karna kyun nahi da raha hai

  • http://www.webdesignerdevelopers.com/ Web Designer Developers

     Good informative & helping one sharing thanks

  • IsaqSalawu

    Thanks, just what’s neeeded, Isaq, in sunny Dulwich London.

  • Kalvin Bernabe

    Hello every body :)  I nid help, what or how can I post or get a data of a radio button and a data of a list?
    im a newbie, pls reply. asap :D

    • Mr Choclate222

      code for a radio button.

      u can visit waqasuow.hostzi.com/project1

  • Mr Choclate222

    http://waqasuow.hostzi.com/project1.htm plz visit my site to get more help

  • Lydphiri

    i have followed what this page instructed,but everytime i press the update i keep getting a black web page and the database does not even get updated. please help

    admin.html

    Category Name:
    Description  :

    update.php

    <?php
    $cat_name =$_post['cat_name'];
    $cat_desc =$_post['cat_desc'];

    mysql_connect ("localhost","root","babez@123") or die ('Error :'.mysql_error());
    mysql_select_db("emusic");

    $query="INSERT INTO tbl_category(cat_id,cat_name,cat_description,cat_image) values('Null',' .$cat_name ',' .$cat_desc ','NULL')";

    mysql_query($query) or die ('Error, updating database');
    echo "Database Updated With: ".$cat_name .cat_desc";
    <?

    • Mr Choclate222

      its very simple if u are facing any kind of problem in updating ur database.
      u can visit easy and best tutorial at waqasuow.hostzi.com/project1

  • http://www.webdesignbizz.com/ Website Template

    Very nice article a useful one,Thanks for sharing this creative stuff here with us…

  • Miranda Ebert

    Amazing tutorials! These 3 work perfectly! To people maybe wondering about line 6 and 7 (in update.php), in the picture it simply ends on I, you can just change the line to end with:

    or die (“cannot connect”);

    so it doesn’t close down the following line. Enjoy!”

  • saad iqbal

    thats very usefull for me

  • Official Dumbass

    you have emancipated me from the official dumbass category with this tutorial. Thank you!

  • Basalirwadavidiana

    One of the biggest schools called city academy has an estimated pupils population of 4200,with an average number per class(s1,s2 etc)of 600.this means each class has about 6 streams each of 100 pupils(e.g. S1A,S1B,…,S1F).to maintain school standarda,individual pupil performance as well as class standards has to be tracked.this task can not be easily managed by a spreadsheet application but a database one.
    Required:
    1.put related information in same categories and of each category,create a table.
    2.use php/mysql to create them and save them on a disk in form of a database
    3.by use of forms or otherwise,show how you would capture data ,modify,remove unwanted data and produce simple reports
    4.discuss in details the difficulties you have or expected to encounter while designing and implementing the above project

    • waqas ahmed

      its so simple sir

  • Malik Khawar Abbas

    Hi Friend!
    Here is also a link that is related to the problem. It is step by step tutorial. easy and simple.
    http://developerqueries.blogspot.com/2012/03/php-form-tutorial-stored-client.html

  • http://www.facebook.com/gomezralf Ralph Veyra Gomez

    what will i do when it prints an “Error Updating Database” 
    what went wrong?? please respond :)

  • lauraine 2012

    I just searching this kind of things in search engines. My searching was ending here. Keep up your good work. I bookmarked it for general updates.
    html5 media player| youtube html5 player

  • http://www.facebook.com/josue.reyes Josué Reyes

    great great great… just great… it works and i find it very usefull…

    • jai

      hi reyes… a u programmer ?

  • Chris Tan

    this one is good ,but how about insert data in array ,still can use POST method ?

    • Mr Choclate222

      yes

  • http://www.facebook.com/profile.php?id=616100385 Right T’ Qureshi

    Parse error: syntax error, unexpected T_STRING in /public_html/kesc/update.php on line 13 

    • Mo

      I received the same error I changed line 13 to the following and it worked fine:

      echo (‘Database Updated’)

      I didn’t see the need to list all of the fields that updated, if the parser returned a successful update, that’s fine with me. I can always check the tables to ensure date populated the fields correctly. There is no ending semi-colon…hope this helped.

  • Pingback: sql update error using php

  • Pingback: sql update error using php | Jisku.com - Developers Network

  • Pingback: Arrays, Foreach, & Explode…Oh My!

  • http://www.facebook.com/yosua.a.wibisono Yosua Anjar Wibisono

    After I put on every script I do not appear on the program and the data that I add no empty … Can you explain the content or suggestions can be given

  • Pingback: Populating Multi-Select Boxes From Your DB Using an All-in-One Form

  • Pingback: Populating Multi-Select Boxes From Your DB Using an All-in-One PHP Form

  • Pingback: Populating Multi-Select Boxes From Your DB Using an All-in-One PHP Form | clio 3 blog

  • pls help me

    Parse error: syntax error, unexpected $end in /home/hostingu/public_html/update.php on line 15
    please help me with this, what is wrong with ?>

  • http://www.facebook.com/adamridley.com.au Adam Ridley

    what a dug gunt… why make it images?

  • Mahasish Shome

    High risk of MySQL Injection…

    • spyderman4g63

      Yeah sorry. This is really old and I’ve been meaning to update it.

  • hggggggggghhhhhhhhhhhhhhhhhhhh

    hhhhh