Reputation: 297
Okay so a while ago I asked this question
How can I grab and store multiple $_POST Variables in a for each loop?
And the response was perfect, and it worked for inserting the values into the database just fine. However, I now am revisiting this project and I want to UPDATE only one field in the database, specifically the post test field for that particular user, using the same or similar method. How would this be possible?
Currently I have something along the lines of this.
$SGUID = the Unique User ID
$SGpost = the field i want to update
$SGQID = question ID
Obviously, this does not work.. and my code is extremely sloppy as I tried to replace and edit this along the way. Any ideas?
foreach ($_POST as $p => $v)
{
if (preg_match("/^Q\d+$/",$p)) { //$_POST variables with Q1, Q2, Q3, etc etc
$query_3 = mysql_query("UPDATE SGresults SET SGpost = '$p', SGpostCheck = 1 WHERE SGUID = '$SGUID' AND SGQID = '$p'") or die('Error: '.mysql_error ());
$SGQID++;
}
}
}
When I echo out $p I get the following Q11 Q21 Q31 Q44 Q54 Q63 Q73 Q83 Q93 Q103 Q111 Q122 Q131 Q142 Q153 Q163 Q17
Which is what I want, except without the Q, and just the second value. So for example if it was 'Q163' I just want to insert the '3' part into SGpost WHERE the database is 'Q16'.
Thanks again again! Any help would be greatly appreciated!
EDIT:: Looked over my code again and changed some values around...The following DOES work, so I think I will stick with it. Unless bad code? Thanks again for your suggestions.
$SGQID= 1;
foreach ($_POST as $i => $v)
{
if (preg_match("/^Q\d+$/",$i)) { //$_POST variables with Q1, Q2, Q3, etc etc
// Here we insert value $v to database
if ($SGtestType == "Post-test") {
$query_post = mysql_query("UPDATE SGresults SET SGpost = '$v', SGpostcheck ='1' WHERE SGQID = '$SGQID' AND SGUID = '$SGUID' ") or die('Error 109: '.mysql_error ());
$SGQID++;
// ^^ increments the question value everytime an insert is made
//last 2 fields is check for existing value.. or if not exists.. 1 if it does.
}
}
}
}
Upvotes: 0
Views: 172
Reputation: 2156
Assuming you trust the post data to not be an xss attack:
foreach ($_POST as $p => $v)
{
if (preg_match("/^Q(\d+)$/",$p, $matches)) { //$_POST variables with Q1, Q2, Q3, etc etc
$id = (int)$matches[1];
$query_3 = mysql_query("UPDATE SGresults SET SGpost = '$id', SGpostCheck = 1 WHERE SGUID = '$SGUID' AND SGQID = '$id'") or die('Error: '.mysql_error ());
$SGQID++;
}
}
}
Upvotes: 2