I have a form that will send data via POST. I want that data to go to different MySQL tables based on the POST "name."
What I have so far is a while loop for the form fields that will name each input in the format: "name"{}$id. I thought that using {} as a delimiter I could then use explode() and use a conditional statement to select which table the data should go to.
Is this the best way to do this? The issue I'm having is also calling the name, since using foreach for example on POST will just return the values and not the names. I have enclosed the code below:
<?php while ($cred = mysql_fetch_array($credentials_process)) { ?>
<div class="edit-profile-background-inputs">
<span><input type="text" name="cred{}<?php echo $cred['id']; ?>" value="<?php echo $cred['credentials']; ?>" /></span>
<span style="margin-left:10px;"><a href="<?php echo "background.php?cred=".$cred['id']; ?>">Remove</a></span>
</div>
<?php } ?>
I need those fields named cred{} to go to credentials table, those named edu{} to go to the education table, etc.
<input type="text" name="cred[<?php echo $cred['id']; ?>]"...
<input type="text" name="edu[<?php echo $edu['id']; ?>]"...
in PHP
$insert=array();
foreach ($_POST['cred'] as $k=>$v)
{
$insert[$k]=mysql_real_escape_string($v); // yes I know mysql is being depreciated
}
$sql='INSERT INTO cred ('. implode(',', array_keys($insert)).') VALUES ('. implode(',', $insert).');
repeat for $_POST['edu']
If your results set is such that you're outputting more than one row with the same key
$i=0;
while ($cred = mysql_fetch_array($credentials_process)) { ?>
<input type="text" name="cred[$i][<?php echo $cred['id']; ?>]"...
...
$i++;
}
If you print_r($_POST)
from that you'll be able to figure out how to deal with them.
NB. For safety I would also make sure only the expected posted vars get used
$allowed=array('cred_id', 'cred_something', 'etc');
foreach ($_POST['cred'] as $k=>$v){
if (!in_array($k, $allowed)) continue;