大家好,抱歉我的英语不好。
我有一个 SET 类型的列“example”。 我必须制作一个 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中,无所谓
感谢帮助
最佳答案
我们可以通过 information_schema.columns
的查询获取列定义
假设该表在当前数据库中(并且假设我们在选择对表名使用大小写混合时了解 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
作为应用程序代码的一部分运行的想法。这样做将在事务中进行隐式提交,并且在执行操作时还需要独占表/元数据锁。
关于php - 如何在不知道当前值的情况下向 PHP 中的 MySQL SET 类型添加可能的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47780299/