如何在不知道当前值的情况下将可能的值添加到 php 中的 MySQL SET 类型

How to add a possble value to a MySQL SET type in php, without know the current values

大家好,抱歉我的英语不好。

我的列“example”是 SET 类型。 我必须制作一个 php 页面,您可以在其中向该列添加值。

首先我需要知道“example”中的内容,以防止通过控件添加现有值。其次,我需要添加新值。

这是我想做的。

//I just made the connection to the db in PDO or MySQLi
$newValue=$_POST['value']; //I take the value to add in the possible values from a form
//Now I have to "extract" all the possible values. Can't think how.

//I think I can store the values into an array
$result=$sql->fetch();  //$sql is the query to extract all the possible values from "example"

//So now i can do a control with a foreach
foreach($result as $control){
     if ($newValue == $control){
          //error message, break the foreach loop
     }
}
//Now, if the code arrives here there isn't erros, so the "$newValue" is different from any other values stored in "example", so I need to add it as a possible value
$sql=$conn->query("ALTER TABLE 'TableName' CHANGE 'example' 'example' SET('$result', '$newValue')"); //<- where $result is the all existing possible values of "example"

在 PDO 或 MySQLi 中,无所谓

感谢您的帮助

如果您需要 SET 类型 - 您应该知道要添加什么值。否则,只需使用 VARCHAR 类型。

我们可以通过 information_schema.columns

的查询获取列定义

假设 table 在当前数据库中(并且假设我们在选择 table 名称的混合大小写时认识到 lower_case_table_names 设置)

 SELECT c.column_type 
   FROM information_schema.columns c
  WHERE c.table_schema = DATABASE()
  WHERE c.table_name   = 'TableName'
    AND c.column_name  = 'example'

注意 SET 定义中允许的元素数量限制。

去掉末尾的右括号,追加',newval').


就我个人而言,我不太喜欢将 运行 和 ALTER TABLE 作为应用程序代码的一部分的想法。这样做将在事务中进行隐式提交,并且在执行操作时还需要独占 table / 元数据锁。