I am struggling to find out the syntactically correct wa开发者_如何学编程y in which to add on more variables and rows to these statements:
/* WANT TO ADD ON FIVE MORE $_POST[''] */
if(isset($_POST['check_prof']) && $_POST['check_prof'] == 'checked') {
$check_prof = "checked";
}else{
$check_prof = "unchecked";
}
/* SAME HERE, WANT TO ADD THE OTHER FIVE IN HERE AS WELL */
$query = "UPDATE `Users` SET `check_prof` = '" . $check_prof . "' WHERE `id` = '" . $auth->id . "' LIMIT 1";
mysql_query($query,$connection);
$auth->refresh();
}
Do you mean like this?
$fields = array('check_prof', 'check_this', 'check_that', 'check_whatever');
foreach($fields as $field){
isset($_POST[$field] && $_POST[$field] == 'checked')){
$$field='checked';
} else {
$$field='unchecked';
}
$query = "UPDATE `Users` SET `$field` = '" . $$field . "' WHERE `id` = '" . $auth->id . "' LIMIT 1";
mysql_query($query,$connection);
$auth->refresh();
}
By the way, instead of storing "checked" and "unchecked" in your database (as a varchar) you can store it as type tinyint(1) and just use a 0 or a 1. It will take up way less space.
Another thing, this will do a separate query for each field. It's more efficient to write one query to do the changes for all fields if performance is a concern.
Assuming I'm understanding what you mean, try this:
<?php
$arr = array('check_prof' => 'unchecked',
'check_student' => 'unchecked');
foreach($arr as $field => $checked) {
if (isset($_POST[$field]) && $_POST[$field] == 'checked') {
$arr[$field] = 'checked';
}
// I don't know where $auth is coming from
$query = "UPDATE `Users` SET `$field` = '" . $arr[$field] . "' WHERE `id` = '" . $auth->id . "' LIMIT 1";
mysql_query($query,$connection);
$auth->refresh();
}
?>
You would simply need to add fields as needed to $arr
for it to loop through.
精彩评论