0

I'm new on StackOverflow. Hope I'm doing the questioning correctly.

I'm trying to insert data from an external XML (URL) into an SQL table, but I get:

Error: INSERT INTO 'table_name' ('price')VALUE ('5.95') You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''BBB' ('price')VALUE ('5.95')' at line 1

I'm able to ECHO and PRINT values from the XML and also able to INSERT non-xml values into the table. The code I'm using is:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

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

foreach ($xml->product as $row) {
    $price = $row -> price;

$sql = "INSERT INTO 'table_name' ('price')"
    . "VALUES ('$price')";  

}

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Would be great if someone can help me out on this one. I've the feeling I'm pretty close...

Shnugo
  • 66,100
  • 9
  • 53
  • 114
Hn3M
  • 13
  • 4

2 Answers2

0

As far as I know, with MariaDB you have to use Backticks to "qoute" an object's name.

Try it like this:

$sql = "INSERT INTO `table_name` (`price`) VALUES ('$price')";

If you do not deal with dangerous object names you might use just

$sql = "INSERT INTO table_name (price) VALUES ('$price')";
Shnugo
  • 66,100
  • 9
  • 53
  • 114
  • Hi Shnugo! Thanks that worked! – Hn3M Jan 12 '17 at 16:41
  • Hi Shnugo. Again thank you for the answer. I'm now stumbling upon the fact that it only imports one value into the SQL database. Could you maybe elaborate how to repeat this $sql query for all the possible rows in the XML? I've been trying to figure this out, but can't find it anywhere. – Hn3M Jan 13 '17 at 07:18
-1

If you got your price properly then you should check your query Ex. INSERT INTO table_name (price) VALUES ('$price')

Bhavika
  • 40
  • 4