By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,038 Members | 870 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,038 IT Pros & Developers. It's quick & easy.

how to insert data into databse when a button is clicked

P: 2
hiii everybody,

i have a little code that inserts the data into the databse. but the problem is the insertion should be peroformed only when a button is clicked. i have problems in this because i am not able to call the function when the button is clicked. hope anyone can help me out with a good code.

echo"Enter the name :";
echo"<input name='names' type='text'>";
echo"<input type='submit' value='ADD name' align=center><br>";
$link = mysql_connect("","","");
mysql_select_db("db");

/*the below statements must get executed only when the button is clicked*/
$query="insert into table value("");
mysql_query($query);
Jan 23 '07 #1
Share this Question
Share on Google+
2 Replies


acoder
Expert Mod 15k+
P: 16,027
Just use a simple submit button which posts the data to another page which should be specified in your form tag, e.g.
[HTML]<form action="youractionpage.php" method="post" ...>
<input type="submit" ...>[/HTML]
Jan 23 '07 #2

ronverdonk
Expert 2.5K+
P: 4,258
The easiest way to handle this is in one script. After you entered the name and clicked the 'ADD name' button, the script itself is invoked again and processes the entered value by inserting it into the database.
The script's process is the folllowing:
Expand|Select|Wrap|Line Numbers
  1. If form is submitted 
  2.   Do
  3.     get the value
  4.     connect to server and db
  5.     build insert stmt
  6.     insert value into db
  7.     issue message
  8.   End-Do
  9. End-If
  10. Else
  11.   Do
  12.     show form
  13.     enter data
  14.     at click submit form
  15.   End-Do
  16. End-Else
[php]<?php
// check to see if form is submitted
if (isset($_POST['names'])) {
// get the POSTed value after cleansing
$names = stripslashes($_POST['names']);
// setup the server and db connection
$link = mysql_connect("","","")
or die("Cannot connect to server: ".mysql_error());
mysql_select_db("db")
or die("Cannot connect to database: ".mysql_error());
// build the MySQL query
$query="INSERT INTO table VALUES('$names')";
// insert into db
$res = mysql_query($query)
or die("INSERT error: ".mysql_error());
// issue message
echo "Field succesfully added to database";
}
else {
echo '<form action="'.$_SERVER['PHP_SELF'].'" method="POST">';
echo "Enter the name :";
echo "<input name='names' type='text'>";
echo "<input type='submit' value='ADD name' align=center><br>";
}
?>[/php]
Good luck.

Ronald :cool:
Jan 23 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.