Rectangle 27 0

Best way to fill in a PHPHTML form with user specific mysql saved data?

<form method="post">
 <input type="hidden" name="Character[id]" value="<?= intval($char['id']) ?>">
 <input name="Character[name]" value="<?= htmlentities($char['name']) ?>">
 <input name="Character[age]" value="<?= htmlentities($char['age']) ?>">
 <input type="submit">
function loadCharacter($id) {
    ... $result = result from: SELECT id, name, age FROM Characters WHERE id = ?
    ... return first (should be only) row of $result
function saveCharacter($char) {
    if (empty($char['id'])):
        ... do insert
        ... $char['id'] = last insert ID
        ... do update

    // return the saved char; inserting would have added an ID
    return $char;
if (isset($_POST['Character'])) {
    $char = saveCharacter($_POST['Character']);
elseif ( ...the user already has a character id... ) {
    $char = loadCharacter(...character id...);
else {
    // first time on the page, and there's no saved character
    // give $char the right field names, to prevent notices
    $char = array('id' => null, 'name' => null, 'age' => null);

(If the names are different, you'll need to convert. You can usually have the DBMS do this for you; google for "SQL column alias" for more info.)

(Note, a lot of stuff has been omitted. I don't know or care what database you're using, or how you do validation; the important part is the form processing, and that works regardless of DB.)

...and a loadCharacter to SELECT that row, and return its contents with the same names as you had them in the form. (Keeping the form and database field names consistent helps quite a bit here. If the two use the same names, you can just return the row directly.)

And when you include the form from above, it will put $char's values in the proper elements.

Let's have a saveCharacter that would take that info and save it as a row... (pseudocode lines start with ...; fragments look this...)

Let's take a simple example. Let's say we have a table Characters, with fields id, name and age.

One of the cleaner ways (IMO) to provide an edit form for this table, is to have the form assume there's an array (let's call it $char) that has these fields. The main code would get this array from wherever, be it from the form fields or from the database.

When the form is submitted, $_POST['Character'] would be an array, and contains all the info the form submitted about the character.