I have an entry Form. When the page is loaded, it must check:
if ($_SESSION[WorkMode] == 'UPDATE')
Then fill the Form with values from the database, else open a blank Form.
If I fetch the results in a different PHP file and call this .php file on load, how to fill the Form.
Set the variables that hold the values for your form, then include the "template" of the form you're having.
File 1:
<?php
$res = mysql_query("..");
if($res) {
$row = mysql_fetch_assoc($res);
$name = $row['name'];
$birthday = $row['birthday'];
...
include('form.tpl');
}
File 2 (form.tpl)
<form action="">
<input type="text" name="username" value="<?php isset($name)?$name:""; ?>" />
.. and so on
</form>
Alternatetively you can use a full blown template engine like Smarty to do the job for you.
Best wishes,
Fabian
$formvalue = NULL;
if ($_SESSION[WorkMode] == 'UPDATE')
$formvalue = $some_database_value;
echo '<input type="text" name="myname" value="'.$formvalue .'" />';
I found out that the following did it for me, adding the variable after a column.
<label>Firstname : </label><input type="text" name="Firstname" value= "<?php echo (isset($_POST['firstname'])) ? htmlspecialchars($_POST['firstname']) : $firstname;?>"
Related
there!
I want to do a database search and display the result back to the user in a pre-populated HTML form.
I located the exact part in the code that is not working but I can't understand why PHP is not picked by the server. I'm using UwAMP.
To illustrate the problem here is my short snippet of code that I need help with:
<form id="st_reg" action="" method="POST">
Student Number:
<input type="number" name="s_num" min="1000000" max="3000000" > </br>
<input type="Submit" value="Search">
</form>
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
if(empty($_POST['s_num'])){
$errors[] = "You forgot to enter the Student No!";
}
else{
$st_no = trim($_POST['s_num']);
}
if(empty($errors)){
//Open database connection
require('../../connect_to_database/mysql_connect.php');
//Check if the student is already in the database
$query = "SELECT * FROM student WHERE student_no = $st_no";
//Run the query
$result = mysqli_query($db_connection,$query);
if(!$result){
echo "The student does not exist!";
echo"Please <a href='index.html'>go back</a> and choose another action!";
}
elseif($result){
echo "<h2>Student Details:</h2>";
while($row = mysqli_fetch_array($result)){
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
AND the PHP code inside VALUE ATTRIBUTE is not executing when it should in reality. Don't bother about GLOBAL php tags not being closed 'cause they are in the file (I'm not that dump).
Please note all this code is inside a .php file with HTML code. This is a just the processing part after the form is submitted. I saved my time by using single-quotes for echo and escaped the sigle-quotes along the way where DB access was required. I tried curly brackets around variables, echo with double-quotes escaping double-qoutes within it but none of these attempts were successful. This is strange because I can perfectly echo $row['student_no'] outside of this context and is running fine.
I also looked at similar questions on this website. They were close but none of them had nearly to this context. I am open to any suggestions and better than that solutions.
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="<?php if(isset(\$row[\'student_no\'])) echo \$row[\'student_no\']; ?> ">
should look like this:
echo '<form id="st_reg" action="" method="POST">
<label>Student Number:</label>
<input type="number" name = "st_number" min="1000000" max="3000000" value="' . (isset($row['student_no']) ? $row['student_no'] : '') . '">
CONTINUATION OF STRING...
The following will do what you want.
value="<?= (isset($row["student_no"]) ? $row["student_no"] : "") ?>"
You don't need to worry about all of the escaping when you're inside the PHP chunk already.
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>
I have inside loop some fields for send inside form with other fields :
<?php
for($f=1;$f<=3;$f++)
{
?>
<input type="text" name="friend['email_<?php echo $f;?>']" value="<?php echo $_POST['friend']['email_'.$f.''];?>">
<?php
}
?>
When i send from form i need get the value of each field if no empty , i think the problem it´s in no recover the value send from the form , i don´t know if i writte right
Ony it´s that problem , thank´s , the best regards
I think the problem here is that you have single quotes around email_<?php echo $f; ?> - in POST data, these are not needed. So, you would have:
<form action="myPage.php" method="POST">
<?php for ($f=1;$f<=3;$f++) { ?>
<input type="text" name="friend[email_<?php echo $f; ?>]" value="<?php echo ... ?>">
<?php } ?>
<input type="submit">
</form>
PHP will parse POST data into associative arrays, so you will get back a 'friend' object in $_POST. You can access this like so:
<?php
$friends = isset($_POST['friend']) ? $_POST['friend'] : array();
print_r($friends);
?>
I'm not sure if i'm getting it right. You must send your form data in order to manipulate it. For example if you want to print all the form data:
Client Side:
<form action="boo.php" method="POST">
<input type="text" name="name">
<input type="text" name="age">
<input type="submit">
</form>
Server Side:
<?php
$name = "";
$age = "";
if( isset($_POST['name']) && isset($_POST['age']) )
{
$name = htmlspecialchars($_POST['name']);
$age = htmlspecialchars($_POST['age']);
}
echo 'Your name is ' . $name . ' and your age is ' . $age;
?>
If you are trying to retain the values even after invalid input you can just echo the input in value attribute of the input field.
Hey i have having a problem i just found working with session i am using at the moment firefox 23 but i have check that on some other browsers as well.
I have created a simple code where i have created a form and just opened a session and i have noticed that once i have submit the form and then click on "Go Back" to return to the page the info i have inserted is not saved on the browser.
Normally when you submit a form once you go back the data you have entered is saved and you can just edit the inputs and resent it but when i have used session_start() on the page that function stopped working.
Well i am guessing maybe the browser save the form data in sessions as well and once i use it in php it's somehow effect the normally way the browser work.
I hope someone know how i can fix that i know you are able to save sessions with html5 and javascript now but i would rather do that with php.
Attached below is the code i have been using:
<?php
session_start();
// store session data
$_SESSION['name']= "name";
?>
<form method="post" action="index.php">
<input type="text" name="email" placeholder="Email" /><br />
<input type="text" name="name" placeholder="Name" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
The browser refilling the form is simply that, the browser. This is not something you should rely upon for form re-population.
Your PHP code does not attempt to refill the form by printing anything within the input value="" attributes.
Generally when a form is submitted a programmer will validate the submitted values, store them in some fashion (the session is fine) and if they need them to reappear on the form they will print those values back out like I described.
I think you want to put the CORRECT fields back into the form values and blank out the incorrect ones. You don't have to use sessions:
<?php // formx.php
// accept POST variables
$fld1 = isset($_POST['fld1']) ? $_POST['fld1'] : "";
$fld2 = isset($_POST['fld2']) ? $_POST['fld2'] : "";
// edit variables
$errmsg = "";
if (!$fld1 == "") { if($fld1 <> "1") { $errmsg .= "fld1 is not 1<br />\n"; $fld1 = ""; } }
if (!$fld2 == "") { if($fld2 <> "2") { $errmsg .= "fld2 is not 2<br />\n"; $fld2 = ""; } }
if ($errmsg == "") { $errmsg = "Values accepted"; }
// output form
$body = <<<EOD
<html>
<body>
<div>%s</div><!-- errmsg -->
<form name="formnm" action="formx.php" method="post">
Enter "1" <input type="text" name="fld1" value="%s" /><br />
Enter "2" <input type="text" name="fld2" value="%s" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
EOD;
printf($body, $errmsg, $fld1, $fld2);
?>
I have been using PHP for a while now and I have always wondered how to represent a single form to handle updates and inserts into a database. At the present, I am using 2 seperate forms to do this and they both have basically the same information and textboxes, etc. I know there is a better way of handling this but I'm not sure what that is.
I have tried to use a single form in the past but the html mixed with the php looks terrible and is really hard to maintain. I am after "clean" and neat.
Can someone please put me on the right track.
One of the things that I have to use are POST values if the user submits the form and the validation didn't pass, the refresh should not wipe out the already entered values.
You could use a single form, with a hidden field for id. If this field is set - then you should update the $_POST['id'] record with the rest of the form. If the field is not set (that is, it has value=""), you should insert the form data to a new record.
You'll set the id field according to the action, for example /data/edit/1 will set the id field to , and/data/new` will not set value to it.
For example, your view could be
<form action="/data/edit/1">
<input type="hidden" value="<?php echo $data->id; ?>" />
<input type="text" value="<?php echo $data->name; ?>" />
</form>
In case of a new record, call your view with the following data
$data->id = '';
$data->name = '';
In case of a known record, simply init the $data object with the data
$data->id = $record_id;
$data->name = $record_name;
This is how I would probably do it without using any other frameworks/libraries etc. It is basically what Elazar Leibovich said.
<?php
//id is zero or a record id depending on whether updating or inserting
//an existing record could be edited using edit.php?id=10
//if the id GET parameter is omitted a new record will be created
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
$error = '';
if ($id) {
//this array would be in the same format as the one below
$record = fetchRecordFromDb($id);
} else {
$record = array( 'field1' => 'default value', 'field2' => 'some other default' );
}
//allow POST data to override what is already in the form
foreach ($record as $key => $value) {
if (isset($_POST[$key])) {
$record[$key] = $_POST[$key];
}
}
if (isset($_POST['submit'])) {
if (!validateForm()) {
$error = 'Some form error';
} else {
if ($id) {
updateRecord($id, $record);
} else {
insertRecord($record);
}
//ok, redirect somewhere else
header('Location: http://somewhere');
exit();
}
}
?>
<form method="post">
<?php echo $error; ?>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($record['field1']); ?>"><br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($record['field2']); ?>"><br />
<input type="submit" name="submit">
</form>