poonam
poonam

Reputation: 810

PHP-Function call

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

Upvotes: 0

Views: 903

Answers (2)

mensi
mensi

Reputation: 9826

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:

<?php
if (!empty($_POST['name'])){ // check if form values are there
    $username = $_POST['name'];
    print ($username);
    mysql_connect("localhost","root","");
    mysql_select_db("addressbook");

    mysql_query("insert into colleague values ('$username')");
}
?>

<form  method="post">
    <input type="name" name="name" /><br />
    <input type="submit" name="mysubmit" value="Submit" />
</form>

You might also want to work your way through a PHP Tutorial first

Upvotes: 4

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

You cannot, I repeat CANNOT, combine JS and PHP in this way.

Right-click the page, select View Source, and you will clearly see why.

PHP is run BEFORE the browser gets the page.

Therefore, you get an empty record when you load the form, then a filled one when you submit it because $username is defined that time.

Upvotes: 5

Related Questions