我有一个在提交时更新用户信息的表单。当前设置仅允许在填写所有字段后提交表单。我需要为每个字段创建 if 语句,如果填充,则更新,如果没有,则不要。
我在下面列出了密码字段,它描述了我想为每个字段做什么,但我不确定我是否可以在 IF 中列出多个变量,或者我是否必须编写单独的 IF 语句并从数据库中选择每一次
if($password != '') {
if($password != $password2) {
$error = '<div class="error_message">Attention! Your passwords did not match.</div>';
}
if(strlen($password) < 5) {
$error = '<div class="error_message">Attention! Your password must be at least 5 characters.</div>';
}
if($error == '') {
$sql = "UPDATE login_users
SET restricted = '$restrict',
company_name = '$company_name',
contact = '$contact',
email = '$email',
user_level = '$level',
password = MD5('$password')
WHERE user_id = '$id'";
$query = mysql_query($sql) or die("Fatal error: ".mysql_error());
echo "<h2>Updated</h2>";
echo "<div class='success_message'>User information (and password) updated for User ID <b>$id ($company_name)</b>.</div>";
echo "<h2>What to do now?</h2><br />";
echo "<a href='xxxxxxxx'>« Back to Admin Panel</a> | Go to the <a href='user_edit.php'>edit users</a> page.</li>";
}
下面是我的代码
if(trim($id) == '1') {
$error = '<div class="error_message">Attention! You cannot edit the main Administrator, use database.</div>';
} else if(trim($company_name) == '') {
$error = '<div class="error_message">Attention! You must enter a company name.</div>';
} else if(trim($contact) == '') {
$error = '<div class="error_message">Attention! You must enter a contact name.</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Attention! You have entered an invalid e-mail address, try again.</div>';
} else if(trim($level) == '') {
$error = '<div class="error_message">Attention! No user level has been selected.</div>';
}
最佳答案
I need to create if statements for each field that says if populated, update, if not, dont.
您可以随时构建 SQL 语句。类似的东西:
$sqlCols = '';
$error = '';
// Password
if ($password != '') {
if ($password == $password2) {
if (strlen($password) > 4) {
$sqlCols .= "password = MD5('".mysql_real_escape_string($password)."'), ";
} else {
$error .= '<div class="error_message">Attention! Your password must be at least 5 characters.</div>';
}
} else {
$error .= '<div class="error_message">Attention! Your passwords did not match.</div>';
}
}
// Email
if ($email != '') {
if (isValidEmail($email)) {
$sqlCols .= "email ='".mysql_real_escape_string($password)."', ";
} else {
$error .= '<div class="error_message">Attention! Your email is invalid.</div>';
}
}
if ($error == '') {
$sql = "UPDATE login_users
SET ".trim($sqlCols, ', ')."
WHERE user_id = '$id'";
// etc...
}
近期切换到PDO以提高性能并更好地防止 SQL 注入(inject)。
关于php - MySQL更新用户代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6551245/