Jay*_*nex 2 php mysql sql-like
我有一个名为'products'的动态表,其中包含多种语言.表格列如下所示:
id, product_id, store_de, store_en, store_fr, store_es... etc
Run Code Online (Sandbox Code Playgroud)
语言可以或多或少.
现在我想更新此表并将以"store_"开头的所有列设置为值1.
我尝试了以下方法:
$stmt = $dbh->prepare( "UPDATE products SET `store_%` = ? WHERE product_id = ?" );
$stmt->execute( array( 1, $lastID ) );
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息:
SQLSTATE [42S22]:找不到列:1054'字段列表'中的未知列'store%'
有没有办法更新以'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));
Run Code Online (Sandbox Code Playgroud)
您需要明确设置每一列.SQL不支持列名通配符(有例外*的SELECT *):
update products
set store_de = 1,
store_en = 1,
store_fr = 1,
store_es = 1,
. . .
where product_id = ?;
Run Code Online (Sandbox Code Playgroud)
您的数据结构表明您确实需要一个ProductStores表.每个语言(?)和每个产品都有一行.它至少有三列:
ProductIdLanguageValue然后你会做:
update ProductStores
set Value = 1
where ProductId = ?;
Run Code Online (Sandbox Code Playgroud)