I have Two forms in my index.php and am trying to get them to submit and POST their data seperatly
Form 1
echo '<form action="process.php?type=news" method="post">';
echo '<table cellspacing="0"><tr><th>';
echo 'Add News to News Feed';
echo '</th></tr><tr><td>';
echo 'Title:<br /><input name="newstitle" type="text" id="add" style="height:16px;width:525px;" size="80" maxlength="186" /><br />';
echo 'Main Body Text:<br /><textarea name="newsfeed" id="add" style="width:525px;height:78px;" maxlength="2000" ></textarea>';
echo '<input style="float:right;margin-top:5px;" id="button" type="submit" value="Submit" />';
echo '</td></tr></table></from>';
And Form 2
echo '<form action="process.php?type=suggest" method="post">';
echo '<table cellspacing="0"><tr><th>';
echo 'Suggest Additions to the Intranet';
echo '</th></tr><tr><td>';
echo '<textarea name="suggest" id="add" style="width:330px;height:60px;" maxlength="800" ></textarea>';
echo '<input style="float:right;margin-top:5px;" id="button" type="submit" value="Submit" />';
echo '</td></tr></table></from>';
I want these both to post and do the action after pressing the submit button, but currently the second form submit to the first forms action
How can i fix this???
EDIT: Also i am using .PHP for both the index and process page then using it to echo the forms onto the page
Also here is the process.php data
$type=$_REQUEST['type'];
$suggest=$_POST['suggest'];
$newstitle=$_POST['newstitle'];
$news=mysql_real_escape_string($_POST['newsfeed']);
if ($type == "news")
{
$sql=mysql_query("SELECT * FROM newsfeed WHERE title = ('$newstitle')");
$number_of_rows = mysql_num_rows($sql);
if ($number_of_rows > 0)
{
echo 'This Title is Already Taken';
}
else
{
$sql="INSERT INTO newsfeed (title, news) VALUES ('$newstitle','$news')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header('Location: index.php');
exit;
}
}
elseif ($type == "suggest")
{
$sql="INSERT INTO suggestions VALUES ('$suggest')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
header('Location: index.php');
exit;
}
Could it be that you are not closing the form with </form>, but with </from>, so the code of the second form is in fact still inside the first form since the tags are never closed?
try giving the submit an on click for each form so in its submit buttons html put this:
onclick="document.forms["myform1"].submit();"
and for form 2 put
onclick="document.forms["myform2"].submit();"
Im not sure exactly what you would like to achieve, so heres my assumptions,
1. your form submits wrongly, eg, second form submits the first form's data
or
2. you would like to do both submits 1 after another.
FOR 1:
Do this.
<form id="form1" action="process.php" method="POST">
<input type="hidden" name="type" value="news">
....
</form>
Note the spelling
/form not /from
<form id="form2" action="process.php" method="POST">
<input type="hidden" name="type" value="suggest">
....
</form>
Note the spelling
/form not /from
Some pointers:
Instead of echoing out so many times, echoing out once is suffice! Remember echos slow down your script. Also I would not pass the type as a $_GET, post is always safer for forms, you can use a hidden field to add the type:
<?php
echo '
<form action="process.php" method="post">
<input type="hidden" name="type" value="news">
...
...
</form>';//Not </from>
?>
Then with the PHP part use a switch case instead of if elses, it will be easier to add features then splitting with another ifelse, plus the default block can be used for anything that dont match like the last else in an if else statement.
<?php
$type = $_POST['type'];
switch($type){
case "news":
...
break;
case "suggest":
...
break;
default:
//default if different type or no type is set
break;
}
?>
Also move over to PDO or prepared mysqli_ functions for your mySQL stuff its safer.
Related
I am trying to get my page to redirect after deleting a record from the database but it wont redirect. It is echoing out text and also deleting the record but it just reloads me on the same page with a form that no longer has information in it.
Here is the button im using
echo '<form>';
echo '<br /><br /><input style="cursor:pointer" class="button" type="submit" value="Delete Event" name="delete" id="delete" />';
echo '</form>';
Here is the PHP im using to delete the row from the DB
if (isset($_POST['delete'])){
$mysqli->query('DELETE FROM information WHERE id = '.intval($_GET['id']));
header('Location: index.php');
}
I have no idea whats wrong with it.
The header doesn't work, probably because there's already another one.
I suggest you to use a little part of Javascript:
if (isset($_POST['delete'])){
$mysqli->query('DELETE FROM information WHERE id = '.intval($_GET['id']));
echo "<script type='text/javascript'>window.location.href = 'index.php'</script>";
}
I assume that both the code snippets are present in a single PHP file. Then, your form will by default post to the same file using GET method.
Change your PHP code to look like this:-
<?php
if (isset($_GET['delete'])){
$mysqli->query('DELETE FROM information WHERE id ='.intval($_GET['id']));
header('Location: index.php');
}
echo '<form>';
echo '<br /><br /><input style="cursor:pointer" class="button" type="submit" value="Delete Event" name="delete" id="delete" />';
echo '</form>';
?>
Your form tag is completely empty. You check if $_POST["delete"] is set, but you haven't even specified the method of communication between your form and your PHP file on your form. Try changing your starting form tag to this:
<form method = "POST" action = "YOUR PHP FILE.php">
Your PHP file seems fine as long as index.php is on the same level as the form.
You can also redirect your page to somewhere else this way:
echo "<meta http-equiv="refresh" content="1;url=index.php"/>"
<form>
Delete id <input type = "text" name ="deleteid" id ="deleteid"/>
<input type ="submit" name = "submit" />
</form>
<?php
if (isset($_POST['submit'])){
$id = $_POST['deleteid'];
$query = "DELETE FROM information WHERE id = $id";
//rest Execute the query
header('Location: xyx.php');
}
<?
This is my first post and I'm complete beginner so please be gentle :)
I'm trying to create a form that after submitting an account name would check and return a CNAME of the host (account+domain.com)
The problem is that I want to do it all on the same website so it will either display the form if nothing has been posted or display the result otherwise.
This is what I've created, it seems that I'm not calling the POST correctly, but I can't really get what am I doing wrong.
Please help
<?php
if(isset($_POST[DomainSubmit])){
$AccountName = $_POST[ClientDomain];
$CName = dns_get_record($AccountName."domain.com", DNS_CNAME);
echo '<h1>'.$CName.'<h1>';
}
echo'<form action="index.php" method="POST" ">
<input type="text" name="ClientDomain">
<input type="submit" name="DomainSubmit">
</form>'
?>
Try to add else so it will be displayed one or another stuff
<?php
if(isset($_POST['DomainSubmit']) && isset($_POST['ClientDomain'])){
$AccountName = $_POST['ClientDomain'];
$CName = dns_get_record($AccountName."domain.com", DNS_CNAME);
echo '<h1>'.$CName.'<h1>';
} else {
echo'<form action="index.php" method="POST" ">
<input type="text" name="ClientDomain">
<input type="submit" name="DomainSubmit">
</form>'
}
?>
Edit:
You forgot to properly write array POST (missing quotes)
$_POST[DomainSubmit]
And it should be
$_POST['DomainSubmit']
I have a code like this
<?php
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
} else {
echo "wrong";
}
?>
<form action="" method="post" name="myform">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="submit1">
</form>
I want to save values into db after user clicks the submit button. I have been trying different approaches, but still could not get near to it.
Any ideas/hints what I should do next or doing wrong?
After the given suggesstion below is my code :
<form action="" method="post" name="myform">
<input type="hidden" value="123" name="match">
<input type="submit" value="Claim your daily bonus $o.o2" name="submit1">
</form>
<?php
if(isset($_REQUEST['submit1']))
{
echo "$thismemberinfo[msurf]";
echo " $msurfclicks";
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
//$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo " not set " ;
}
}
?>
you can use isset for checking if button is clicked or not
if(isset($_REQUEST['submit1']))
{
if ( $thismemberinfo[msurf] >= $msurfclicks ) {
$sql=$Db1->query("INSERT INTO d_bonus VALUES('$userid','0.02',NOW())");
echo "success";
}
else
{
echo "wrong";
}
header("location:".$_SERVER['PHP_SELF']);
}
You need to check if the request has come from the post submit i.e. as others pointed check $_POST['submit']
if(isset( $_POST['submit'] ) {
// your complete rest php code goes here to insert the record
}
On page refresh, it'll see the request is not a post request submitted hence won't execute the php code in the if and will just display the page.
Your code is missing a few things..
To insert entries into the database, you should think more about what tasks need to be carried out, I'll give you a list of them, you have probably done some of these.
1) Connect to the database.
2) Obtain the values entered into the form, and store them in local variables, in your case you have used POST on your form and therefore.. here's an example:
$Field1 = mysql_real_escape_string($_POST['match']); // match?? This post data comes from the name field of your form.
3) Create your query... e.g..
$sql = "INSERT INTO table_name (table_heading) VALUES ('$Field1')";
4) Run the query
I am trying to write a dynamic form using PHP. I'd like to have a single webpage that contains two forms:
The upper form allows to search for an element in the mysql database, e.g., for a name
The lower form shows the data that is associated with this name in the database
If I press on the "Search" button of the upper form, then the the lower form is shown and the text fields are filled with data from the database that belong to this name. If I change the user name to some other value and press again "Search", then the data that is associated with the new record is shown and so on.
The lower form also has a button "Update" which allows to transfer changes made to the text boxes (in the lower part) to the database.
Now, I have the following problem: In my script I set initially the value of name (from the upper form) to "". When I then press the "Search" button, then the lower part of the form is shown and the corresponding data is shown in the lower part. When I then press the "Update" button, then the text field associated with name is set to the empty string. This is because in my script I set initially name to the "". I'd like that in this case the data entered in the upper form is not changed, i.e., it stays the same.
I guess, I am missing something here. There is probably an easy solution for this and I am doing something fundamentally wrong. It'd be great if you could help me.
That's what I tried... I deleted lots of details, but I guess that can give you an idea what I am trying to do. Notice that the whole code is in the file update.php.
<?php
function search_bus($mysql, $name)
{
// do some stuff here...
}
function update_bus($mysql, $b_id)
{
// do some stuff here...
}
// some global variables
$b_id = 0;
$username = ""; // username of business
// get b_id that corresponds to username
if (isset($_REQUEST['search']))
{
$b_id =0; // business id
if (isset($_POST['user']))
{
$username = $_POST['user'];
$b_id = search_bus($mysql, $username);
}
}
elseif(isset($_REQUEST['update']))
{
update_bus($mysql, $b_id);
}
?>
<h2>Search:</h2>
<form name="search_bus" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="submit" value="Suchen" name="search"/>
</form>
<?php
if($b_id != 0)
{
?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<-- some form follows here -->
<?php
}
?>
I think what you're missing is to create a HTML Hidden field to keep the value of Name variable.
<input type="hidden" name="name" value="<?php print $nameVar ?>" />
Add this input to both forms so you can keep the value no matter what button the user clicks.
Hope this helps.
Adding code to verify the
<h2>Search:</h2>
<form name="search_bus" method="post"
action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<input type="submit" value="Suchen" name="search"/>
</form>
<?php if($b_id != 0) { ?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];>">
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<-- some form follows here -->
<?php } ?>
Dont initialize $b_id if it already comes into the http request.
if (!isset($_POST['b_id']))
{
$b_id = 0;
}
else
{
$b_id = $_POST['b_id'];
}
This way you can alway remember the last selected value of b_id.
Hope this can help you.
I have two forms in the page one is filter, second is the item list, when I apply the filter to item list form, selected values reset to default. For filter I can save selected values, because I submit this form via POST method, but other remains not submited is possible to save selected that form values after page refresh? Here is some code of second form:
<form name="forma" method="post" onMouseOver="kaina();" onSubmit="return tikrinimas()" action="pagrindinis.php?page=generuoti.php">
<table width="540" border="1" align="center">
<tr>
<td>Client:</td>
<td>MB:</td>
<td>Price:</td>
</tr>
<tr>
<td>
<?php
$query="SELECT name,surname,pers_code FROM Clients";
mysql_query("SET NAMES 'UTF8'");
$result = mysql_query ($query);
echo "<select name=Clients id='clients'>";
echo "<OPTION value=''>- Choose -</OPTION>\n";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[pers_code]>$nt[name] $nt[surname]</option>";
}
echo "</select>";
?></td>
</tr>
</form>
You need to set the selected attribute of your select element based on what is in $_POST. Something like:
$selected = $_POST['Client'];
while($nt=mysql_fetch_array($result)){
if ($selected == $nt[pers_code]) {
echo "<option value=$nt[pers_code] selected="selected">$nt[name] $nt[surname]</option>";
}
else {
echo "<option value=$nt[pers_code]>$nt[name] $nt[surname]</option>";
}
}
Also note that you should probably sanitize any values you get from $_POST.
Unfortunately there is no easy way to do this, and it's something that PHP and web developers in general have maligned for years, because repopulating form fields is never easy AND clean.
Values in the form you aren't submitting wont be sent (via GET or POST), so you're left with writing a custom workaround.
While it's a bit Q&D, I would recommend sending an Ajax call on form submit to store the values for your second form in the $_SESSION variable.
I'm sorry to say there's no easy alternative - due to the stateless nature of HTTP requests, this is something that every programmer has to struggle with.
just to break the question down to a more simplified form, let's assume we don't have the hassle of working with dropdowns. The real issue you're having is to take a value from form 1 and have it work even after form 2 has been submitted.
If you use a hidden field on form 2, of the same name as form 1, and populate it based on both form 1 and form 2's POST data, it will be "remembered"
<? // mostly html with a bit of php. ?>
<form id="f1" method="POST">
<input type ="text" name="f1val" value="<?= htmlspecialchars( array_key_exists( 'f1val', $_POST )?$_POST['f1val']:'' ); ?>">
<input type="submit">
</form>
<form id="f2" method="POST">
<input type="hidden" name="f1val" value="<?= htmlspecialchars( array_key_exists( 'f1val', $_POST )?$_POST['f1val']:'' ); ?>">
<input type ="text" name="f2val" value="<?= htmlspecialchars( array_key_exists( 'f2val', $_POST )?$_POST['f2val']:'' ); ?>">
<input type="submit">
</form>
<script type="text/javascript" src="js/jquery1.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#forma").submit(function(event) {
var 1stformfield = $form.find( 'input[name="misc"]' ).val();
/* stop form from submitting normally */
//event.preventDefault();
$.post("1stformsubmit.php", $("#forma").serialize());
//after it posts you can have it do whatever
//just post code here
$('#iframe1').attr('src', 'iframepage.php?client=' + 1stformfield);
window.frames["iframe1"].location.reload();
return false;
});
});
</script>
<form name="1stform" method="post" action="/">
<input type="text" name="misc" id="misc" />
<input type="submit" name="submit" id="submit" value="submit 1st form"/>
</form>
<iframe id="iframe1" src="" scrolling="no" ></iframe>
iframe page
<form name="forma" method="post" onmouseover="kaina();" action="/">
<table width="540" border="1" align="center">
<tr>
<td>Client:</td>
<td>MB:</td>
<td>Price:</td>
</tr>
<tr>
<td>
<?php
$selected = $_GET['Client'];
$query="SELECT name,surname,pers_code FROM Clients";
mysql_query("SET NAMES 'UTF8'");
$result = mysql_query ($query);
echo "<select name=Clients id='clients'>";
echo "<OPTION value=''>- Choose -</OPTION>\n";
while($nt=mysql_fetch_array($result)){
echo "<option value=$nt[pers_code]>$nt[name] $nt[surname]</option>";
}
echo "</select>"; ?></td>
</tr>
</form>
This will post all inputs inside your form to the file you specify then you can have it do whatever you like, for example show a thank you message..Hope it helps.