Код, который я должен обновить, всегда обновляется с параметрами от POST
в инструкции по обновлению. Даже если они пусты и не равны нулю, это означает, что мой пользователь получает обновление с множеством пустых значений. Я хочу оператор UPDATE
в моей инструкции SQL (я использую PDO), чтобы изменить только то, что установлено, если значение не пустое и также отличается от существующего значения. В настоящее время мой код, я считаю, проверяет, отличается ли значение от существующего значения. Я хочу использовать существующий шаблон, используя bindParam
, если это возможно, но можно открыть для других решений, например. if(!isempty)
если вы считаете лучше!Как только связыватьParam, если значения POST не пустые
Вот мое обновление страницы профиля с POST
форме:
<form id="profile_form" action="updateProfile.php" method="post">
<input hidden name="userID" value="<?php echo $user; ?>"/>
<div class="col-md-9 col-lg-9 " align="center"><img alt="User Pic"
src="<?php echo $data['profile_picture']; ?>"
class="img-circle img-responsive"
style="max-width:30%;max-height:30%;">
<p>
<label for="file">Select a file:</label> <input type="file" disabled name="userfile"
id="file"> <br/>
</div>
<?php
if (isset($_POST['userfile'])){
// Configuration - Your Options
$allowed_filetypes = array('.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = './uploads/profile/'; // The place the files will be uploaded to (currently a 'files' directory).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
echo 'Your file upload was successful, view the file <a href="' . $upload_path . $filename . '" title="Your File">here</a>'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
}
?>
<div class=" col-md-9 col-lg-9 ">
<table class="table table-user-information">
<tbody>
<tr>
<td>Username</td>
<td><input type="text" disabled name="username"
value= <?php echo $data['username']; ?>>
</td>
</tr>
<tr>
<td>First Name</td>
<td><input type="text" disabled name="firstName"
value= <?php echo $data['first_name']; ?>></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" disabled name="lastName"
value= <?php echo $data['last_name']; ?>>
</td>
</tr>
<tr>
<td>Date of Birth</td>
<td><input type="text" disabled name="dob"
value= <?php echo $data['birthdate']; ?>>
</td>
</tr>
<tr>
<tr>
<td>Email</td>
<td><input type="text" disabled name="email"
value= <?php echo $data['email']; ?>>
</td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" disabled name="password">
</td>
</tr>
<!-- Conditional label based on who you are -->
<?php
if ($data['role_id'] == 2) {
echo "<td>Seller Rating</td>";
} else {
echo "<td>Buyer Rating</td>";
}
?>
<td>
<?php
$stars = round($data['rating'], 0, PHP_ROUND_HALF_DOWN);
$diff = $data['rating'] - $stars;
$perc = number_format(($data['rating']/5) * 100);
do {
if ($stars == 1 && $diff < 0) {
echo '<span class="glyphicon glyphicon-star opacity"></span>';
} else {
echo '<span class="glyphicon glyphicon-star"></span>';
}
$stars = $stars - 1;
} while ($stars > 0);
echo "<p> " . $perc . "% </p>";
?>
</td>
</tr>
</tbody>
</table>
<input class="btn btn-sm btn-warning" id="edit" type="button" value="Edit">
<input class="btn btn-sm btn-success" disabled type="submit" value="Submit">
</a>
</div>
</form>
<script>
var el = document.getElementById('edit');
var frm = document.getElementById('profile_form');
el.addEventListener('click', function() {
for (var i = 0; i < frm.length; i++) {
frm.elements[i].disabled = false;
}
frm.elements[0].focus();
});
</script>
Который затем переходит к updateProfile.php
:
<?php
try {
require 'dbConnection.php';
$sql = "UPDATE Users SET
username = COALESCE(:username,username),
first_name =COALESCE(:first_name,first_name),
email =COALESCE(:email,email),
last_name =COALESCE(:last_name,last_name),
birthdate =COALESCE(:dob,birthdate),
passwd =COALESCE(:password,passwd),
profile_picture = COALESCE(:userfile,profile_picture)
WHERE user_id =:userID";
$ins = $db->prepare($sql);
$hashedPass = sha1($_POST["password"],false);
$ins->bindParam(':username', $_POST["username"]);
$ins->bindParam(':email', $_POST["email"]);
$ins->bindParam(':password', $hashedPass);
$ins->bindParam(':first_name', $_POST["firstname"]);
$ins->bindParam(':last_name', $_POST["lastname"]);
$ins->bindParam(':dob', $_POST["dob"]);
$ins->bindParam(':userfile', $_POST["userfile"]);
$ins->bindParam(':userID', $_POST["userID"]);
$ins->execute();
header('Location: profile.php');
} catch (PDOException $e) {
echo $e->getMessage();
}
в сторону: '$ hashedPass = sha1 ($ _ POST [ "пароль"], ложь);' - не делайте этого. См. Http://php.net/manual/en/function.password-hash.php – CD001