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 */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大