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.
Related
I'm new to PHP, and I'm sure this is a common think to do, but 99% of the answers I have found to this involve AJAX, JQuery and/or JavaScript.
I am only allowed to use HTML/CSS and PHP in my project, so I need a working option that does not involve anything else.
I have the following setup:
index.php, this holds my form structure
insert.php, this sanitizes/validates and inserts form data into a database table
Leaving action as insert.php sends me to my insert.php page, which I want to keep private and for developer eyes only...no good.
form action=" " method="post"
// OR
form action="index.php" method="post">
Leaving action blank or as index.php keeps me on the same page, but...
I want to keep my form processing in a separate file (insert.php) and NOT on the same page, if at all possible.
Do I have any options for this that are not excessively complex in pure PHP?
Thanks for any advice.
(PS. If there's any blatant errors or poor form here, I'm all ears to constructive criticism)
Here's a snapshot of my insert.php file if its helpful. I can upload my form as well, but its very basic (just select a course, input first/last name, input student id).
// Clean the data coming from the MySQL tables
$course_clean = htmlentities($_POST['course_id']);
$stu_name_clean = htmlentities($_POST['first_last']);
$stu_id_clean = htmlentities($_POST['stu_id']);
// Escape user input coming from forms
$course = mysqli_real_escape_string($open, $_REQUEST['course_id']);
$stu_name = mysqli_real_escape_string($open, $_REQUEST['first_last']);
$stu_id = mysqli_real_escape_string($open, $_REQUEST['stu_id']);
// INSERT DATA
$insert = "INSERT IGNORE INTO enrolled (course_id, stu_id) VALUES ('$course', '$stu_id')";
if(mysqli_query($open, $insert)){
echo "Records added successfully to ENROLLED.";
} else{
echo "ERROR: Could not add records to ENROLLED. " . mysqli_error($open);
}
Something like this might be what you want:
<?php
if (!empty($_POST)) {
require "insert.php";
}
?>
<html><head></head><body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="text" name="course_id"><br/>
<input type="text" name="first_last"><br/>
<input type="text" name="stu_id"><br/>
<input type="submit">
</form>
</body></html>
It's possible to submit the page to itself and check if the $_POST is empty or not. If it's empty show the form of the page if not insert the data into the database.
<?php if (!empty($_POST)):
// Clean the data coming from the MySQL tables
$course_clean = htmlentities($_POST['course_id']);
$stu_name_clean = htmlentities($_POST['first_last']);
$stu_id_clean = htmlentities($_POST['stu_id']);
// Escape user input coming from forms
$course = mysqli_real_escape_string($open, $_REQUEST['course_id']);
$stu_name = mysqli_real_escape_string($open, $_REQUEST['first_last']);
$stu_id = mysqli_real_escape_string($open, $_REQUEST['stu_id']);
// INSERT DATA
$insert = "INSERT IGNORE INTO enrolled (course_id, stu_id) VALUES ('$course', '$stu_id')";
if(mysqli_query($open, $insert)){
echo "Records added successfully to ENROLLED.";
} else{
echo "ERROR: Could not add records to ENROLLED. " . mysqli_error($open);
}
else: ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="text" name="course_id"><br/>
<input type="text" name="first_last"><br/>
<input type="text" name="stu_id"><br/>
<input type="submit">
</form>
<?php endif; ?>
I want to have a simple HTML input field where people can type all kinds of nonsense. For example, a user types: "Hello, I'm Nicky". When the user then clicks the button Send, I want a simple PHP script to replace the word "Nicky" to "Nicki" and show it to the user. So basially, just a simple PHP script which replaces specific words from an input field and then print out the exact same line the user has inputted, except show Nicki instead of Nicky.
How can I achieve this, in the most simplest way?
My code looks like this now:
<?php
$_POST['name'] = str_replace("Nicky","Nicki",$_POST['name']);
?>
<form method="post">
<input type="text" name="name">
<input type="submit">
</form>
<?php
if(isset($_POST['form-action']) && $_POST['form-action'] == "submit-form"){ // form has been submitted
echo "<p>BEFORE: ".$_POST['name']."</p>"; // what the user entered "Nicky"
$_POST['name'] = str_replace("Nicky","Nicki",$_POST['name']); // find/replace Nicky with Nicki
echo "<p>AFTER: ".$_POST['name']."</p>"; // what the $_POST['name'] now is
}
?>
<form method="post">
<input type="text" name="name" value="Nicky">
<input type="submit">
<input type="hidden" name="form-action" value="submit-form">
</form>
In addition to this, if you want to expand the Find & Replace variables, you could use an array:
$FindReplace = array("Nicky"=>"Nicki", "Blue"=>"Red"); // build an array of find/replace variables
....
foreach($_POST as $Name=>$Value){
echo "<p>Before: ".$Name."=".$Value."</p>"
foreach($FindReplace as $Find=>$Replace){
$Value = str_replace($Find,$Replace,$Value);
}
echo "<p>After: ".$Name."=".$Value."</p>"
}
I have a form with few input fields and a update option ,suppose if i have 10 fields and i update only first two fields and not the rest who can i display a message that only the first to field A and B are updated using PHP and Mysqli
in the screenshot if i update the value of bill id and origin i should display message out in some other page that says that bill id and origin has been updated with "xyz " value
One way is to fetch fields with real and old name i.e.
Select name,name as old_name from table
In html
<input type="text" name="name" value="name from db">
<input type="hidden" name="old_name" value="old_name from db">
After submit form you can check it by.
And check after post.
If(post['name']==post['old_name'])
Something like this.
Another way is from js by checking onchange event
well it'll be something like this ..
html:
<html>
<body>
//action is defining the php file's name which the form will be sent to ;
//method is defining the method which the form will be sent with
<form action="updateCheck.php" method="post">
<input type="text" name="input-filed-1"/>
<input type="text" name="input-filed-2"/>
<input type="text" name="input-filed-3"/>
<input type="text" name="input-filed-4"/>
<input type"text" name="input-filed-5"/>
<input type="submit" value="submit/>
</form>
</body>
</html>
create a file named updateCheck.php in the same directory and enter the following code
<?php $updateMessage = "you have updated the following fields";
for($x = 0 ; $x<=5 ; $x++)
{
// trim for erasing the whitespaces
// that if clause checks if there was data entered in the update input fields
if(isset($_POST["input-field-".$x]) && trim($_POST["input-field-".$x]))
{
$updateMessage.= "input-field-".$x ;
}
}
echo "<script type='text/javascript'>alert('".$updateMessage."')</script>"
?>
I haven't tested the code .. but study it carefully and you'll see how it's done
I am making a form in html. When a person clicks on submit, it checks if certain fields are filled correctly, so pretty simple form so far.
However, i want to save the text which is typed into the fields, if a person refreshes the page. So if the page is refreshed, the text is still in the fields.
I am trying to achieve this using php and a cookie.
// Cookie
$saved_info = array();
$saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][',
$_COOKIE['offer_saved_info']) : array();
foreach($saved_infos as $info)
{
$info_ = trim($info, '[]');
$parts = explode('|', $info_);
$saved_info[$parts[0]] = $parts[1];
}
if(isset($_SESSION['webhipster_ask']['headline']))
$saved_info['headline'] = $_SESSION['webhipster_ask']['headline'];
// End Cookie
and now for the form input field:
<div id="headlineinput"><input type="text" id="headline"
value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ?
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>"
tabindex="1" size="20" name="headline" /></div>
I am new at using SESSION within php, so my quesiton is:
Is there a simpler way of achieving this without using a cookie like above?
Or what have i done wrong in the above mentioned code?
First thing is I'm pretty sure you're echo should have round brackets around it like:
echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value)
That's not really the only question your asking though I think.
If you're submitting the data via a form, why not validate using the form values, and use the form values in your html input value. I would only store them to my session once I had validated the data and moved on.
For example:
<?php
session_start();
$errors=array();
if($_POST['doSubmit']=='yes')
{
//validate all $_POST values
if(!empty($_POST['headline']))
{
$errors[]="Your headline is empty";
}
if(!empty($_POST['something_else']))
{
$errors[]="Your other field is empty";
}
if(empty($errors))
{
//everything is validated
$_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here
header("Location: wherever.php");
}
}
if(!empty($errors))
{
foreach($errors as $val)
{
echo "<div style='color: red;'>".$val."</div>";
}
}
?>
<!-- This form submits to its own page //-->
<form name="whatever" id="whatever" method="post">
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" />
<div id="headlineinput">
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" />
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //-->
</div>
<input type="submit" value="submit" />
</form>
my page receives data which i retrieve with $_post. I display some data and at the bottom of page my button has to save data to mysql. I could submit form to next page, but how do i access the data that I have retrieved with post then? Lets say i have following code (in reality alot more variables ..):
<?php
$v= $_POST["something"];
echo $v;
echo "Is the following information correct? //this would be at the bottom of the page with the buttons
?>
<input type="button" value="submit data" name="addtosql">
You can do it in two methods:
1) You can save the POST variable in a hidden field.
<input type="hidden" name="somevalue" value="<?php if(isset($_POST["something"])) echo $_POST["something"];?>" >
The hidden value also will get passed to the action page on FORM submission. In that page you can access this value using
echo $_POST['somevalue'];
2) Use SESSION
You can store the value in SESSION and can access in any other page.
$v= $_POST["something"];
session_start();
$_SESSION['somevalue']=$v;
and in next page access SESSION variable using,
session_start();
if(isset($_SESSION['somevalue']))
echo $_SESSION['somevalue'];
Take a look. Below every thing should be on single php page
// first create a function
function getValue($key){
if(isset($_POST[$key]))
return $_POST[$key];
else
return "";
}
// process your form here
if(isset($_POST['first_name']){
// do your sql stuff here.
}
// now in html
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="first_name" value="<?php echo getValue("first_name"); ?>" />
<input type="submit" />
</form>