I have a mysql database with few tables and the database has got a one
to many relationship. I want to create a dynamic xml file, which will
be updated by php script and the input comes from the mysqldatabase.
For reasons of anoymitiy and ease I will give a example product. My
products are different cars (many) and the equipments are saved in
seperate table and are many.
Now I will show you the database with these two tables (it’s very easy
made for purpose of ease):
cars_db:
CarId | Manufacturer | Color
001 | Volkswagen | RED
002 | Porsche | Yellow
003 | Audi | Black
cars_equipment:
CarId | equipmentname | sortorder
001 | wheels | 01
001 | sensor | 02
001 | led lamp | 03
001 | tool set | 04
002 | led lamp | 01
002 | tool
set | 02
003 | led lamp | 01
003 | tool set | 02
I want to produce following format of xml file
<cars>
<car id="001">
<manufacturer>Volkswagen</manufacturer>
<equipments>
<equipment>wheels</equipment>
<equipment>sensor</equipment>
<equipment>led lamp</equipment>
<equipment>tool set</equipment>
</equipments>
<car id="002">
<manufacturer>Porsche</manufacturer>
<equipments>
<equipment>led lamp</equipment>
<equipment>tool set</equipment>
</equipments>
<car id="003">
<manufacturer>Audi</manufacturer>
<equipments>
<equipment>led lamp</equipment>
<equipment>tool set</equipment>
</equipments>
</cars>
Now my code is like this:
<?php session_start();
$host_name = 'xyz'; $db_name = 'xyz'; $user_name = 'root'; $password =
'';
$table = 'cars';
try {
$conn=new PDO("mysql:host=$host_name; dbname=$db_name", $user_name , $password);
//$conn->exec("SET CHARACTER SET utf8"); } catch (PDOException $e) {
echo 'Connection -not- made<br/>';
print "Error!: " . $e->getMessage() . "<br/>";
die(); }
$getAll_query = "SELECT cars_db.*, cars_equipment.* FROM cars_db LEFT
JOIN cars_equipment ON cars_db.CarId = cars_db.CarId";
$xml_statement = $conn->prepare($getAll_query);
$xml_statement->execute();
$xml=new DOMDocument ("1.0"); $xml->formatOutput=true;
$machines=$xml->createElement("cars"); $xml->appendChild($cars);
foreach ($xml_statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
$machine=$xml->createElement("car");
$machine->setAttribute("Car ID",$row['CarsId']);
$machines->appendChild($cars);
$c_cars_manufacturer=$xml->createElement("Manufacturer",
htmlspecialchars($row['Manufacturer']));
$c_cars->appendChild($c_CarsId);
$c_equipment=$xml->createElement("equipment");
$cars->appendChild($c_equipment);
} echo "<xmp>".$xml->saveXML()."</xmp>"; $xml->save("cars.xml");
>
Don’t focus on the code, because it’s not very important.
What I need to know is, how can I run equipments so long, that it will display
all equipments like above shown. Or do I need special sql statement.???
In which way I’m able to do so.
I cannot get with PHP done to show it by php script.
I think there should be another loop in the loop, but this doesn’t work either.