在单独的表中拆分存储SQL对象

时间:2014-03-19 04:25:47

标签: php sql sql-server

我的SQL查询通过以下查询随时给出错误输出。我可以在获取结果时设置查询吗?

$con = new connection();
$con = mysql_query("SELECT * FROM object");
while($res = mysql_fetch_array($con)) {

mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'parent_id', '$res[parent_id]');") or die(mysql_error());
mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'nice_url', '$res[nice_url]')") or die(mysql_error());
mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'startpage', '$res[startpage]')") or die(mysql_error());
mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'type', '$res[type]')") or die(mysql_error());
mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'title', '$res[title]')") or die(mysql_error());
mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'menu_title', '$res[menu_title]')") or die(mysql_error());
mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'keywords', '$res[keywords]')") or die(mysql_error());
mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'description', '$res[description]')") or die(mysql_error());
mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'content', '$res[content]')") or die(mysql_error());
mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'date', '$res[date]')") or die(mysql_error());
mysql_query("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES ('$res[id]', 'status', '$res[status]')") or die(mysql_error());

}

2 个答案:

答案 0 :(得分:0)

您使用单引号包装列名称并非正确,您可以使用反引号或不使用反对。但请务必反击任何列名称,即保留关键字甚至表名。

mysql_query("INSERT INTO object_meta 
(`object_id`, `key`, `value`) 
VALUES ('$res[id]', 'parent_id', '$res[parent_id]');") 
or die(mysql_error());

答案 1 :(得分:0)

您的代码对sql注入不安全。此外,您还可以切换到PDO然后切换到mysql函数。您创建一次insert语句,然后将值绑定到查询。此外,这可以保护您免受SQL注入,而无需任何添加代码。

<?php
$pdo = getpdoconnection();
$data = $pdo->query('SELECT * FROM object');

$statement = $pdo->prepare("INSERT INTO object_meta ('object_id', 'key', 'value') VALUES (?, ?, ?)");
while($res = $data->fetch(PDO::FETCH_ASSOC)) {
    $statement->execute(array($res['id'], 'parent_id', $res['parent_id']));
    $statement->execute(array($res['id'], 'nice_url', $res['nice_url']));

    //.....
}

PDO教程

http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers