R
R
ree4i2015-03-14 22:05:04
MySQL
ree4i, 2015-03-14 22:05:04

How to save parsed XML in MySQL?

There is an XML of the form:

<Langs>
  <Lang>
    <Cats>
      <Cat>
        <Items>
        ...
          <Item ID="56"><Name>Имя 1</Name></Item>
          <Item ID="55"><Name>Имя 2</Name></Item>
        ...
        </Items>
      </Cat>
    </Cats>
  </Lang>
</Langs>

Processing with a script
<?
header("Content-Type: text/html; charset=utf-8");
  $xml = simplexml_load_file('xml.php');
  foreach ($xml->Langs->Lang->Cats->Cat->Items->Item as $Item) {
    $Item['ID'];  // извлекаем ID
  $ID=$Item['ID'];
  $Name=$Item->Name;
  }

  //Загружаем данные в БД
$user="login";
$password="pass";
$database="baza";
$dtable="table";

if ([email protected]_connect("localhost",$user,$password)){
mysql_select_db($database);

echo "База данных найдена!";

  $query = mysql_query("SELECT COUNT(*) FROM $dtable WHERE ID='$ID'") or die(mysql_error());
  $user = mysql_fetch_row($query);
  $total = $user[0];

  if ("$total" == 0) {
    $sql = ("INSERT INTO $dtable (ID,Name) VALUES('$ID','$Name')");
    $result = mysql_query($sql) or die("Error ".mysql_error());
  } else {
    echo 'ID существует!';
  }
}
?>

As a result, only the last line is stored in the database (ie "55" "Name 2"). I practically don’t understand MySQL, and the Internet is full of solving problems for saving requests from forms, at least indicate where to dig.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
ree4i, 2015-03-15
@ree4i

Issue resolved. The nesting of operations was incorrect.

M
Multigame, 2015-03-14
@Multigame

$query = mysql_query("SELECT COUNT(*) FROM $dtable WHERE ID='$ID'")
...
 if ("$total" == 0)

Are you sure about your code?
Parsed xml cannot be natively stored in a mysql field, look towards postgresql.
But judging by the quality of your code, the (un)serialize function will do just fine for your purposes. (this is php). The function converts a php object (array, variable) into a special format string. Thus, the string is stored in the database. Similarly, you can store through json_en (de) code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question