gpt4 book ai didi

php - Mysql更新所有以相同名称开头的列

转载 作者:行者123 更新时间:2023-11-29 01:12:57 25 4
gpt4 key购买 nike

我有一个名为“产品”的包含多种语言的动态表。表格列如下所示:

id, product_id, store_de, store_en, store_fr, store_es... etc

语言可多可少。

现在我想更新此表并将所有以“store_”开头的列设置为值 1。

我尝试了以下方法:

$stmt = $dbh->prepare( "UPDATE products SET `store_%` = ? WHERE product_id = ?" );

$stmt->execute( array( 1, $lastID ) );

我收到以下错误消息:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'store%' in 'field list'

有没有办法更新所有以“store_”开头的列,或者我是否必须列出所有列?


根据 jekaby 的回答,这里是对我有用的完整解决方案:

$get_stores = $dbh->prepare("SHOW COLUMNS FROM products_active WHERE field REGEXP '^store'");
$get_stores->execute();
$stores = $get_stores->fetchAll();

$update_string = "";
$first_store = true;
foreach($stores as $store) {
if(!$first_store) {

$update_string .= ", ";

} else {

$first_store = false;

}
$update_string .= $store['Field']." = '".$status."'";

}

$update_activity = $dbh->prepare("UPDATE products_active SET $update_string WHERE product_id = ?");
$update_activity->execute(array($product_id));

最佳答案

您需要明确设置每一列。 SQL 不支持列名的通配符(* 用于 SELECT * 除外):

update products
set store_de = 1,
store_en = 1,
store_fr = 1,
store_es = 1,
. . .
where product_id = ?;

您的数据结构表明您确实需要一个 ProductStores 表。每种语言(?)和每种产品都有一行。它至少有三列:

  • ProductId
  • 语言

那么你只需要做:

update ProductStores
set Value = 1
where ProductId = ?;

关于php - Mysql更新所有以相同名称开头的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36307158/

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