2 回答

TA貢獻1805條經(jīng)驗 獲得超10個贊
您可以通過稍微修改 php 代碼來實現(xiàn)該目標。因此,不要使用固定表列和 SQL 參數(shù)來更新表,而是檢查 $_POST['editaccessrole'] 并動態(tài)構造參數(shù)和 UPDATE SQL。希望下面的代碼對您有用。
function updateAdmin($pdo) {
$a_firstname = sanitize_data($_POST['editfirstname']);
$a_lastname = sanitize_data($_POST['editlastname']);
$a_email = $_POST['editemail'];
$a_accessrole = sanitize_data($_POST['editaccessrole']);
$admin_id = sanitize_data($_POST['admin_id']);
$data = array('a_firstname' => $a_firstname, 'a_lastname' => $a_lastname, 'a_email' => $a_email, 'a_accessrole' => $a_accessrole);
$password_sql = "";
if (isset($_POST['editpassword']) && !empty($_POST['editpassword'])) {
//Add the a_password column in UPDATE statement if edit password value is set and non empty
$a_password = sanitize_data($_POST['editpassword']);
$password=password_hash($a_password, PASSWORD_BCRYPT,['cost' => 12]);
//So the parm and SQL is dynamic based on $_POST['editpassword']
$data['a_password'] = $password;
$password_sql = ", a_password=:a_password";
}
try {
$sql = "UPDATE tbl_admin SET a_firstname=:a_firstname, a_lastname=:a_lastname, a_email=:a_email{$password_sql}, a_accessrole=:a_accessrole WHERE admin_id=:admin_id";
$stmt = $pdo -> prepare($sql);
$stmt -> bindParam('admin_id', $admin_id);
$stmt -> execute($data);
//This is success but you are sending true as error, any particular reason? I hope you did it intentionally.
$response['error'] = "true";
} catch(PDOExecption $e) {
$dbh -> rollback();
print "Error!: " . $e -> getMessage() . "</br>";
//This is failed but you are sending false as error, any particular reason? I hope you did it intentionally.
$response['error'] = "false";
}
// print_r($response);
echo json_encode($response);
}

TA貢獻1816條經(jīng)驗 獲得超4個贊
您提到了我想要的,如果密碼字段中有數(shù)據(jù),則更新它,否則在更新時忽略密碼字段。。if在這種情況下,您可以在 SQL 查詢中使用條件,如下所示:
UPDATE tbl_admin
SET a_firstname = :a_firstname,
a_lastname = :a_lastname,
a_email = :a_email,
a_password = if(a_password is null or length(a_password) = 0,a_password,:a_password),
a_accessrole = :a_accessrole
WHERE admin_id = :admin_id
更新:
如果您的意思是來自發(fā)布請求的空密碼字段,您可以首先為查詢占位符設置適當?shù)臄?shù)據(jù),如下所示:
$data = array(
'a_firstname' => $a_firstname,
'a_lastname' => $a_lastname,
'a_email' => $a_email,
'a_password' => empty(trim($a_password)) ? '' : $password,
'a_accessrole' => $a_accessrole
);
你的 SQL 查詢將如下所示:
UPDATE tbl_admin
SET a_firstname = :a_firstname,
a_lastname = :a_lastname,
a_email = :a_email,
a_password = if(length(:a_password) = 0,a_password,:a_password),
a_accessrole = :a_accessrole
WHERE admin_id = :admin_id
- 2 回答
- 0 關注
- 175 瀏覽
添加回答
舉報