【问题标题】:Foreach in foreach check data?foreach 在 foreach 检查数据?
【发布时间】:2021-01-13 02:55:37
【问题描述】:

我有一个获取数据的 xml 文件。我将这些数据记录在数据库中并进行更新。现在我面临一个逻辑我无法解决的情况。

我想做;我想检查数据库中的数据是否有我从 XML 获得的数据,如果有任何未附加的数据则添加,如果添加了则更新它。

示例代码如下。提前感谢您的支持

$current = simplexml_load_file('http://example.com/simple.xml');

foreach($current->simple as $item){

// Database Control data
$tax  = $item->tax;
$data = $db->query("SELECT*FROM current WHERE tax_number = '$tax' ");

foreach($data->results() as $row){

if(isset($data))
{
   // Edit
}
else
{
   // Insert
}

}

}

根据上面的代码,有这样的情况。比如xml文件有50条数据,如果当前表有500条数据,则返回50*500次,每条数据乘以我要控制的表中的个数。他只是补充道。

【问题讨论】:

    标签: php mysql pdo foreach


    【解决方案1】:

    考虑到您的表格中每个tax_number 都有唯一的价值。您应该将此 tax_number 列设为唯一。

    ALTER TABLE `current`
        ADD UNIQUE INDEX `tax_number` (`tax_number`);
    

    完成后,您可以使用 mysql INSERT ... ON DUPLICATE KEY UPDATE 功能在单个查询中为给定的 tax_number 插入记录或更新现有记录。

    考虑到您有 col1col2tax_number 作为表中的列,如果此记录已存在,您想要更新 col1。所以mysql查询会是

    INSERT INTO `current` (col1, col2, tax_number) 
    VALUES ('a', 'b', 12345)
    ON DUPLICATE KEY UPDATE col1 = 'a';
    

    注意:您的代码容易受到sql injection 的攻击,请确保通过参数绑定将您的代码更新为PDO

    所以php中对应的代码应该是这样的。

    $current = simplexml_load_file('http://example.com/simple.xml');
    
    foreach($current->simple as $item){
    
        $query = $db->prepare('INSERT INTO current (currentDocumentNumber, currentTaxNumber, currentIdentity,currentOperationType,currentAmountOfDebt,currentAmountDue,currentAccountDate)
                    VALUES (:doc_number, :tax_number, :identity, :operation_type, :debt_amount, :due_amount, :date)
                    ON DUPLICATE KEY UPDATE currentAmountOfDebt = :debt_amount, currentAmountDue = :due_amount');
       
        $query->bindParam(':doc_number', $item->EVRAK_NO, PDO::PARAM_STR);
        $query->bindParam(':tax_number', $item->VERGI_NO, PDO::PARAM_INT);
        $query->bindParam(':identity', $item->TC_KIMLIK_NO, PDO::PARAM_STR);
        $query->bindParam(':operation_type', $item->ISLEM_TURU, PDO::PARAM_INT);
        $query->bindParam(':debt_amount', $item->KPB_BTUT, PDO::PARAM_STR);
        $query->bindParam(':due_amount', $item->KPB_ATUT, PDO::PARAM_STR);
        $query->bindParam(':date', $item->TARIHI, PDO::PARAM_STR);
        $query->execute();
    }
    

    【讨论】:

    • 我试过但它只是保存,不更新。为什么会这样?
    • 确保使用相关的 php 变量更新值 a
    • 你能告诉我们echo '<pre>'; print_r($item); die;。我想看看你在这个变量中有什么值。
    • 感谢您的回答。我按原样使用您给我的代码,但它只是添加数据,重新注册它而不是更新现有数据。
    • 当然,您需要根据您的代码更新这些 col1 或 col2,这就是为什么我问您转储 echo '<pre>'; print_r($item); die;
    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 2012-07-28
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多