How to get Value from form (symfony 1.4) - php

I've made complex form which is valid in action. I'd like to get value from this input to save file on server.
<input type="text"
name="produkty[pForm][1][caption]"
id="produkty_pForm_1_caption" />
I've tried something like that:
$this->form=new ProduktyForm();
if ($request->isMethod(sfRequest::POST))
{
$this->form->bind($request->getParameter('produkty'),$request->getFiles('produkty'));
if ( $this->form->isValid())
{
$file=$this->form->getValue('produkty[pForm][1][src]');
$filename='u';
$extension = $file->getExtension($file->getOriginalExtension());
$file->save(sfConfig::get('sf_upload_dir').'/'.$filename.$extension);
}
}
But it doesn't work.

'produkty' is the name of your form. Are you using a subform to capture an array of possible files to be input?
You could get the values of the entire form by doing this.
$form_vals = $this->form->getValues();
Then you could could see what variables you have by your output.
You'll probably be able to get the input this way.
$caption = $form_vals['pForm'][1]['caption'];
this is working fine but how to fetch the values from file attributes . i cant get the values from file input
my main form name is slide and subform is mslide
here is the my code
$this->multiSlideForm->bind($request->getParameter('slide'), $request->getFiles('slide'));
$form_vals = $this->multiSlideForm->getValues();
echo $form_vals['mslide'][0]['slide_name']; //working
echo $this->multiSlideForm->getValue('[mslide][0][file_name]')->getOriginalName(); //not working

Related

How to avoid using $_GET to extract data from the URL

I am currently working on a form that requires few fields to be filled by the user and few based on the selection made by the user on the previous page. The URL looks like below:
http://localhost:8080/series/dynamics/admin/cleanURL/post.php?subgroup=redapple&adverid=254427035
where redapple is the $_GET variable. However what I wd like the url to look like is ;
http://localhost:8080/series/dynamics/admin/cleanURL/post.php?adverid=254427035
i.e. no info about subgroup selection in the url. But still would like to have the subgroup field to be filled with the choice made by user.
My php looks like this:
<?php require('../config/connection.php');
if(isset($_POST['variable'])){
$values = mysqli_real_escape_string($dbc, $_POST['variable']);
$query = "SELECT * FROM prdct_categories WHERE product = '$values'";
$result = mysqli_query($dbc, $query);
$rand = rand(0, 1000000);
$html = '<ul>';
while($row = mysqli_fetch_assoc($result)){
$clickable_url = 'post.php?subgroup='.$row['subgroup'].'&advertid='.$rand;
$html .= '<li class="nav">';
$html .= ''.$row['subgroup'].'';
$html .= '</li>';
}
$html .='<ul/>';
echo $html;
mysqli_close($dbc);
}
If you don't want to pass information in the URLs then you'll need to use a Cookie or Session. Post the form to a page that gathers the posted data and then set a session or cookie before redirecting the user to the correct page.
http://php.net/manual/en/features.cookies.php
Or
http://php.net/manual/en/features.sessions.php
You can also use a POST request, for example, if I made a form like:
<form action="form_url.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
In form_url.php, I could access the variables like so:
<?php
var_dump($_POST);
The benefit of using POST over GET is that in can be encrypted over SSL whereas all parameters inside a GET request are encoded and visible in the URL. Also, since the URL can only be 265 characters max, that's also the limit of the data size.
If you want to upload something such as an image, you'll want to use a file input in a form field (like the one above) so that data can be sent over a file-stream instead of a url.
EDIT:
If you want another way to just get the url data, you don't have to use get. The full URL can be given by:
<?php
var_dump($_SERVER['HTTP_HOST']);
var_dump($_SERVER['REQUEST_URI']);
Although the REQUEST_URI is probably what you want. Note that any data passed through here can also be obtained from GET, but you don't have to use GET to get the data. You would then want to parse the URL with something like:
<?php
var_dump(explode('\', $_SERVER['REQUEST_URI']));

How to populate input type file value from database in PHP? [duplicate]

This question already has an answer here:
Echo the value inside html input type=file
(1 answer)
Closed 8 days ago.
I am writing the code for editing a form that contains an input file field. I am getting all the values pulled from database for different field types but the file type input does not show its value.
I have a code that looks like this:
<input class="picturebox" id="logo" name="userfile" value="<?php echo $discount_details->picture_name;?>" />
But actually in rendered view value attribute is null for userfile field.
How do I load the value of input type when someone is editing the form and does not want to alter the picture entered earlier by him upon edit.
you can give the value attribute to input file type
if you want to show the file content while updating form you can show it in separate tag
like:
<input type="file" /> <span><?php echo $row[column_name]?></span>
here you should consider one thing
if the use is selected new file to upload you can update the column else the use not selected any thing just updated other content without file you should update the column name with old file name.
$file = $_FILES['file']['name'];
if($file!="") {
move_uploaded_file($_FILES['file']['tmp_name'],'/image/'.$file);
} else {
$file = $oldfile;
}
You can just make value field empty and show your old image at just up of that input field(or below).then check after submitting form, if $_POST['userfile'] is empty don't update table.picture_name.
The simple trick is that ; give an id to the tag
<input type="file" name="file" /> <span name="old" value="<?=$row[column_name]?>"><?php echo $row[column_name]?></span>
Then in PHP make it like this:
$oldfile = $_POST['old'];
$file = $_FILES['file']['name'];
if($file!="") {
move_uploaded_file($_FILES['file']['tmp_name'],'/image/'.$file);
} else {
$file = $oldfile;
}
you can write this way
Step 1: Fetch your image in a variable. like this $pimg = $result['pimage'];
Step 2: write html code for add file. <input type="file" name=""image">
Step3: in PHP fetch the file if image upload by user. like this $pimage = $_FILES['images']['name'];
Step 4: now check if the user uploaded the file or not.
if(empty(file name)){
if yes then update image it.
}else{
if no then priviously uploaded image use it.
}

SQL Query onsubmit - change existing results

Good morning everyone,
I have a page that performs a default connection to database, search and looped output of data to the page by applying a template for each result in the table using this code:
<?php
$result = mysqli_query($con,"SELECT * FROM XXX WHERE Type='ABCD';");
while($row = mysqli_fetch_array($result))
{
include('includes/template-1234.php');
}
mysqli_close($con);
?>
On the same page I have a simple HTML search box:
<div id="srch-form">
<form>
<input name="srch-box" type="text" id="srch-box" size="45" onClick="this.value='';" onFocus="this.select()" onBlur="this.value=!this.value?'Enter Product Name or SKU#':this.value;" value="Enter Product Name or SKU#">
<input type="submit" name="srch-btn" id="srch-btn" value="Search">
</form>
</div>
Because I am just learning PHP - how do I set this up so that the default action still occurs on page entry, but - onsubmit of something in the searchbox the data in the current page is replaced by the results of the submission? I guess I'm getting confused over the fact that since I have already assigned a value(s) to $result to get the default output, If the value of $result is changed by the search form, does PHP automatically refresh the page when the value of $result is changed? - Sorry if this is a simple thing.
First, you'll have to add an action (which file to refer when submitted) and preferably a method-type in your form-tag. You will also have to include value of $productName (given from server-side php) inside of your html (look at value attribute)
Do something like this:
html-form: (Examplefile: yourhtmlform.php)
Then in your php-file get value from a specific element like this:
<?php
//File querydb.php (example filename)
//Form is submitted and srch-box is set (only set when form is submitted)
if(isset($_POST['srch-box'])) {
$type = $_POST['srch-box']; //Get value of input-element
}
else {
$type = 'kingkong'; //Default type to search
}
$prepareQuery = mysqli_prepare($dbConnectionLink,"SELECT * FROM XXX WHERE Type=:type");
//...code to fetch results..
//You get a productName (or SKU) from db
if (isset($result['product_name'])) {
$productName = $result['product_name']; //or whatever your column is called
}
else {
$productName = '';
}
include('yourhtmlform.php'); //Observe that it must be php to echo out value of $productName in this included file
I noticed you didn't use prepared-statement. Look for more information on prepared statements here: http://www.php.net/manual/en/mysqli.prepare.php (use them!)
I hope this will help you somehow :-)

php - filling in form fields from database values

I'm trying to "pre-fill" (not sure if there's a technical term for this) form fields with values that the user has previously entered in the database. For this example it's a City and State. When the user loads the page to edit options, these values (which they have previously entered) will automatically be in the text boxes.
<tr><td>City</td><td><input type="text" name="city" value="<? $city = "usercity"; echo $formValue->location('$city'); ?>"></td>
<td>State</td><td><input type="text" name="state" value="<? $state = "userstate"; echo $formValue->location('$state'); ?>"></td>
Is there any way to set a value based on the input (from the boxes above)? If it was something like function location($input) I would know how to, but when there's nothing in the parenthesis, is there any way to set a value?
function location(){
$userid = $_SESSION['userid'];
$server = 'localhost';
$user = 'root';
$password = '';
$connection = mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db(testdb, $connection) or die(mysql_error());
$result = mysql_query("SELECT '$location' FROM userinfo WHERE userid = '$userid'");
$user_data = mysql_fetch_array($result);
if($location =='usercity'){
$userlocation = $user_data['usercity'];
return $userlocation;
}
else
$userlocation = $user_data['userstate'];
return $userlocation;
}
Instead of thinking about this from a global perspective think about the problem in it's context.
Your starting point (from the server perspective) is that an HTTP GET request has come in from a client for this page, or a client is returning to this page from after a POST request. In either case, the server has located the "resource" (the PHP script) that should handle this request and dispatched it by loading the PHP interpreter with the script file.
The context at this point is at the first line of the script; at the point where the interpreter has just finished parsing and started executing. Ask yourself: does the current request include an active session identifier? If it does have an active session, then check to see if the client has filled in this form before and if they have, substitute the default form values they've previously submitted for the normal form default values. If the client does not have an active session or has not used the form before then show a blank form with default values as needed.
Tip: Consider using this technique to debug your code. Pick a line in your code and place a mental "break point" at that place. Ask yourself: what is the context of this script at this point? What variables are defined? What is the server state? What is the client expecting? Once you have an answer to those questions, writing the code is simple.
From what I see in your code you have the variable in single quotes:
$city = "usercity"; echo $formValue->location('$city');
remove the single quotes, as it will pass '$city' as is, not the value of $city. Try
$city = "usercity"; echo $formValue->location($city);
to make it clearer:
$city = "usercity";
print ('$city'); // will print $city
print ($city); // will print usercity
My last few projects had forms all over the place and telling php to fill out the forms each time was a pain in the arse.
For my current project, I kept the input names the same as the mysql field names. Makes submitting and populating way easier.
When it comes to populating the forms, I use some ajax (jQuery used all over the project so using jquery's ajax() function;
FORM
<form>
<input name="field_one" type = "text" >
<input name="field_two" type = "text" >
<input type="button" value="Send">
</form>
I put a conditional statement at the top of the doc along the lines of:
<?php if($_POST['update']){
$query=mysql_query("SELECT * FROM table WHERE unique_id='$id' LIMIT 1");
echo json_encode(mysql_fetch_assoc($query));
exit;
} ?>
Lets say you have a list of items you want to be able to click on and edit (populate the form with it's corresponding data). I assign it a data- attribute and fill it with it's unique id, normally an AI PRIMARYKEY eg:
while($r=mysql_fetch_assoc($data)){
echo "<li data-unique_id=\"\">$r[name]<span class="edit">edit</span></li>";
?>
$('.edit').click(function(){
var toget = $(this).parent().data('unique_id');
$.ajax({
url:'here so it sends to itself',
data:'update='+toget,
success:function(data){
for (var key in data) {
if (data.hasOwnProperty(key)) {
$('input[name="'+key+'"]').each(function(){
$(this).val(data[key]);
});
}
}
}
});
There's a little more work required for <select>, <textarea>, checkboxes, but same general idea applies, (I threw in a couple of if statements, but it could probably be handled way better)
I could probably explain this better, but I hope you get the idea and i've been of some help.
FYI
my inserts are like...
foreach($_POST as $k=>$v){
$v=mysql_real_escape_string($v);
$fields.=" `$k`,";
$vals.=" '$v',";
}
$fields=substr($fields,0,strlen($fields)-1);//to get rid of the comma :)
$vals=substr($vals,0,strlen($vals)-1);//and again
mysql_query("INSERT INTO ($fields) VALUES ($vals)");

How do I create a server-side form submission script that has client-side characteristics?

I'm working in PHP to build a form. I know how to display the form and then take submitted values from the $_POST variable, and I know how to validate those variables and display a "Thank You" or an "Error" page depending on the input.
What I don't know how to do, though, is create a client-side-like system wherein despite having my users hit a "back" button a separate screen I can then take the information I gathered from the first submission and display dynamic error messages like "Please provide a valid email address" or "First name is a required field" next to the fields that were entered incorrectly. I'd also like to retrieve any previously submitted data that was valid and have it populate in the form so users don't get frustrated by losing everything they entered.
What is the right approach to accomplishing something like this in PHP? I originally thought if I could pass back an array of error messages with an input type="hidden" tag I could then pull my values and display messages dynamically with PHP, but I keep getting stuck in that approach.
You could add the errors a php session, but this creates issues for users who have multiple browser tabs open.
My preferred method is to have the form submit to the same page and put the errors directly on that page so the user does not have to click the back button. That way you can highlight the fields directly in the form (make the background or outline red or something similar.)
<input type="text"
<?php (empty($_POST['field']?'style="backgroung-color: red;"':''))?>
name="field" value="<?php echo $_POST['field']?>" />
You can put <input type="text" name="field" value="<?php echo $_POST['field']?>" /> to get the old value.
Because the web is, by definition, stateless, there is no really good way to track what the user does when they hit the back button. There are hacks that work using a hidden iframe, but that is way more trouble that what you are looking for.
Don't mix client logic with server logic. The exact same script can output the form and take it's input. In case input successfully validates, it goes on. If not, it will display the form again, this time with error messages and the already-entered data.
Next time the user submits the form, validation starts again until it passes successfully.
So you extend the form with input values and error messages in the first place, but you only display them if flagged/set.
This can be done just with additional variables next to $_POST - or if you like it - by using a complete form abstraction from a framework, like zend framework (which might be overhead for what you like to do) or just with a library/component like the popular HTML_QuickForm2.
Edit:
This is some very bare code to demonstrate the overall methodology, if you use a library it is much nicer (and you don't have to code it instead you can concentrate on the actual form like the definition on top). This code is more for reading and understanding the flow than for using, I quickly typed it so it (most certainly has) syntax errors and it's not feature complete for a full blown form. This one has only one email field and is even missing the submit button:
/* setup the request */
$request->isSubmit = isset($_POST['submit']);
/* define the form */
$form->fields = array
(
'email' => array
(
'validate' => function($value) {return filter_var($value, FILTER_VALIDATE_EMAIL);},
'output' => function($value, $name) {return sprintf('<input type="text" value="%s" id="%s">', htmlspecialchars($value), htmlspecialchars($name)},
'default' => 'info#example.com',
),
);
/**
* Import form data from post request
*
* #return array data with keys as field names and values as the input strings
* or default form values.
*/
function get_form_post_data($form, $request)
{
$data = array();
foreach($form->fields as $name => $field)
{
$data[$name] = $field->default;
if ($request->isSubmit && isset($_POST[$name]))
{
$data[$name] = $_POST[$name];
}
}
return $data;
}
/**
* Validate form data
*/
function validate_form_data($form, $data)
{
foreach($form->fields as $name => $field)
{
$value = $data[$name];
$valid = $field['validate']($value);
if (!$valid)
{
$form->errors[$name] = true;
}
}
}
function display_form($form, $data)
{
foreach($form->fields as $name => $field)
{
$value = isset($data[$name]) ? $data[$name] : '';
$hasError = isset($form->errors[$name]);
$input = $field['output']($name, $value);
$mask = '%s';
if ($hasError)
{
$mask = '<div class="error"><div class="message">Please Check:</div>%s</div>';
}
printf($mask, $input);
}
}
// give it a run:
# populate form with default values -or- with submitted values:
$form->data = get_form_post_data($form, $request);
# validate form if there is actually a submit:
if ($request->isSubmit)
{
validate_form_data($form, $form->data);
}
# finally display the form (that can be within your HTML/template part), works like echo:
display_form($form, $form->data)
Use the form to submit to the same page, and if the form validates, use a header to redirect the user into the thank you page.
header("Location: thank-you.php");
If the form fails validation, you could easily display all the errors on the same page.

Categories