I have some sets of form elements created dynamically which I use on page creation.
<?php for ($i=0;$i<6;$i++){ ?>
<div id="hold">
<input type="text" name="slinks<?php echo $i; ?>" value="<?php echo $slinks[$i]; ?>" placeholder="Input Link Name" />
<select name="cat<?php echo $i; ?>">
<option value="" selected="selected">Select Category</option>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
<div class="clear"></div>
</div>
<?php } ?>
I am able to insert the values into my MySQL database. I want to populate values into these fields on page edit. My problem is how to bind values into the form elements assuming my database fetched sample values as:
<?php
$query = $dhb->prepare("SELECT * FROM table2 WHERE $col = ?");
$query->execute(array($id));
$amt = $query->rowCount();
$rows = $query->setFetchMode(PDO::FETCH_NUM);
while($z = $query->fetch()){
print_r($z);
}
?>
And the output from print_r()
Array
(
[0] => 3
[1] => Item3
)
Array
(
[1] => 1
[2] => Item1
)
Array
(
[0] => 2
[1] => Item2
)
lets assume $edit=true, means it is in edit mode. then you php code will be.. assuming you have ever set different
<?php
$query = $dhb->prepare("SELECT * FROM table2 WHERE $col = ?");
$query->execute(array($id));
$index = array();
$value = array();
$amt = $query->rowCount();
$rows = $query->setFetchMode(PDO::FETCH_NUM);
while($z = $query->fetch()){
print_r($z);
$index[] = $z[0];
$value[$z[0]] = $z[1];
}
?>
and you html code will be...
<?php if($edit && is_array($index) && is_array($value)){
$flagForNewField = false;
for ($i=0;$i<6;$i++){
if(in_array($i,$index){ ?>
<div id="hold">
<input type="text" name="slinks<?php echo $i; ?>" value="<?php echo $slinks[$i]; ?>" placeholder="Input Link Name" />
<select name="cat<?php echo $i; ?>">
<option value="" selected="selected">Select Category</option>
<option value="1" selected="<?php if($i==1){echo "selected";}else{} ?>">Item 1</option>
<option value="<?php if($i==2){echo "selected";}else{} ?>">Item 2</option>
<option value="<?php if($i==3){echo "selected";}else{} ?>">Item 3</option>
</select>
<div class="clear"></div>
</div>
<?php
}else{
$flagForNewField = true;
// ccase if input in not in fetched result
}
}
}else{
for ($i=0;$i<6;$i++){ ?>
<div id="hold">
<input type="text" name="slinks<?php echo $i; ?>" value="<?php echo $slinks[$i]; ?>" placeholder="Input Link Name" />
<select name="cat<?php echo $i; ?>">
<option value="" selected="selected">Select Category</option>
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
</select>
<div class="clear"></div>
</div>
<?php }
}?>