0

我正在尝试将来自节点的数据保存在使用 SimpleXML 加载到应用程序中的 xml 文档中。下面是我的代码,但是 SQL 语句有问题,因为我遇到了一个致命错误。

我不明白为什么会抛出这个,因为id(如下面的错误消息中提到的)被用作要放入的值,而不是作为列。

那么,我在这里做错了什么?谢谢!

php:

    $db;

    $theProducers = simplexml_load_file('sources/producers.xml');

    foreach ($theProducers->producer as $producer) {
        $attr = $producer->attributes();
        $producers[$i]['id'] = (int)$attr[0];
        $producers[$i]['name'] = (string)$producer->name;
        $producers[$i]['address'] = (string)$producer->address;
        $producers[$i]['zipcode'] = (string)$producer->zipcode;
        $producers[$i]['town'] = (string)$producer->town;
        $producers[$i]['url'] = (string)$producer->url;
        $producers[$i]['imgurl'] = (string)$producer->imgurl;

        $i += 1;
    }

    try {
            $db = new PDO('sqlite:ProducersDB.sqlite');
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
    catch(PDOException $e) {
        die("Something went wrong: " . $e->getMessage());
    }

    for($i = 0; $i < count($producers); $i++) {

        $sql = "INSERT INTO producers (producerid, name, address, zipcode, town, url, imgurl)
                VALUES($producers[$i]['id'], $producers[$i]['name'], $producers[$i]['address'], $producers[$i]['zipcode'], $producers[$i]['town'], $producers[$i]['url'], $producers[$i]['imgurl']); ";

        if(!$db->query($sql)) {
            die("Couln't execute query!");
        }
    }

错误信息:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]:
General error: 1 no such column: 'id'' in
/Applications/XAMPP/xamppfiles/htdocs/app/index.php:55 Stack trace: #0
/Applications/XAMPP/xamppfiles/htdocs/app/Labb2/index.php(55):
PDO->query('INSERT INTO pro...') #1 {main} thrown in
/Applications/XAMPP/xamppfiles/htdocs/app/index.php on line 55

数据库结构:

Table: Producers

id INTEGER PRIMARY KEY,
producerid INT,
name TEXT,
address TEXT,
zipcode INT,
town TEXT,
url TEXT,
imgurl TEXT
4

2 回答 2

1

You query to INSERT element in your table is not properly built. Your values are in a PHP array which is not interpreted properly between your double quotes, it should be something like this:

$sql = "INSERT INTO producers(producerid, name)
        VALUES ('" . $producers[$i]['id'] . "', '" . $producers[$i]['name'] . "')";

You should also look the method prepare from PDO to properly set dynamic values in your query instead of building it by yourself.

EDIT: according to the PHP documentation on Strings I'm wrong and you can interpret an array between double quotes, sorry for the confusion.

于 2012-12-02T19:15:08.220 回答
1

根据字符串解析文档,多维数组需要你使用复杂的语法;此外,必须引用 SQL 字符串:

$sql = "INSERT INTO producers (...)
        VALUES({$producers[$i]['id']}, '{$producers[$i]['name']}', ..."

为避免字符串格式问题,建议使用参数

于 2012-12-02T21:42:11.593 回答