Jump to content

Update mysql table data from xml file


enrb15

Recommended Posts

Good morning, I ask you why I have a problem with a script in php to update the data of a mysql table.

I have a table with the following values:

id, name, city, city_id

and an xml file with the data to be updated:

id_city, city

I tried to make a script to update the data in the table, but unfortunately I always get errors.

My script is as follows:

 

<?php
$conn = mysqli_connect("localhost", "root", "", "dbtest001");


$affectedRow = 0;

$xml = simplexml_load_file("city.xml") or die("Error: Cannot create object");

foreach ($xml->children() as $row) {
    
    $id_city = mysqli_real_escape_string($conn, ($row-> id_city));
    $city = mysqli_real_escape_string($conn, ($row-> city));
    
        
    $sql = "UPDATE user_city SET (id_city, city)
    VALUES ('" . $id_city . "', '" . $city . "')
    ON DUPLICATE KEY UPDATE id_city=$id_city "
    ;
    
    
    $result = mysqli_query($conn, $sql);
    
    if (! empty($result)) {
        $affectedRow ++;
    } else {
        $error_message = mysqli_error($conn) . "\n";
    }
}
?>

 

Link to comment
Share on other sites

Your UPDATE query should be an INSERT .. ON DUPLICATE KEY query.

If there is a duplicate you should be updating the city, not the id.

INSERT INTO user_city (id_city, city)
    VALUES ('$id_city', '$city')
    ON DUPLICATE KEY UPDATE city = '$city'

Better still, use prepared statements.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.