0

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;
    }
5
  • $city = "usercity"; echo $formValue->location('$city'); <-- where is that usercity value coming from? Commented Jan 7, 2012 at 22:12
  • usercity is the name of the column in the database. If I just put $formValue->location('usercity') then how am I supposed to use that input in the function? Commented Jan 7, 2012 at 22:20
  • what's not working with your current setup? are you getting errors? also you could return the $user_data array, right now you are sending an unecessary query to the db. Commented Jan 7, 2012 at 22:33
  • I'm sorry, I am not sure I clearly understand your issue (I saw a mistake in your code stated in my answer below). Do you need a better way to implement this or are you experiencing errors? (if you are using the code you are showing us it won't work - see my answer). Commented Jan 8, 2012 at 0:32
  • Is there any way to set an input based on the way I attempted to describe above? (I edited it from the original, so this is a different question from my original) Commented Jan 8, 2012 at 5:44

3 Answers 3

0

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I am able to fill the fields in when I have two different functions; one for city and one for state. I'm having trouble figuring out how to use one function to do this by distinguishing between the inputs.
Drupal takes the approach of callbacks: something like hook_form_alter($form, &$state = null) where $form represents the default data structure, and $state is the current state of the form data structure (either from previous invocations or blank if it's a fresh invocation).
I figured out part of the problem, now I have another. For one of my fields I'm using a "textarea". Is there any way to fill in the values like you can with just a typical text block?
Inside of your HTML template you have <textarea name="text-data">TEXT</textarea>. For a typical form element, the value is often within a node attribute value instead, like <input type="text" name="text-data" value="TEXT"/>. Instead of substituting the data into the attribute, substitute it into the node value of the textarea. In both cases, remember to escape the output data appropriately to prevent some weird and possibly dangerous bugs.
0

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

Comments

-1

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)");

4 Comments

I wouldn't down vote this answer but I think it's examples are overkill. It also doesn't escape output, so it could be vulnerable to an XSS attack.
I'll throw in a stripslashes just for you :)
@Joshua aside from that could you see any reason this would not be a good idea? Just wondering if it would be safe to continue this way, (sorry dude, not trying to hijack your question)
Besides stripslashes (or mysql_real_escape_string) not being used correctly in any way shape or form relating to any of this and besides the database insertions being vulnerable to SQL injection, and in addition none of this addressing the XSS attack vector on output? Yeah, it's a really, really, bad solution, now in multiple different ways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.