数组php中的IF语句


IF Statement inside array php

大家好,我有一个更新数据库的代码

$users = Sdba::table('tabusuarios');
$users->where('User_Id =', $User_Id);
$data = array('User_Name'=> $User_Name, 'User_Email'=> $User_Email, 'User_Status'=> $User_Status, 'User_Perm'=> $User_Perm);
$users->update($data);

我的问题是,如果存在类似的内容,我还想再更新1列

if ($_POST["User_Password"]) $data = array('User_Password'=> saltSenha($_POST["User_Password"]));

所以我想做一个所有这些东西的

谢谢你的帮助。

使用isset构造并执行此

$users = Sdba::table('tabusuarios');
$users->where('User_Id =', $User_Id);
$data = array('User_Name'=> $User_Name, 'User_Email'=> $User_Email, 'User_Status'=> $User_Status, 'User_Perm'=> $User_Perm);
if(isset($_POST["User_Password"]) && !empty($_POST["User_Password"]))
{
    $data['User_Password']=saltSenha($_POST["User_Password"]);
}
$users->update($data);
$users = Sdba::table('tabusuarios');
$users->where('User_Id =', $User_Id);
if ($_POST["User_Password"]) {
    $data = array('User_Name'=> $User_Name, 'User_Email'=> $User_Email, 'User_Status'=> $User_Status, 'User_Perm'=> $User_Perm, 'User_Password'=> saltSenha($_POST["User_Password"]));
}else{
    $data = array('User_Name'=> $User_Name, 'User_Email'=> $User_Email, 'User_Status'=> $User_Status, 'User_Perm'=> $User_Perm);
}
$users->update($data);

只需执行以下操作:

$users = Sdba::table('tabusuarios');
$users->where('User_Id =', $User_Id);
$data = array('User_Name'=> $User_Name, 'User_Email'=> $User_Email, 'User_Status'=> 
if ($_POST["User_Password"]){
    $data['User_Password'] = saltSenha($_POST["User_Password"]);
}
$User_Status, 'User_Perm'=> $User_Perm);
$users->update($data);

只需设置基础$data数组,然后如果$_POST["User_Password"]存在&不是空的,只需将其添加到数组中?示例基于下面的代码。我发现,使用array_key_exists()!empty(trim())的双重检查机制是确保您不会在传递的变量(如$_POST$_REQUEST$_GET:)中处理垃圾数据或空白的最佳方法

$users = Sdba::table('tabusuarios');
$users->where('User_Id =', $User_Id);
$data = array('User_Name'=> $User_Name, 'User_Email'=> $User_Email, 'User_Status'=> $User_Status, 'User_Perm'=> $User_Perm);
if (array_key_exists("User_Password", $_POST) && !empty(trim($_POST["User_Password"])) {
  $data['User_Password'] = saltSenha($_POST["User_Password"]);
}
$users->update($data);