php - 使用单个查询更改多个 MySQL 字段 - 产品代码销售

标签 php html mysql database forms

我有一个网站,其中包含我销售的产品,每个产品都有自己的产品代码。问题是最近我们将所有产品代码更改为所有产品。

因为今天之前插入 MySQL 的所有销售都使用旧的产品代码,当我尝试获取一份报告以查看一种产品已售出多少时,系统会发现 0,因为它会在插入旧销售的同时查找新的产品代码与旧的。

解决方案:

即使这是一种痛苦,除了更新所有已售出并插入 MySQL 的产品之外,没有其他方法,用新产品代码更新旧产品代码,这样它就能正常工作。

我需要像这样更新:

    $update = mysqli_query($database, "
update `sales` SET code = 0001 WHERE `code` = '4574645448458'
");

唯一的问题是它仅更新具有此产品代码的第一个产品,但我有数百个使用相同产品代码销售的产品...

如何以某种批量方式解决这个问题?

我将更改的示例:

0001 的代码 4574645448458 0002 的代码 4574645448459

等等

最佳答案

这是 Marc B 的建议示例。
使用prepared statementexecute它与每对“旧/新”值。

A prepared statement can be executed repeatedly. Upon every execution the current value of the bound variable is evaluated and sent to the server. The statement is not parsed again. The statement template is not transferred to the server again.

例如:

// define an array with all of the code changes as "key/value" pairs
$changes=array(
    '4574645448458' => '0001',
    '4574645448459' => '0002',
    ....
);

// define the query string with placeholders
$sql="UPDATE `sales` SET `code`=:new_code WHERE `code`=:old_code;";

// prepare the statement and set up variables to be bound upon execution
$q=$database->prepare($sql);
$q->bind_param(':new_code',$new_code);
$q->bind_param(':old_code',$old_code);

// iterate through "changes", defining the "old" and "new" values for each code change
// execute the prepared statement with each pair of values
foreach ($changes as $old_code => $new_code) {
    $q->execute();
}

关于php - 使用单个查询更改多个 MySQL 字段 - 产品代码销售,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31926349/

相关文章:

html - 滚动 div 顶部的 CSS 褪色部分

php - WebsitePanel - mysql_connect() : Access denied for user 'user' @'localhost' (using password: YES) on line 38. 连接到 mysql 时出错

php - 添加到mysql数组

php - 如何缩短函数查询?

javascript - 客户端和服务器时间之间的差异

javascript - 根据请求将 MySQL 数据从 PHP 发布和检索到 html

php - 使用数据库查询从 Php 导出 CSV 文件

php - PHP 中简单干净的 xml 操作

php - 如何将 "error codes"添加到结果中?

css - 如何使列表项水平填充 div?