how to handle a large php mysql $_POST UPDATE/INSERT
I'm trying to do something like this so I don't have to type out all of my post entries. I can't seems to get this to w开发者_开发技巧ork though.
edit: added some changes.
foreach($_POST as $key => $value)
{
$key = "'".mysql_real_escape_string($key)."'";
$value = "'".mysql_real_escape_string($value)."'";
$qstring = "UPDATE load_test SET ".$key."=".$value." WHERE Id = '".$_POST['id']."'";
mysql_query($qstring);
}
What you are trying to do here is incredibly, dangerously insecure.
// List the fields that may be updated here
$expectedFields = array('fielda', 'fieldb');
// Updated values to be stored here
$updates = array();
// Generate the update strings
foreach ($_POST as $key => $value) {
if (in_array($key, $expectedFields)) {
$updates[] = "`$key` = '".mysql_real_escape_string($key)."'";
}
}
// Do all updates at once
$qstring = "UPDATE load_test SET " . join(', ', $updates) . " WHERE Id = '" . mysql_real_escape_string($_POST['id']) . "'";
mysql_query($qstring);
This improves several things
- All updates happen in one query, rather than one per field
- The fields are validated (and sanitised, as they're only accepted if they're in the valid list)
- The ID value is also sanitised
foreach($_POST as $k=>$v){
@$select.=" `".mysql_real_escape_string($k)."` = '".mysql_real_escape_string($v)."',";
}
$select = rtrim($select,',');
$select = "UPDATE load_test SET".$select." WHERE id=".$_POST['id'];
mysql_query($select) or die(mysql_error());;
try this is alot faster then the previous one you want need to do more then 1 query and other then that i think it's safe enough to escape the key since trying updating a column that doesn't exist doesn't get you anywhere, and trying to make an injection escaping will protect you from that, you should though make sure the id is numeric
精彩评论