I designed plain html site,with one enquiry form.It has some fields like name ,address etc.
Onclick of submit button,i wanted this data to go into the database.
I created database and table using phpmyadmin on XAMPP server.
My code is as follows(hello.php):
<script>
function insert_db()
{
<?php
$username = $_POST['name'];
print ($username);
mysql_connect("localhost","root","");
mysql_select_db("addressbook");
mysql_query("insert into colleague values ('$username')");
?>
}
</script>
<form method="post">
<input type="name" name="name" /><br />
<input type="submit" name="mysubmit" value="Submit" onclick="insert_db()"/>
On click of submit button ,two entries are made into the database.One is blank and other is entered value.
how to call the function only once??Is there any other way out..
You can’t mix php and javascript like this. You see, the PHP will always be executed server-side, regardless where it is in the file (PHP does not know JavaScript). Therefore, the first time you load the page, it will insert an empty row (since $_POST[‘name’] is empty). Then, if you click submit, it will do nothing, since the JavaScript code ist empty, submit the form to the server and evaluate the PHP code again, this time with the desired effect.
A proper way to do this would be:
You might also want to work your way through a PHP Tutorial first