Hi,

I want to create a dynamic form, relative with the table i'm working with.

I'm selecting the columns from a certain table:

<?php
    $tableColumns = $dbConnect->query("SHOW COLUMNS
                                       FROM projects 
                                       WHERE Field NOT IN ('ID');");
?>

Then i want to get each result's value (according to the ID selected) and put it in an array:
URL: localhost/index.php?page=form&action=update&id=1

<?php
    $values[]="";

    if($_GET['action']=='update')
    {
        $selectTableResult=$dbConnect->query("SELECT *
                                              FROM ".$table."
                                              WHERE `ID`=1");

        while($rowTable=$selectTableResult->fetch_assoc())
        {
            print_r($values[] = $rowTable);
        }
    }
?>

What i want to do is write something like this:

<div class="form-group">
    <label>Text Input</label>
    <input class="form-control" name="textBox" type="text" value="<?php echo $value[1] ?>">
</div>

Like this, if i want to update an Item, the value of the input is "Test" (or whatever) and if i want to add an Item the value is empty.

Can someone help me, please?

Thanks!

Dani AI

Generated

Brief summary: generate the form from the table schema and use column names as keys so update vs create is automatic. Fetch the column list (skip the auto-increment PK), fetch the row when action is update, then render inputs named like data[column_name]. That makes server-side processing a simple associative-array operation instead of relying on numeric indexes.

Notes on the existing replies: was close but appending the whole row into a numeric $values[] makes mapping awkward. 's idea to post arrays is the right direction; prefer the column-name keys (for example data[title]) rather than numeric keys. 's AJAX suggestion is useful only when fields must appear live for other users — it is not necessary to prefill an edit form.

Example (safe, modern pattern using PDO and INFORMATION_SCHEMA):

$stmt = $pdo->prepare(
  "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
   WHERE TABLE_SCHEMA = :db AND TABLE_NAME = :table AND COLUMN_NAME <> 'ID'
   ORDER BY ORDINAL_POSITION"
);
$stmt->execute([':db' => $dbName, ':table' => $table]);
$cols = $stmt->fetchAll(PDO::FETCH_COLUMN);

$row = [];
if (!empty($_GET['id'])) {
  $r = $pdo->prepare("SELECT * FROM `$table` WHERE `ID` = :id LIMIT 1");
  $r->execute([':id' => (int) $_GET['id']]);
  $row = $r->fetch(PDO::FETCH_ASSOC) ?: [];
}

foreach ($cols as $col) {
  $val = isset($row[$col]) ? htmlspecialchars($row[$col], ENT_QUOTES) : '';
  echo "<div class=\"form-group\">\n<label>".ucwords(str_replace('_',' ',$col))."</label>\n";
  echo "<input class=\"form-control\" name=\"data[$col]\" type=\"text\" value=\"$val\">\n</div>\n";
}

Simple POST handling (prepared statements, associative input):

$input = $_POST['data'] ?? [];
if (!empty($_POST['id'])) {
  $fields = array_keys($input);
  $set = implode(', ', array_map(function($c){ return "`$c` = :$c"; }, $fields));
  $sql = "UPDATE `$table` SET $set WHERE `ID` = :id";
  $input['id'] = (int) $_POST['id'];
  $pdo->prepare($sql)->execute($input);
} else {
  $cols = array_keys($input);
  $place = implode(', ', array_map(function($c){ return ':'.$c; }, $cols));
  $sql = "INSERT INTO `$table` (`".implode('`,`',$cols)."`) VALUES ($place)";
  $pdo->prepare($sql)->execute($input);
}

Cautions and tips: always use prepared statements to avoid SQL injection, escape values for HTML (htmlspecialchars) to avoid XSS, validate/sanitize the id, skip columns that should not be editable (passwords, computed columns), and map DB data types to appropriate input types (number, date, textarea). This pattern keeps add (empty defaults) and edit (prefilled values) behavior straightforward.

Recommended Answers

All 2 Replies

You could let Ajax do this. You would then repeat certain PHP function over and over again, with space of around 2 seconds, wait until PHP finds something new in the database and produces output, and then create a new field (with JavaScript) and make it's content, the content that PHP has provided you.

<input name="textBox[<?php echo $myid; ?>]"

when you post this you'll get an array for each form element with key = id
$_POST['textBox'][$myid]

commented: nice one +4
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.