问题
public function addDynFields()
{
$checkedfileds=$_POST['CheckedFileds'];
$fields=implode(',',$checkedfileds);
$dynflds = strtolower($fields);
$dynclmns = 'add_to'.'_'.$dynflds;
if($fields == 'Title')
{
$this->db->query("ALTER TABLE `pm1asset_dynamic_fields` ADD ".$dynclmns." int(11) NOT NULL");
}
else
{
$this->db->query("ALTER TABLE `pm1asset_dynamic_fields` ADD ".$dynclmns." varchar(255) NOT NULL");
}
}
Here above code is a controller code. Here $checkedfileds
is a multiple check box values in the array form. Here i want to explode the $checkedfileds(Array)
values and store it as a separate columns in a table.
If i include $checkedfileds
in $this->db->query("ALTER TABLE pm1asset_dynamic_fields ADD ".$checkedfileds." varchar(255) NOT NULL");
it is created as a Array as a column name in a table, suppose if i include $dynclmns
in $this->db->query("ALTER TABLE pm1asset_dynamic_fields ADD ".$dynclmns." varchar(255) NOT NULL");
it created as a add_to_title but next column is not created, i don't know why it's not going to create. can any one please help me..
回答1:
Try to repair your sql query syntax and modify your codes like this :
$checkedfileds = $_POST['CheckedFileds'];
$qry = "ALTER TABLE `pm1asset_dynamic_fields` ";
foreach ($checkedfileds as $key => $value) {
$dynflds = strtolower($value);
$dynclmns = 'add_to' . '_' . $dynflds;
if ($value == 'Title') {
$qry .= "ADD COLUMN `" . $dynclmns . "` int(11) NOT NULL";
} else {
$qry .= "ADD COLUMN `" . $dynclmns . "` varchar(255) NOT NULL";
}
end($checkedfileds);
// use (;) for the last row, otherwise use (,)
if ($key === key($checkedfileds)) {
$qry .= ";";
} else {
$qry .= ", ";
}
}
$this->db->query($qry);
This will generate query like below :
ALTER TABLE `pm1asset_dynamic_fields`
ADD COLUMN `add_to_title` int(11) NOT NULL,
ADD COLUMN `add_to_col2` varchar(255) NOT NULL,
ADD COLUMN `add_to_col3` varchar(255) NOT NULL;
回答2:
Try adding varchar(255)
to each column
$input=$_POST['CheckedFileds'];
$checkedfileds = array_map(function($value) { return $value." varchar(255)"; }, $input);
$fields=implode(',',$checkedfileds);
来源:https://stackoverflow.com/questions/61007738/how-to-explode-the-values-in-the-array-and-it-as-a-separate-columns-by-creating