Inserting Data Into a MySQL Database using PHP
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”.

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.

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.

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.

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.

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.

Now to start coding a php file we always start with the open and close php tags.

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.

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.

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.

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.

Now you can test out the form.

When you submit the form you should see your results displayed.

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.

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
















on February 4th, 2008 at 1:29 am
Good post for those new to php/mysql. Glad to see regular posts after a long inactivity. Please continue posting regularly if not frequently.
on February 26th, 2008 at 2:30 am
That is a great help
on February 29th, 2008 at 4:21 am
Hello there.
Just found your site. Great job!
I like it much.
look here http://live.com
on February 29th, 2008 at 10:55 am
dasdasdasd
on March 11th, 2008 at 5:31 am
Hello
Just found your site. !
I like it and thanks .
on March 15th, 2008 at 1:32 am
I run the script and it echos it was updated but the table doesnt show any info was inserted, what could i have possibly one wrong?
on March 15th, 2008 at 5:09 am
Do you have any info in the table at all. For some reason if I do not enter the first row of data manually using php my admin, then the table will not update from the php file.
on March 15th, 2008 at 9:20 pm
i entered data myself through phpmyadmin and then tried to with the script and it did squat
on March 15th, 2008 at 10:19 pm
It’s hard to tell what could be happening. I would check the code one more time. It is strange that it is not throwing a MySQl error. Make sure the query is right.
on March 16th, 2008 at 8:27 pm
i checked it but i also found a friends script and its doing what i need but not exactly i need to code a script that pulls info from a database but can also put it in and yeah theres to much to explain in this lol, i just need to find someone to talk mono on mono on like a chat thing or something and see if they can help me
on March 17th, 2008 at 6:50 pm
Thank you very much for the training lesson above. It has come in handy close to a deadline.
on March 25th, 2008 at 2:32 pm
Thanks a lot….it clears my doubts
on March 31st, 2008 at 11:17 am
Thanx a lot!
I’ll be waiting for the next script, the one that will searching the database
on April 16th, 2008 at 11:45 pm
thank a lot…
it is very helpful for me to do assignment..
on April 27th, 2008 at 6:38 pm
I tried you’re code and no matter what i did it would not work
on May 5th, 2008 at 6:28 am
Hi!
I need to extract data from mysql by using php….and I want as a link; so user can click to see details of that link (more info)
can u give me a hand pls!!!!!
on May 17th, 2008 at 7:06 am
hello
Thanks for the tips, but why do firefox & ie both return this parse error:
“syntax error, unexpected ‘;’ in /home/gypsy/public_html/update.php on line 10″
? please help
on May 17th, 2008 at 9:30 am
ok dont worry, figured it out, I think I am on a slightly newer version of php or something, because changing my syntax slightly fixed the error.
instead of
echo “updated with: ” .variable. ;
I wrote
“updated with: “, variable ;
on May 24th, 2008 at 2:10 am
Thank you very much
on June 12th, 2008 at 1:58 am
hi
i want set a update and view buton
on June 16th, 2008 at 10:35 am
if you please help me! i am a student and i have web project
if i have a page in html with checkbox and i want to select one or more
pieces how can i write the php page to add the selected pieces to the invoice!
with my thanks
on June 17th, 2008 at 7:18 pm
@ sanae
There is an easy way to do this. I am going to do a tutorial on this that will post next week some time. For starters you would need to make all the checkboxes be in an array.
eg:
Box 1
Box 2
Box 3
You receiving file should then contain a for next loop that will take each box and if they were checked and if they were to run a query to enter them into the database like so:
foreach($cats as $key => $value) {
if ($value > 0) {
$sql = sprintf(”insert INTO value_table(row1,rrow2) VALUES(’%s’,'%s’);”,
$value, $old_no);
mysql_query($sql);
}
}
That should do what you need to do. Let us know if you have issues and thanks for the great tutorial idea.
on June 17th, 2008 at 7:22 pm
(HTML not allowed in comments) Here is what Box1, Box2, and Box3 should be.
input type=’checkbox’ name=’boxes[]‘ value=’1′ />Box 1
input type=’checkbox’ name=’boxes[]‘ value=’2′ />Box 2
input type=’checkbox’ name=’boxes[]‘ value=’3′ />Box 3
on June 27th, 2008 at 10:45 am
Nice tutorial, syntax highlight really helps in understanding the code
on June 28th, 2008 at 10:00 am
nice tutorial
on June 30th, 2008 at 10:01 am
I tried it and it did not update…not sure why.
I typed the exact thing you have
on June 30th, 2008 at 10:12 am
Here is my code:
when ran, it gives the error “error updating database”
Please help!!
html file
————–
Members Search
Enter Member Information:
ID:
First Name:
Last Name:
Phone Number:
Php file
————-
$fname = $_POST['FirstName'];
$lname = $_POST['LastName'];
$phone = $_POST['PhoneNumber'];
mysql_connect(”localhost”, “bookorama”, “bookorama123″) or die (’Error: no db connection ‘ . mysql_error());
mysql_select_db(”test”);
$query=”INSERT INTO members (id, firstname, lname, phone)VALUES (’NULL’, ‘”.$fname.”‘, ‘”.$lname.”‘, ‘”.$phone.”‘)”;
mysql_query($query) or die (’error updating database’);
echo “database was updated with: ” .$fname.” “.$lname.” “.$phone;
// close connection
mysql_close();
on June 30th, 2008 at 2:01 pm
@IJ
Can you give us the exact error message? That will make troubleshooting much easier.
on July 2nd, 2008 at 10:09 pm
@John
the error is :
error updating database
on July 16th, 2008 at 12:26 am
your way is the best way of teaching for people who need to learn faster.
on July 19th, 2008 at 6:45 am
hi!
when i submit the form a blank page appear and nothing is being updated in mysql database,where could i be wrong
thanx!
on July 23rd, 2008 at 3:57 am
tnx but i didnt get it
on July 28th, 2008 at 2:20 am
keep getting error database not updated, any suggestions?
Here’s my code, seems right?
on July 30th, 2008 at 5:49 am
Thanks for this simple article about inserting to database
on July 30th, 2008 at 6:46 am
Nice code.
It works very well.
on August 7th, 2008 at 1:16 am
a big help
on August 7th, 2008 at 12:03 pm
Great article, one more thing can u plz show me how to use a login form to get data from mysql…. would be of immense help….thanx yet again…!
on August 7th, 2008 at 1:32 pm
oh, oh?! it does not return Fname, but shows lname and PHON… deleted everything and started again from the very beginning still d same… please help me u can reply to my mail addy…
on August 8th, 2008 at 3:38 am
Where can i download the whole code?????
on August 14th, 2008 at 3:28 am
pliz guy, I wanted to register members but when I clicked at submit button it displays a blank page.my code is:
on August 31st, 2008 at 2:03 am
I am trying this out and getting a blank page too. My form is at:
http://www.tccnotary.com/newclients.php
Right now my script is only attempting to write the submitted order date (the first field) to the database. Once I know that works I can work on the other fields. My script, insert.php, is:
on August 31st, 2008 at 2:03 am
$orderDate = $_POST['orderDate'];
mysql_connect (”localhost”, “tcc”, “cameronTom”) or die (’Error: ‘ . mysql_error ());
mysql_select_db (”neworder”);
$query=”INSERT INTO clientsopennew (orderID, orderDate)VALUES (’NULL’,'”$orderDate.”‘)”;
mysql_query($query) or die (’Error updating database’);
echo “Database updated with: ” .$orderDate ;
on September 4th, 2008 at 2:43 am
Anyone? Anyone?
on September 9th, 2008 at 10:54 am
Can anyone help why this is not working. The database is not updated.
All help is more than welcome.
Thanks
$connectionID=mysql_connect(’localhost’,'test’,”);
$dbname=mysql_select_db(’testdb’);
if($action==”INS”)
{
$Poule1 = $_POST['Poule1'];
$Poule2 = $_POST['Poule2'];
$datumtijd = $_POST['datumtijd'];
$team = $_POST['team'];
$thuis = $_POST['thuis'];
$uit = $_POST['uit'];
$Locid = $_POST['Locid'];
$scheidsr1 = $_POST['scheidsr1'];
$scheidsr2 = $_POST['scheidsr2'];
$tafel = $_POST['tafel'];
$klok = $_POST['klok'];
$sec = $_POST['sec'];
$zaalw = $_POST['zaalw'];
$query=”INSERT INTO NS_wedstrijden (Poule1, Poule2, datumtijd, team, thuis, uit, Locid, scheidsr1, scheidsr2, tafel, klok, sec, zaalw) VALUES (’”.$Poule1.”‘, ‘”.$Poule2.”‘, ‘”.$datumtijd.”‘, ‘”.$team.”‘, ‘”.$thuis.”‘, ‘”.$uit.”‘, ‘”.$Locid.”‘, ‘”.$scheidsr1.”‘, ‘”.$scheidsr2.”‘, ‘”.$tafel.”‘, ‘”.$klok.”‘, ‘”.$sec.”‘, ‘”.$zaalw.”‘)”;
$result = mysql_db_query(”Wedstrijd”,$query,$connectionID) or die (”Error updating database” . mysql_error() . “\n$query\n”);
on September 9th, 2008 at 8:57 pm
All the helpers appear to have left.
on September 9th, 2008 at 9:05 pm
The code looks like it should work.
on September 11th, 2008 at 3:37 pm
Do you mean Martijn’s code or my code? Or both?
on September 12th, 2008 at 9:03 pm
:Martijn:
Try something more along the lines of this coding instead, if you prefer to use the mysql_db_query command.
<?php
$connectionID = mysql_connect (’localhost’, ‘test’, ‘password’);
$dbname = mysql_select_db(’testdb’);
mysql_connect ($connectionID)
or die (”Could not connect to the MySQL server.”);
$query = “INSERT INTO NS_wedstrijden (Poule1, Poule2, datumtijd, team, thuis, uit, Locid, scheidsr1, scheidsr2, tafel, klok, sec, zaalw) VALUES (’”.$Poule1.”‘, ‘”.$Poule2.”‘, ‘”.$datumtijd.”‘, ‘”.$team.”‘, ‘”.$thuis.”‘, ‘”.$uit.”‘, ‘”.$Locid.”‘, ‘”.$scheidsr1.”‘, ‘”.$scheidsr2.”‘, ‘”.$tafel.”‘, ‘”.$klok.”‘, ‘”.$sec.”‘, ‘”.$zaalw.”‘)”;
$result = mysql_db_query ($dbname, $query)
or die (”Query ‘$query’ failed with error message: \”" . mysql_error () . ‘”‘);
// Display the data returned by the query
while ($temp = mysql_fetch_row ($mysql_result)) {
echo $temp[0], ”;
}
?>
on September 20th, 2008 at 7:54 am
Hi there,
I’m desperatly looking for help so hope you guys could really help me out.
I’d need something very simple in which a user can insert data to the DB (like this) and then have a search field per one of the fields (example name) and have everyone of that name pop out.
How would this be done?
Thanks!
on September 21st, 2008 at 10:05 pm
Sasha:
Check out this tutorial that I wrote a while ago:
http://teamtutorials.com/photoshop-tutorials/web-graphics/sql-select-based-on-text-inserted-into-a-text-box
I think it is what you are looking for. Thanks.
on September 30th, 2008 at 2:41 pm
Still no answer for my question.
on September 30th, 2008 at 3:17 pm
Christian, try to echo your sql variable after you create it. Seems it is not creating a valid update.
on September 30th, 2008 at 3:23 pm
Try either of these:
$query = ‘INSERT INTO clientsopennew (orderID, orderDate)VALUES (NULL,”$orderDate”)’;
$query = “INSERT INTO clientsopennew (orderID, orderDate)VALUES (NULL,’”.$orderdate.”‘)”;
on September 30th, 2008 at 3:59 pm
Okay, I have an update and clarification. When I use:
the database does get populated. But when I use:
The database does not get populated and a blank screen appears.
on October 2nd, 2008 at 4:20 pm
Thanks, John, for the response. Okay, I basically have it working now. You can fill out all the fields and it’ll populate the database. Only two problems remain (and they are minor compared to what I was facing before but still important):
1. If the user uses a character such as an apostrophe it prevents the database from populating.
2. It’s not populating the product field, which is the only field in this form that utilizes radio buttons.
on October 2nd, 2008 at 4:28 pm
Christina look up sanitizing database inputs. This will gt you started http://xkcd.com/327/ . Not sure about the radio buttons, echo the query and see if the value is being sent.
on October 2nd, 2008 at 6:04 pm
“sanitizing database inputs”
Okay, got it. Thanks . . . and funny cartoon.
on October 7th, 2008 at 4:03 am
this is sanjeev
i have written that code but i am not able to update data in my sql ,
i am getting the error.
Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\sandeep\update.php on line 9
pls help me
on October 10th, 2008 at 4:50 am
when i click submit the whole contents of my php file are displayed in the html page
here is my script
<?php
$Title= $_POST['Title'];
$FirstName= $_POST['FirstName'];
$Surname= $_POST['Surname'];
$JobTitle= $_POST['JobTitle'];
$Company=$_POST['Company'];
$Department= $_POST['Department'];
$Office= $_POST['Office'];
$BusinessPhone= $_POST['BusinessPhone'];
$HomePhone= $_POST['HomePhone'];
$Fax= $_POST['Fax'];
$Cell =$_POST['Cell'];
$Email = $_POST['Email'];
$WebPageAddress= $_POST['WebPageAddress'];
$PhysicalAddress= $_POST['PhysicalAddress'];
$MailingAddress= $_POST['MailingAddress'];
$Birthday= $_POST['Birthday'];
$month= $_POST['month'];
$year = $_POST['year'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (”Error connecting to MySQL”);
mysql_select_db($dbname, $conn) or die (”Could not open database”);
$query=”INSERT INTO contacts(Title,FirstName,Surname,JobTitle,Company,Department,Office,BusinessPhone,HomePhone,Fax,Cell,Email,WebPageAddress,PhysicalAddress,MailingAddress,Birthday,month,year)VALUES(’”.$Title”‘, ‘”$FirstName”‘,’”$Surname”‘,’”$JobTitle”‘,’”$Company’”,’”.$Department’”,’”.$Office”‘,’”.$BussinessPhone’”,’”.$HomePhone’”,’”.$Fax”‘,’”$Cell”‘,’”.$Email”‘,’”.$WebPageAddress”‘,’”.$PhysicalAddress”‘,’”.$MailingAddress”‘,’”.$Birthday”‘,’”.$month”‘,’”.$year”‘)”;
mysql_query($query);
echo “Record Addedclick hereto return to contacts”;
$result = mysql_query($query);
mysql_close($db1);
mysql_close($conn);
echo “”;
?>
on October 20th, 2008 at 3:49 pm
Hi
I need help please.
I keep trying and get the messege: Error Updating Database.
Any suggestions?
Many thanks in advance.
Amir
The codes:
form:
First Name:
Last Name:
Phone-Numbe:
update:
table:
<?php
// Connects to Database
mysql_connect(”localhost”, “xxx”, “xxx”) or die(mysql_error());
mysql_select_db(”friends”) or die(mysql_error());
//collects data from “friends” table
$data = mysql_query (”select * from tablename “) or die (mysql_error(Error));
//puts the “tablename” info into the $info_array
$info=mysql_fetch_array($data);
//print out the contents of the entry
Print “”;
Print “”;
Print “Family Name:”.$info['FName'].”";
Print “Last Name:”.$info['LName'].”";
Print “Phone No.:”.$info['PHON'].”";
Print “”;
?>
on October 22nd, 2008 at 6:32 am
Please can you kindly send the query for insserting into the database using php? because i tried the one written here but the report that I got was that there was an error in line 7 which I tried all tha I could but it still dosent work.
on October 22nd, 2008 at 6:36 am
I will be Very greatful if someone can kindly help solve my TRASH
Thanks
on October 22nd, 2008 at 7:02 am
Please is there a web site or page that I can download the whole code????????????????????????
on October 22nd, 2008 at 9:50 am
Please post lines 6 and 7 from your code. Most likely you forgot a semicolon.
on October 22nd, 2008 at 9:51 am
Also these comments are getting pretty long. Maybe we should launch a forum for these types of questions?
on October 22nd, 2008 at 10:26 am
Thiboso are you saving these files with a .php extension and is php running on your server??
on October 22nd, 2008 at 10:31 am
Please take a good look at this query that I wrote.
Is there anything missing?? Yet I still recieve this (Parse error: parse error, unexpected ‘;’ in C:\wamp\www\root\update.php on line 7).
Please I need your help Here …thanks so Far
on October 22nd, 2008 at 12:07 pm
I don’t see the code you posted, but that error message is telling you exactly what is wrong. Unexpected semicolon, which means you have an extra one or you forgot something else in the line before it. If you post lines 6 &7 I will tell you what is wrong with them.
on October 22nd, 2008 at 12:10 pm
Amir there is no update statement in the code you posted. The code you posted cannot result in the error you are stating.
on October 25th, 2008 at 5:33 am
Hi All
Thank you.
Got my mistake and fixed it.
Working now.
Many thanks!!
And I think a forum for that sort of questions would be very helpfull.
Amir
on November 6th, 2008 at 7:20 am
very nice and useful example gud work keep it up …
on November 24th, 2008 at 3:18 am
Hi,
Very helpful site.
I have a problem .. could any ine pls help me.
I’m using php,MySql.
In my code there is a checkbox. I want to update that checkbox value in the database.. whether it is checked or not. How to capture that value in the database.
on November 27th, 2008 at 12:53 am
I cannot seem to get the database to update or post. Please Help. Here’s my code.
[
<?php
//Verrify Session
session_start();
if(!session_is_registered(myusername)){
header("location:index.php?id=accessdenied");
}
// Rest of Page
require_once ("functions.php");
connect();
mysql_select_db("news")or die("cannot select DB");
// Table Selection - Via URL
$table = $_GET['table'];
// Defining The Form Data
$form_subject = $_GET['subject'];
$form_date = $_GET['date'];
$form_column = $_GET['column'];
$form_preview_post = $_GET['preview_post'];
$form_full_post = $_GET['full_post'];
// Defining Who It Was Posted By
$session_name = $_SESSION['myusername'];
$sql=”INSERT INTO `$table`(`subject`, `date`, `category`, `preview`, `post`)VALUES(`$form_subject`, `$form_date`, `$form_column`, `$form_preview_post`, `$form_full_post`)”;
mysql_db_query($sql);
/*
if($result){
echo “Successful”;
echo “”;
echo “Back to main page“;
}
else {
echo “ERROR”;
}*/
?>
]
on December 1st, 2008 at 11:29 am
Hi,
perfect tutorial
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
on December 7th, 2008 at 9:01 pm
Hey I am having the same problem as Amir, I keep getting the “die” message “error updating database”.
I’m guessing mismatched column names with the database? but I’ve double checked about a zillion times lol. sorry to be a pain…
Thanks for your help.
on December 7th, 2008 at 9:15 pm
sorry! i got it working! yay
stupid commas…
on December 28th, 2008 at 4:12 pm
hi..thanks for the code..while i m clicking on ‘Update database’ button, the output is
$Fname=$_Post['Fname']; $Lname=$_POST[['Lname']; mysql_connect(”localhost”,”abcd”,”1234″) or die(’Error’ .mysql_error()); mysql_select_db(”test1″); $query=”INSERT INTO test1(ID,Fname,Lname) VALUES (’NULL’,'”.$Fname.”‘, ‘”.$LName”)”; mysql_query($query)or die (’Error updating database’); echo “Database Updated with: “.Fname.” “.LName.; mysql_close();
My code for update.php( i m using the same code as mentioned above: -
Untitled Document
$Fname=$_Post['Fname'];
$Lname=$_POST[['Lname'];
mysql_connect(”localhost”,”abcd”,”1234″) or die(’Error’ .mysql_error());
mysql_select_db(”test1″);
$query=”INSERT INTO test1(ID,Fname,Lname) VALUES (’NULL’,'”.$Fname.”‘, ‘”.$LName”)”;
mysql_query($query)or die (’Error updating database’);
echo “Database Updated with: “.Fname.” “.LName.;
mysql_close();
on January 26th, 2009 at 2:40 pm
how to display the data in a table from the database using select query
on February 18th, 2009 at 10:28 am
The code you palced really help. I also wanted to know How you merge several List/menu options into one when writting php code. Lets say u have a drop down list for day another one for month and year. But the database entry is a single entry.
on February 19th, 2009 at 2:29 am
I’m just trying to add one record on my database. Unfortunatley it just says ‘Error updating database’ everytime I try to add a valid record. Here is my code. Please help. Very Urgent.
<?php
$country_name = $_POST['country_name'];
// Initiating a MySQL connection
$db_host = “localhost”;
$db_username = “testuser”;
$db_passwd = “testpass”;
$db= mysql_connect($db_host, $db_username, $db_passwd) or die (”Could not connect to database”);
echo “Connection established.”;
// Connecting to database
$db_name = “country”;
mysql_select_db(”$db_name”) or die (”Could not select the database gurung”);
echo “Database country is selected.”;
$query=”INSERT INTO country (countryID, country_name) VALUES (’NULL’, ‘”.$country_name”‘)”;
mysql_query($query) or die (’Error Updating database’);
echo “Database Updated With: ” .$country_name. “”;
?>
on February 19th, 2009 at 6:02 am
Jack. I lied in the tutorial above. You don’t have to use . if you use double quote it will echo the variable. Try this:
$query=”INSERT INTO country (countryID, country_name) VALUES (’NULL’, ‘$country_name’)”;
on February 19th, 2009 at 6:03 am
Or if you want to do it the other way:
$query=”INSERT INTO country (countryID, country_name) VALUES (’NULL’, ‘”.$country_name.”‘)”;
You forget a period
on February 19th, 2009 at 9:17 pm
John, thanks for the reply. I tried removing the double quote in $country_name but it still comes with ‘Error updating database’ error. When you mentioned “You forget a period”. What do you mean by that. The $query you wrote in your second comment is same as the one I wrote! Please help.
Many thanks, Jack.
on February 20th, 2009 at 12:12 am
Hey folks,
If anyone of you out there is struggling, use the following code:
This code works perfect. Put your thumbs up.
Cheers,
Jack
on February 20th, 2009 at 3:16 am
[...] Creating a Form that will Search a MySQL Database [...]
on February 28th, 2009 at 3:06 pm
sir,what you did above doesn’t work for me……………
nothing is entered in my data base
please help me
its urgent…….
reply soon
on March 3rd, 2009 at 2:39 am
<?php
// Connects to your Database
$host=”localhost”; //Host Name
$username = ” root”; //mysql user name
$password =” sivagami”; //mysql password
$db_name =”tms” ;//database name
$tbl_name =”employee” ; //Table Name
mysql_connect(”localhost”, “root”, “sivagami”) or die(mysql_error());
mysql_select_db(”tms”) or die(mysql_error());
$emp_id = $_POST['emp_id'];
$emp_name = $_POST['emp_name'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$date_of_birth = $_POST['date_of_birth'];
$date_of_join = $_POST['date_of_join'];
$designation = $_POST['designation'];
$query =”INSERT INTO $tbl_name (emp_id, emp_name,address,phone,date_of_birth,date_of_join,designation) VALUES ( ‘”.$emp_id.”‘, ‘”.$emp_name.”‘,’ “.$address.”‘,’”.$phone.”‘,’”.$date_of_birth.”‘, ‘”.$date_of_join.”‘,’”.$designation.”‘ )”) or die(mysql_error());
$result = mysql_query($query) or die(’Error updating database’);
if($result)
{
echo “successfull”;
echo “”;
}
else {
echo “ERROR”;
}
mysql_close();
?>
is this correct or not. i doesn’t work properly. i am not able to insert data to table through forms in php
please anybody help me.
on March 3rd, 2009 at 2:19 pm
Why are you trying to add the die() function to the $query VARIABLE.
Also if you are using php 5 there is no need for concatenation of a string if you use double quotes (meaning no need to use “.” just simple put the $variable in like below) I wrote this a long time ago and have learned a lot since. Maybe I will write some kind of updated version if I get a chance.
Anyway try this and if it doesn’t work you are going to have to figure it out. This isn’t a code writing service, though I could probably make a pretty penny if I charged for it
<?php
// Connects to your Database
$host=”localhost”; //Host Name
$username = ” root”; //mysql user name
$password =” sivagami”; //mysql password $db_name =”tms” ;//database name $tbl_name =”employee” ; //Table Name
mysql_connect(”localhost”, “root”, “sivagami”) or die(mysql_error());
mysql_select_db(”tms”) or die(mysql_error());
$emp_id = $_POST['emp_id'];
$emp_name = $_POST['emp_name'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$date_of_birth = $_POST['date_of_birth']; $date_of_join = $_POST['date_of_join']; $designation = $_POST['designation'];
$query =”INSERT INTO $tbl_name (emp_id, emp_name,address,phone,date_of_birth,date_of_join,designation) VALUES ( ‘$emp_id’, ‘$emp_name’,'$address’,'$phone’,'$date_of_birth’, ‘$date_of_join’,'$designation’)”;
$result = mysql_query($query) or die(’Error updating database’);
if($result){
echo “successfull”;
echo “”;
}
else {
echo “ERROR”;
}
mysql_close();
?>
Also in your code I don’t think mysql_close() is actually doing anything. You need to set a variable equal to your connect and then close it. Something like $conn = mysql_connect(whatever you want here); mysql_close($conn);
If the code outputs an error try to Google it. If it doesn’t out put anything echo $query to verify it is valid.
on March 3rd, 2009 at 2:48 pm
Works perfectly. Thank you
on March 5th, 2009 at 1:58 am
i have a poblem in inserting data into table. i am puting dateof birth as select oprion as month, year,date. the user select this and post to table. but i create only date_of birth field as date data type. hoe i insert these there input into one field in table. please anybosy help me. the following coding only use. is ther eany error suggesstion please reply me.
on March 5th, 2009 at 2:07 am
Thanks mr.john ward. i try as you said. i have further confusion i am putting date of birth as select option in form user enter three inout date,month,year. but i am using dateof birth as single field in mysql table. now how i put my date into table. the following code only i tried. but it also doesn’t work. what to do sir.
on March 6th, 2009 at 6:09 am
sivgavin you hav three fields day month year, just format them into a date before you insert it into the database. $date = $_POST[''year"].”/”.$_POST_['month''].”/”.$_POST['day'] or whatever format you want ot use. THen insert $date.
on March 13th, 2009 at 1:03 pm
[...] If you haven’t taken a look at the past tutorials you may want to: How to Access a MySQL Database Using PHP Inserting Data Into a MySQL Database using PHP [...]
on March 14th, 2009 at 12:20 pm
how i pass my dropdown menu & radiobutton selected item into database mysql . please reply me . i am in deadline of my final year project work. i am a student.
on March 15th, 2009 at 8:50 pm
sivagami it sounds like you need to read the tutorial again. I tell you exactly how to do this with an input box. Set the name on your drop down box and that will be the variable passed.
on March 16th, 2009 at 4:09 am
thanks sir. it works correctly. sorry i am poor in php. thats why i am querying here. i am using separate function for getting date month and year. that’s why i am finding very difficult. here is my coding.
function createYears($start_year, $end_year, $id=’year_select’, $selected=null)
{
/*** the current year ***/
$selected = is_null($selected) ? date(’Y') : $selected;
/*** range of years ***/
$r = range($start_year, $end_year);
/*** create the select ***/
$select1 = ”;
foreach( $r as $year )
{
$select1.= “$year\n”;
}
$select1 .= ”;
return $select1;
}
from this which one is id of select option. either year_select or return value select1.
on March 23rd, 2009 at 5:33 pm
hey there!
everything was working proper until the update.php part or the 3rd part!
it works half way thou,
it send info to the info to the server, but only the field, not the info shows either on the server or in the update.php
example name: john
on my server and .php file will show name: “empty or blank”
that start to happen i was trying to fix the update.php file, i went to server and add two more names as in the beginning of the tutorial and then when i used the database.php file to see if updates the only filed showing was the phone number , first and last name was “black”
what went wrong?
on March 23rd, 2009 at 5:35 pm
ah also when it updates the info below will show blank!
Database Updated With: “blank”
on March 23rd, 2009 at 7:38 pm
Seems like your variables aren’t getting passed. Echo your update statement and see if it is correct.
on March 23rd, 2009 at 11:11 pm
by the way how do i echo my update statement ?
on March 24th, 2009 at 3:38 am
$query=”INSERT INTO TestTable (ID, FNAME, LNAME, PHON)VALUES (’NULL’,'”.$FNAME.”‘,’”.$LNAME.”‘,’”.$PHON.”‘)”;
mysql_query($query) or die (’Error Upadating Database’);
echo “Database Updated With: “.$FNAME.” “.$LNAME.” “.$PHON;
echo $query;
You probably aren’t passing the variables correctly. Are you using the get or post method?
on March 24th, 2009 at 11:04 am
hey john,
i find out what was wrong with it!
$FNAME = $_POST['FNAME'];
$LNAME = $_POST['LNAME'];
$PHON = $_POST['PHON'];
i typed post instead POST ops!
but sitll not completely right! its not passing the phone data! it does not show any error , just dont add to “Database Updated With: “.$FNAME.” “.$LNAME.” “.$PHON; either the database itself
i know it was a post before with similar problem not sure if was a solution for it! i’ll go back there and read again!
also i add
echo $query;
to my code and it didnt worked to well!
i’m postin my whole update.php file so you can take a look!
update
on March 24th, 2009 at 11:05 am
update
on March 24th, 2009 at 11:06 am
on March 24th, 2009 at 6:51 pm
Hey John,
thankx so much! it works perfectly now,
just for future developers i will add this,
my code wasnt working first, instead
POST
i typed
post
second!
on my form.php i mistyped again,
instead PHON i typed FHON;
problem solved now! thanks John code is great!
now moving to Log in part…hehe
on March 24th, 2009 at 11:09 pm
Hey john.
me again!
one more question, how do i display my data in row and colomn like this
mysql> DESCRIBE employee_data;
+——–+——————+——+—–+———+—————-+
| Field | Type | Null | Key | Default | Extra |
+——–+——————+——+—–+———+—————-+
| emp_id | int(10) unsigned | | PRI | 0 | auto_increment |
| f_name | varchar(20) | YES | | NULL | |
| l_name | varchar(20) | YES | | NULL | |
| title | varchar(30) | YES | | NULL | |
| age | int(11) | YES | | NULL | |
| yos | int(11) | YES | | NULL | |
| salary | int(11) | YES | | NULL | |
| perks | int(11) | YES | | NULL | |
| email | varchar(60) | YES | | NULL | |
+——–+——————+——+—–+———+—————-+
on March 25th, 2009 at 1:31 am
<table>
<tr>
<th>field 1</th>
<th>filed 2</th>
<tr>
<?php while $row = mysql_fetch_array($query){
?>
<tr>
<td>
<?php echo $row['field1'];?>
</td>
<td>
<php echo $row['field2'];>
</td>
</tr>
<?php } ?>
</table>
on March 25th, 2009 at 11:55 am
Thanks Johne once again!
so that is how my code should looks like adding that to my tutorial?
mysql_error());
mysql_select_db (”necrose66″);
//build query
$query = mysql_query(”SELECT * FROM TestTable”);
// display results
?>
Name
Last
<?php while $row = mysql_fetch_array($query)) { echo ” ID: ” .$row['ID']. ” First Name: “.$row['FNAME']. ” Last Name: “.$row['LNAME'].” Phome: “.$row['PHON'].” “;}
?>
<?php echo $row['FNAME'];?>
on March 26th, 2009 at 6:34 pm
I did this, but i get
No Database Selected. as my error.
What could the problem be? I have checked my PHPmyAdmin and the correct db_xxxxx is there, as is the table.
I checked the process log in phpmyadmin as well, and it shows database ‘none’ in the ‘Kill’ process.
on April 7th, 2009 at 12:26 pm
Hi Guys, Great tutorial, however keep coming up with an error:
The following is for update.php but i have used filename newcustomer.php
Parse error: parse error on line 11 (begins with $query=”INSERT INTO)
on April 7th, 2009 at 12:27 pm
Hi Guys, Great tutorial, however keep coming up with an error:
The following is for update.php but i have used filename newcustomer.php
Parse error: parse error on line 11 (begins with $query=”INSERT INTO)
on April 7th, 2009 at 12:59 pm
Dont worry…. got it sorted!
on April 9th, 2009 at 11:45 pm
Hi Guys, I need a little help.
I am trying to do something “simple” that is collect emails for an e-bulletin signup with the form post method in flash to write to a mysql database using php.
MYSQL version is 5.0.32
PHP Version is 5.2.6
I am using Action Script 2.0 in Flash
Here is my php:
And here is my actionscript:
function sendEmail(email)
{
var _loc1 = new LoadVars();
_loc1.email = email;
_loc1.onLoad = function (ok)
{
submit_btn.enabled = true;
};
_loc1.sendAndLoad(”http://realityla.com/form.php”, _loc1, “POST”);
gotoAndStop(2);
} // End of the function
stop ();
userPath = email_txt;
userPath.onSetFocus = function ()
{
userPath.text = “”;
};
submit_btn.onRelease = function ()
{
indexOfAt = email_txt.text.indexOf(”@”);
lastIndexOfDot = email_txt.text.lastIndexOf(”.”);
if (indexOfAt != -1 && lastIndexOfDot != -1)
{
if (lastIndexOfDot < indexOfAt)
{
message.text = “please verify your email.”;
}
else
{
var _loc2 = email_txt.text;
this.enabled = false;
sendEmail(_loc2);
} // end else if
}
else
{
message.text = “please enter correct email address”;
} // end else if
};
MYSQL version is 5.0.32
PHP Version is 5.2.6
I am using Action Script 2.0 in Flash
Maybe I am just tired, but it’s not working. Help please!!!
on April 9th, 2009 at 11:48 pm
Sorry, here is my php, geesh….
Email Post
on April 9th, 2009 at 11:49 pm
// Connects to your Database
$host=”mysql.realityla.com”; //Host Name
$username = ”coryjames”; //mysql user name
$password =”mark1045”; //mysql password $db_name =”tms” ;//database name $tbl_name =”employee” ; //Table Name
mysql_connect(”mysql.realityla.com”, “coryjames”, “mark1045”) or die(mysql_error());
mysql_select_db(”ebulletin”) or die(mysql_error());
$email = $_POST['email'];
$query =”INSERT INTO $email (email) VALUES (‘$email’)”;
$result = mysql_query($query) or die(’Error updating database’);
if($result){
echo “successfull”;
echo “”;
}
else {
echo “ERROR”;
}
mysql_close();
?>
on April 15th, 2009 at 3:08 am
Hi
is there any way that i can create user by assigning privilleges by just clicking on the check boxes {check boxes for assigning privilleges}
i can create the database with textboxes but don’t have an idea about the check boxes
Help needed!
on April 16th, 2009 at 10:28 am
I’m trying to write data and time using PHP but am not having any luck. This is the code I use:
$sql = “update contacts set ” . “address=’$address’, ” . “address2= ‘$address2′,” . “city= ‘$city’,” . “state= ‘$state’,” . “zip= ‘$zip’,” . “country= ‘$country’,” . “officephone= ‘$officephone’,” . “homephone= ‘$homephone’,” . “fax = ‘$fax’” . “whensubmitted= NOW(),” . “WHERE id LIKE ‘$recordid’ “;
I get an error with the whensubmitted= NOW() command.
Can anyone help?
on April 16th, 2009 at 10:37 am
$sql = “update contacts set address=’$address’, address2= ‘$address2′, city= ‘$city’, state= ‘$state’, zip= ‘$zip’,country= ‘$country’, officephone= ‘$officephone’, homephone= ‘$homephone’, fax = ‘$fax’, whensubmitted= NOW() WHERE id LIKE ‘$recordid’ ;
there was no comma before when submit. Other than that I’m not sure, Post the error next.
on May 29th, 2009 at 12:29 pm
hi! everyone i have made a register page in php which will collect data in a form from user and store it in mysql db .My prob is that on clicking the submit button i get a blank page n a blank record is created in db .
i hav checked the code so many times but to no gud please help me iam a newbie.iam posting the code below:<?php
if(isset($_POST['user'])&&isset($_POST['pass']))
{
if(strlen($_POST['user'])<4)
echo”Username Must Be More Than 4 Characters.”;
elseif(strlen($_POST['pass'])<6)
echo”password must be more than 6 characters.”;
elseif($_POST['user']==$_POST['pass'])
echo”username and password cannot be same”;
else
{
include(”register.php”);
$firstname=$_POST['fname'];
$lastname=$_POST['lname'];
$username=mysql_real_escape_string($_POST['user']);
$password=$_POST['pass'];
$sex=$_POST['sex'];
$occupation=$_POST['occupation'];
$city=$_POST['city'];
$state=$_POST['state'];
$country=$_POST['country'];
$phno=$_POST['phno'];
$emailid=$_POST['email'];
$comment=$_POST['comment'];
$sqlcheckforduplicate=”SELECT user FROM userinfo WHERE user=’$username’;”;
if(mysql_num_rows(mysql_query($sqlcheckforduplicate))==0)
{
$sqlreguser=”INSERT INTO userinfo(firstname,lastname,user,pass,sex,occupation,city,state,country,phno,eid,comment)VALUES(’”.$firstname.”‘,’”.$lastname.”‘,’”.$username.”‘,’”.$password.”‘,’”.$sex.”‘,’”.$occupation.”‘,’”.$city.”‘,’”.$state.”‘,’”.$country.”‘,’”.$phno.”‘,’”.$emailid.”‘,’”.$comment.”‘);”);
$query= mysql_query($sqlreguser) or die(”error in query:$sqlreguser”.mysql_error());
$dbh=”register”;
mysql_close($dbh);
echo”$query”;
if($query)
{
echo”You are Registered and can now Login”;
$formusername=$username;
header(”location:home.php”);
}
}
else
{
echo”The username you have choosen is already taken.please try another one.”;
$formusername=$username;
}
}
}
else
{
echo”You could not be registered because of missing data.”;
}
?>
on June 17th, 2009 at 6:08 am
This is the code that I have used:
However whenever I submit my form I always get the ‘error updating database’ message.
Anyone any ideas as to what I’m doing wrong?
Thanks in advance!!!!!!!