i set up a php form to insert data into my db, and noticed the query would run by default every time the page was refreshed. figured i could just move the query into it's own file, and then call it "on submit"...but that didn't work. what's the best way to do this?
Assuming your form is being POSTed to the server, then
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... process the form
}
?>
Checking for the presence of an input field is unreliable - you might change the field's name and forget to update the fieldname check. This method is 100% - the REQUEST_METHOD value will always match how the script was invoked.
Here is how you do it save this file as connection.php Please be aware there is no validate script here. This is just a simple example of how to insert the record into database using php mysql on a same page.
Save this file as conn.php
<?php
$hostname_tfc_conn = "servername";
$database_tfc_conn = "connname";
$username_tfc_conn = "dbusernanme";
$password_tfc_conn = "dbpassword";
$tfc_conn = mysql_pconnect($hostname_tfc_conn, $username_tfc_conn, $password_tfc_conn) or trigger_error(mysql_error(),E_USER_ERROR);
?>
Now name the following page as you want
<?php
include_once("conn.php");
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO user (username, password, email) VALUES (%s, %s, %s)",
($_POST['name'], "text"),
($_POST['password'], "text"),
($_POST['email'], "text"));
mysql_select_db($database_tfc_conn, $tfc_conn);
$Result1 = mysql_query($insertSQL, $tfc_conn) or die(mysql_error());
$insertGoTo = "filename.php";//Put you filename here if the record is successful
header("Location: %s", $insertGoTo));
}
?>
<body>
<form id="form1" name="form1" method="POST" action="<?php echo $editFormAction; ?>">
<p>Name :
<input type="text" name="name" id="name" />
</p>
<p>Email:
<input type="text" name="email" id="email" />
</p>
<p>Password:
<input type="text" name="password" id="password" />
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
<input type="hidden" name="MM_insert" value="form1" />
</form>