1

我用它在数据库中添加或更新一些东西。

$update = mysql_query
("
    INSERT INTO details (id, name, team, cost) 
    VALUES ('$id', '$name', '$team', '$cost') 
    ON DUPLICATE KEY UPDATE cost = '$cost' 
") 
or die (mysql_error());

基本上,我想做......

如果$cost发生变化,将旧值和新值回显到屏幕上,否则什么也不做。

我将如何去做这样的事情?

4

4 回答 4

2

首先,您必须在 temp 变量中保持与您的 id 相对应的成本

$query        = "SELECT cost FROM details WHERE id = $id";
$resource     = mysql_query($query);
$temp_array   = mysql_fetch_assoc($resource);
$old_cost     = $temp_array['cost'];

现在执行您的操作

mysql_affected_rows 将在 DUPLICATE KEY UPDATE OPERATION 上返回 2

$update = mysql_query("
INSERT INTO details (id, name, team, cost) 
VALUES ('$id', '$name', '$team', '$cost') 
ON DUPLICATE KEY UPDATE cost = '$cost' ") 
  or die (mysql_error());
  if(mysql_affected_rows() == 2)
  {
      echo "old cost = $old_cost";
      echo "New Cost : $cost";
   }

试试这个希望它有帮助

于 2013-03-08T04:39:08.603 回答
1

You can use the mysql_affected_rows() command, see mysql_affected_rows.

Essentially it will tell you how many rows have been updated. Full example:

$update = mysql_query
("
    INSERT INTO details (id, name, team, cost) 
    VALUES ('$id', '$name', '$team', '$cost') 
    ON DUPLICATE KEY UPDATE cost = '$cost' 
") 
or die (mysql_error());
if(mysql_affected_rows($update) != 0)
     echo $cost;

In this case, you'd have to define the old cost in $cost (that line is really for you to interpret as you would like). To do this, you would have to use a SELECT before hand.... Perhaps you could check for a duplicate key instead of using the super elegant ON DUPLICATE KEY...

于 2013-03-08T04:14:03.650 回答
1

我建议使用PHP 的 PDO而不是 mysql_* 函数,因为它们已被正式弃用,而且PHP 的 PDO是一种更安全且更面向对象的方法

→ 有关PHP 的 PDO 的更多信息,请访问: http: //php.net/manual/en/book.pdo.php

话虽如此,INSERT语句仅返回TRUEFALSE,具体取决于 INSERT 语句是成功完成还是失败。

→ 此外,mysql_affected_rows()mysql_num_rows()只会返回插入/更新的行数,不是您正在寻找的旧成本。

因此,您需要分两部分执行此操作:

一个)

SELECT `cost` 
FROM `details`
WHERE `id` = '$id'

如果为上述查询找到行,则您知道您有重复的 id,并且可以评估cost返回的与您拥有的新 $cost。

然后,您可以使用可用的新旧成本来回答您的问题,并且可以:

二)

INSERT INTO details (id, name, team, cost) 
VALUES ('$id', '$name', '$team', '$cost') 
ON DUPLICATE KEY UPDATE cost = '$cost' 

→ 确保你清理了你正在使用的变量;mysql_real_escape_string

→ 或者只使用PHP 的 PDO,因为当您将变量绑定到查询时,它会为您清理变量。

于 2013-03-08T04:24:59.293 回答
0

There is, AFAIK, no way to get the old cost after running your query. You will need to do this in two steps. First a select, and then the insert/update.

于 2013-03-08T04:15:12.920 回答