php - Foreach in foreach check data?
one text
Solution:
Considering you'll have unique value per tax_number
in your table. You should make this tax_number
column as unique.
ALTER TABLE `current`
ADD UNIQUE INDEX `tax_number` (`tax_number`);
Once done you can use mysql INSERT ... ON DUPLICATE KEY UPDATE feature to insert a record or update existing record in single query for a given tax_number.
Considering you have col1
, col2
and tax_number
as columns in your table and you want to update col1
if this record already exists. So mysql query would be
INSERT INTO `current` (col1, col2, tax_number)
VALUES ('a', 'b', 12345)
ON DUPLICATE KEY UPDATE col1 = 'a';
Note: Your code is vulnerable to sql injection
, make sure you update your code by PDO with parameter binding.
So corresponding code in php would be like this.
$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();
}
Source