简体   繁体   English

通过PHP在$ value更改时更新Mysql行

[英]Update via PHP a Mysql row at a $value change

I need some help. 我需要协助。 Please, note: below lines of codes are only for a main idea example. 请注意:下面的代码行仅用于主要思想示例。

I have a php function to count some entries in a mysql table 我有一个php函数来计数mysql表中的一些条目

$query = "SELECT COUNT(my_matches) FROM my_table";
$db->setQuery($query);
$value = $db->loadResult();

Now, I need to update another row of another table with $value 现在,我需要用$ value更新另一个表的另一行

$query = "UPDATE my_table_reviews SET user_rating = (user_rating + '$value') WHERE listing_id = 77");
$db->setQuery($query);
$autorating = $db->loadResult();}

The problem is: how to update row user_rating from my_table_review ONLY WHEN $value change? 问题是:仅在$ value更改时如何从my_table_review更新user_rating行?

In words... if $value is changed so to this (second query). 换句话说,如果$ value更改为第二次查询。 If $value is stable, do nothing. 如果$ value稳定,则不执行任何操作。

I'm a little bit confused... any help would be really appreciated! 我有点困惑...任何帮助将不胜感激!

if $value is changed so to this (second query). 如果$ value更改为此值(第二个查询)。 If $value is stable, do nothing. 如果$ value稳定,则不执行任何操作。

Then try this: 然后试试这个:

UPDATE my_table_reviews 
SET user_rating = (user_rating + '$value') 
WHERE listing_id = 77
-- update if only the user_rating had changed:
AND user_rating <> user_rating + $value 

If you want to trigger a DB update when a PHP variable changes ($value) then you'll need to abstract all the updates on that variable. 如果要在PHP变量更改($ value)时触发数据库更新,则需要提取该变量上的所有更新。 eg 例如

class Example {
  var $value = 0;

  function var_set($v) {
    $this->value = $v;
  }

  function var_get() {
    return $this->value;
  }
}

...then instantiate your class and access the variable: ...然后实例化您的类并访问变量:

$k = new Example();
$k->var_set(100);
print_r($k);

Once you've got all your accessor/mutator operations going via this abstraction, you can include a check to see if it's changed and use that as the trigger. 一旦所有访问器/更改器操作都通过该抽象进行,就可以进行检查以查看其是否已更改并将其用作触发器。

  function var_set($v) {
    if ($v != $this->value) {
      $this->value = $v;
      // update the DB
      $query = "UPDATE my_table_reviews SET user_rating = (user_rating + '".$this->value."') WHERE listing_id = 77");
      // ...
    }
  }

If on the other hand you want MySQL to identify if there's been an update, and only apply your update if it's different, then just run the UPDATE statement you proposed initially. 另一方面,如果您希望MySQL识别是否有更新,并且仅在更新不同的情况下才应用更新,则只需运行最初建议的UPDATE语句即可。 MySQL will test to see if there's a change and only apply it if there is. MySQL将测试是否有更改,并且仅在有更改的情况下应用。 Adding additional logic to force it to detect that change will only slow down the query resolution time. 添加其他逻辑来强制它检测到更改只会减慢查询解析时间。 Much better to test in PHP before firing the query at all. 在完全触发查询之前,最好在PHP中进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM