尝试保存到SQLite数据库时出现致命错误

时间:2012-12-02 19:09:55

标签: php sql database arrays sqlite

我正在尝试使用SimpleXML从xml doc中的节点中保存数据。下面是我的代码,但是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

db结构:

Table: Producers

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

2 个答案:

答案 0 :(得分:1)

您查询表中的INSERT元素未正确构建。您的值在PHP数组中,在双引号之间无法正确解释,它应该是这样的:

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

您还应该从PDO中查看方法prepare,以便在查询中正确设置动态值,而不是自己构建它。

编辑:根据Strings上的PHP文档,我错了,您可以在双引号之间解释一个数组,对不起有困惑。

答案 1 :(得分:1)

根据string parsing documentation,多维数组要求您使用复杂的语法;另外,必须引用SQL字符串:

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

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