gpt4 book ai didi

PHP 跳过不存在的函数变量

转载 作者:可可西里 更新时间:2023-11-01 00:19:33 25 4
gpt4 key购买 nike

我有这段代码:

public function changeProfile ($first_name, $last_name, $email, $phone, $password, 
$bank_name, $bank_account_number, $bank_account_name,
$gender, $birthday, $address, $area, $default_type) {

$this->connect();

$data = array ('first_name' => $this->escapeString($first_name),
'last_name' => $this->escapeString($last_name),
'email' => $this->escapeString($email),
'phone' => $this->escapeString($phone),
'password' => $this->escapeString($password),
'bank_name' => $this->escapeString($bank_name),
'bank_account_number' => $this->escapeString($bank_account_number),
'bank_account_name' => $this->escapeString($bank_account_name),
'gender' => $this->escapeString($gender),
'birthday' => $this->escapeString($birthday),
'address' => $this->escapeString($address),
'area' => $this->escapeString($area),
'default_type' => $this->escapeString($default_type));

$this->update('user', $data, 'email = "'.$email.'" AND phone = "'.$phone.'"');
$res = $this->getResult();

}

现在,我有这样的问题:

我想“跳过”函数中的一些变量,例如 $birthday$gender,这样它就不会在 SQL UPDATE 上被处理,让当前数据的原样。

我的意思是,如果 $birthday$gender data 不存在,则不要更新表中的现有数据。因为当我尝试在函数上使用 NULL 作为变量时,我的数据被空数据替换了。

如何在没有多个 if 检查每个变量的情况下管理这种情况?

谢谢

最佳答案

如果有这个选项,您应该用参数数组替换函数的参数列表,例如:

public function changeProfile($variables)
{
$this->connect();

$data = array();
foreach ($variables as $key => $value) {
$data[$key] = $this->escapeString($value);
}

// Validation?
if (!isset($data['email'], $data['phone'])) {
die('Required fields missing.');
}

$this->update('user', $data, 'email = "' . $data['email'] . '" AND phone = "' . $data['phone'] . '"');
$res = $this->getResult();
}

这假设 SQL 查询是静态的。如果需要,您还可以向其中添加更多字段。

然后你可以这样调用它:

$test->changeProfileUpdated([
'first_name' => 'john',
'last_name' => 'doe',
'email' => 'example@example.com',
'phone' => 12345,
'password' => 'password1',
'bank_name' => 'ANZ',
'bank_account_number' => '123-456',
'bank_account_name' => 'J DOE',
'gender' => 'M',
'birthday' => '1/2/13',
'address' => '12 Fake St',
'area' => 'Area 51',
'default_type' => 'Some default'
]);

Here's a demo 比较您的代码、此示例和验证失败。

关于PHP 跳过不存在的函数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34868401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com