gpt4 book ai didi

php - 尝试删除所有行或具有相同代码的一行时出现php语法错误

转载 作者:行者123 更新时间:2023-12-03 08:08:58 26 4
gpt4 key购买 nike

我在codeigniter中编写了一个delete函数。用户有两个选择。全部删除或删除一行。我不想重复相同的代码,而是使用类似的函数。但是有一个错误'分析错误:语法错误,意外的T_ELSE'。我该如何解决这个问题?重复代码的唯一方法?

public function _delete_port()
{
if ($_GET['delete_all']):
foreach ($_GET['delete_id'] as $delete_id):
else:
$delete_id = $_GET['delete_id'];
endif;
// Some controls
// ...

$this->db->delete('ma_port', array('id' => $delete_id));

if ($_GET['delete_all']) :
endforeach;
endif;

redirect($url);
}

最佳答案

您的代码面临的主要问题似乎是对流控制的工作原理的误解。您采用的方法是尝试使用if / else / endif构造代码的外观而不是代码的外观。

您的过程是,如果$_GET['delete_all']作为数组存在,则使用循环,否则使用$_GET['delete_id']。因此,首先检查变量的内容,然后采取适当的措施。如果$_GET['delete_id']不存在,可以通过将$_GET['delete_all']放入数组来简化整个过程。

// Empty array we'll fill later
$delete_ids = array();

// If the delete_all array is available, use it as the array to delete from
if (isset($_GET['delete_all']) && is_array($_GET['delete_all'])) {
$delete_ids = $_GET['delete_all'];
}
// Next if delete_id is present
else if (isset($_GET['delete_id'])) {
// Place it into the array to use later
$delete_ids[] = $_GET['delete_id'];
}
else {
// Neither was set, you have an error state, so handle it however you need to
// Redirect, display an error, whatever.
}

// Now loop over your array and perform the action.
// The array either contains the original array from $_GET['delete_all'] or the single element $_GET['delete_id']
// Or it may be empty entirely, and therefore won't do anything
foreach ($delete_ids as $delete_id) {
$this->db_delete('ma_port', array('id' => $delete_id));
}

// And finish with your redirect
redirect($url);

关于php - 尝试删除所有行或具有相同代码的一行时出现php语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19590794/

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