drvlf9739 2014-05-16 13:55
浏览 88
已采纳

在for循环中存储mysql中的变量

I am working on a project where I need to save some variables to a database and retrieve some of those variables in a class to recalculate the next batch of variables.

However I came to realise that the current project is running too slow and find out where the leak was: in storing those variables. (Insert statement in PHP)

Since the insert statement can get in a pretty big for loop, like this ($auctionobjects and numberofdays is filled in by the user, $hours == 24):

for($i = 0; $i< $numberofdays)  {
    for ($n = 0; $n < $hours)  {
        for ($k = 0; $k < $auctionobjects)  {
        $strSql = 'insert into results (vars) values ()'
        $blnOke = $objDatabase->query($strSql)
        }
    }
 }

The waiting time can get pretty long, which is not desirable as the simulation must be able to run for a pretty long time.

Now my idea was to get an insert statement as the following:

$strSql = 'insert into results (vars) values (), (),()'

But the variables that fill the columns in MySql change troughout the simulation. Since I don't know how big the $auctionobjects variable will be, I cannot get the right number of brackets I need to fill in.

What I could do is create a variable that creates the string needed for the amount of $auctionobjects like this:

$createSqlString  = '(vars)'
for($x = 0; $x< $auctionobjects; $x ++)  {
   $createSqlString .= ,(vars)
}

And then insert it in the Sql statement, but I am not sure if there is a more clean solution.

  • 写回答

1条回答 默认 最新

  • duanlu8613 2014-05-16 14:15
    关注

    You might try something like this:

    $createSqlString = `INSERT INTO results (var, var, var) VALUES ';
    $vars = array();
    
    for($x = 0; $x < $auctionobjects; $x ++)  {
        /* processing ... */
        $vars[] = "($val1, $val2, $val3)";
    }
    $createSqlString .= implode (',', $vars);
    

    implode is pretty nice for these SQL-style comma separated lists.

    If you wanted to be really careful about bind variables to prevent injection attacks, you could try this:

    $createSqlString = `INSERT INTO results (var, var, var) VALUES ()';
    $sqls = array();
    $vals = array();
    
    for($x = 0; $x < $auctionobjects; $x ++)  {
        /* processing ... */
        $sqls[] = '(?,?,?)';
        $vals[] = $val1;
        $vals[] = $val2;
        $vals[] = $val2;
    }
    $createSqlString .= implode (',', $vars);
    /* then bind the $vals array to the statement and execute it */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?