根据另一列

时间:2017-06-06 12:57:51

标签: php mysql

我有一个包含以下表结构的表代码。 id是自动递增id,代码是随机唯一的15位数代码,customer_id是客户的id。

 id      code    customer_id 
 1     123...4      1            
 2     124...5      1            
 3     128...3      1            
 4     234...1      2            
 5     678...3      2            
 6     567...8      1            

代码实际上是一个15位数字,我按照下面的代码随机生成。根据用户输入的代码数量,我一次生成代码,将ignore插入表中,如果由于重复而忽略了几行,则将post添加到表中,并添加所需的额外数量用户。我使用这种方法是因为对代码数量的请求通常在50k到100k左右,这种方法效果很好。

do{


        $codes = array();
        $question_marks = array();
        $sql = "SELECT count(*)  FROM code";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $initialCount = $stmt->fetchColumn();
        for ($i=0;$i<$codesToGenerate;$i++){
            $code = getToken(15);
            array_push($codesArray, $code,  $customerId);
            $question_marks[] = '('  . placeholders('?', 2) . ')';
        }

        $datafields = "code,  customer_id";
        $this->db->beginTransaction(); // also helps speed up your inserts.
        $sql = "INSERT IGNORE INTO code (" . $datafields  . ") VALUES " . implode(',', $question_marks) ;
        $stmt = $this->db->prepare($sql);
        try {
            $stmt->execute($codesArray);
        }catch (\PDOException $e){
            echo $e->getMessage();
            $result = 0;
        }
        $this->db->commit();


        $sql = "SELECT count(*)  FROM code";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $finalCount  = $stmt->fetchColumn();
        $rowsInserted = $finalCount - $initialCount;
        $codesGenerated += $rowsInserted;
        $codesToGenerate = $codesToGenerate - $rowsInserted;
    }while($codesToGenerate>0);

我在表中添加了一个列serial_number,我想添加一个serial_number,它将根据customer_id为下面各个客户的每个值递增。如何更改PHP代码以添加serial_number。请注意,我想避免在serial_number中出现漏洞。

 id    code       customer_id  serial_number
 1     123...4      1            1
 2     124...5      1            2
 3     128...3      1            3
 4     234...1      2            1
 5     678...3      2            2
 6     567...8      1            4     

我该怎么做?

以下是我的一些想法:

  1)Should it be done seperately post this transaction? 
  2)Should I maintain a last count of serial_number for each customer in a   separate table and then increment in PHP before adding to table. 
  3) How do I take care of concurrencies if I use the approach mentioned in 2 above 

0 个答案:

没有答案