1

请参见下面的代码,它检查表中是否存在数据,如果不存在则插入它,否则更新表。

正如您所看到的,它看起来有点乱 - 有没有改进代码逻辑或更小的东西?我有几张桌子需要做同样的事情。

foreach ($sheet as $data) {
    // Get Phone ID
    $dataPhoneID = mysql_escape_string($data['handset']['phone_id']);

    if (isset($stocks[$dataPhoneID])) {
        $stockPhone = $stocks[$dataPhoneID ];
        $phoneName = mysql_escape_string($stockPhone['description']);
        $stock = mysql_escape_string($stockPhone['stock']);

        $SQL = "SELECT * FROM phone_affiliate WHERE affiliate_id = 1 AND affiliate_phone_id = '$dataPhoneID'";
        $q = mysql_query($SQL);
        if (mysql_num_rows($q) == 0) {
            $SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
            if (mysql_query($SQLInsert)) {
                $phone_id = mysql_insert_id();
                $SQLInsert = "INSERT INTO phone_affiliate (phone_id, affiliate_id, affiliate_phone_id, stock) ";
                $SQLInsert .= "VALUE('$phone_id', '1', '$dataPhoneID', '$stock')";
                mysql_query($SQLInsert) or die(mysql_error());
            }
        } else {
            $row = mysql_fetch_assoc($q);
            $phone_id = $row['phone_id'];
            $SQLUpdate = "UPDATE phone_affiliate set stock = '$stock' WHERE affiliate_id = 1 AND phone_id = $phone_id";
             mysql_query($SQLUpdate) or die(mysql_error());
        }

      // Similar code block above for other tables.
    }
}

注意:我知道 PDO,但我没有时间在现有系统上替换它。

4

2 回答 2

5

使用 mysql 的REPLACE INTOINSERT... ON DUPLICATE KEY UPDATE。例如:

foreach ($sheet as $data) {
    // Get Phone ID
    $dataPhoneID = mysql_escape_string($data['handset']['phone_id']);

    if (isset($stocks[$dataPhoneID])) {
        $stockPhone = $stocks[$dataPhoneID ];
        $phoneName = mysql_escape_string($stockPhone['description']);
        $stock = mysql_escape_string($stockPhone['stock']);

        $SQLInsert = "INSERT INTO phone_affiliate (affiliate_id, affiliate_phone_id, stock) ";
        $SQLInsert .= "VALUES ('1', '$dataPhoneID', '$stock') ";
        $SQLInsert .= "ON DUPLICATE KEY UPDATE stock = '$stock'";
        mysql_query($SQLInsert);
        if (mysql_insert_id()) {
            $SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
            mysql_query($SQLInsert);
            $phone_id = mysql_insert_id();
            $SQLUpdate = "UPDATE phone_affiliate set phone_id = $phone_id WHERE affiliate_id = 1 AND affiliate_phone_id = $dataPhoneID_id";
        }
    }
}
于 2012-09-20T15:49:57.857 回答
0

您也可以使用 INSERT IGNORE 构造

于 2012-09-20T15:51:09.073 回答