douzang7928 2016-06-30 01:07 采纳率: 100%
浏览 73
已采纳

PHP内部的MySQL更新循环

I want to retrieve 8,000 records from a MySQL database, perform a calculation to give each record a rating, then update the database with the rating.

Here's what I have:

require_once('db-connect.php');

//---RETRIEVE FROM DB
mysql_select_db($database_lg, $lg);
$query_r1 = "SELECT * FROM tblposts WHERE status = 'live'";
$r1 = mysql_query($query_r1, $lg) or die(mysql_error());
$row_r1 = mysql_fetch_assoc($r1);

do {

  $id = $row_r1['id'];
  $v1 = $row_r1['views'];
  $v2 = $row_r1['likes'];
  $v3 = $row_r1['tagcount'];
  $v4 = $row_r1['dcount'];
  $v5 = $_POST['content_rating'];

  $rating = $v1 + $v2 + $v3 + $v4 + $v5;

  //---UPDATE DB
  $updateSQL = "UPDATE tblposts SET rating='$rating' WHERE id = '$id'";
  mysql_select_db($database_lg, $lg);
  $Result = mysql_query($updateSQL, $lg) or die(mysql_error());

} while ($row_r1 = mysql_fetch_assoc($r1));
mysql_free_result($r1);

Is this the way to do it? It seems to me I could make my server go up in smoke by doing 8,000 updates this way, but I don't know of a more elegant solution. Any insight appreciated.

Note: I realize that mysql_* functions are deprecated. On the site in question I have to live with them for a while longer.

  • 写回答

1条回答 默认 最新

  • drl6054 2016-06-30 01:20
    关注

    How about this for an insight?

    UPDATE
        tblposts
    SET
        rating = views + likes + tagcount + dcount + $value
    WHERE
        status = 'live';
    

    This means: "For each status that is currently live, make the column rating be the sum of views, likes, tagcount and dcount and a php variable". Pretty much a translation of your php code.

    This removes the need for any selects and loops. Let the DB do the work for you.


    Since you are using mysql_*, I'm not even going deep about security and that stuff. I'll just leave this here for reference:


    And take care when using do..while like that. Since it only checks after running at least once, you might get some notice/warning in case there are no results.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序