I'm reading through xml files with simplexml_load_file. I'm trying to loop through 3 different xml files and then insert the value into mysql database. It's only inserting the last array. Should I be using a while loop?
Here is my code:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Load/read xml files
$id1 = simplexml_load_file('1.xml');
// echo $id1->video[0];
$id2 = simplexml_load_file('2.xml');
// echo $id2->video[0];
$id3 = simplexml_load_file('2.xml');
// echo $id3->video[0];
// make into an array list
$arr = array($id1->video[0], $id2->video[0], $id3->video[0]);
// loop through array and insert into sql database
foreach ($arr as $value) {
$value = $value;
$sql = "INSERT INTO videos (username, src, type, position)
VALUES ('admin', '".$value."', 'vide', '0')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
$sqlon every iteration. You also are open to SQL injections. Parameterize.