我正在使用PDO重写所有代码。我在PDO中重写DuplicateMySQLRecord函数时遇到了问题。
函数DuplicateMyQLRecord($table,$id_field,$id)
我就是无法将我的思想包裹在这件事上——我已经捅了很多刀,这一切都是一次悲惨的失败。
有人能帮助一个兄弟吗?
为什么要为此创建一个函数?
INSERT INTO my_table SELECT * FROM my_table WHERE column="data"
请记住,如果您没有唯一的分隔符(id等),这将导致大问题。
举个例子:
假设我有一张这样的桌子:
+-------------+-------+----------+
| something | other | there_is |
+-------------+-------+----------+
| huh | what | no id |
+-------------+-------+----------+
我执行
INSERT INTO my_table SELECT * FROM my_table WHERE there_is="no id"
现在我们有
+-------------+-------+----------+
| something | other | there_is |
+-------------+-------+----------+
| huh | what | no id |
| huh | what | no id |
+-------------+-------+----------+
如果我想再次执行它怎么办?这行得通,对吗?好吧,这次我们会得到:
+-------------+-------+----------+
| something | other | there_is |
+-------------+-------+----------+
| huh | what | no id |
| huh | what | no id |
| huh | what | no id |
| huh | what | no id |
+-------------+-------+----------+
然后
+-------------+-------+----------+
| something | other | there_is |
+-------------+-------+----------+
| huh | what | no id |
| huh | what | no id |
| huh | what | no id |
| huh | what | no id |
| huh | what | no id |
| huh | what | no id |
| huh | what | no id |
| huh | what | no id |
+-------------+-------+----------+
等等。。因此,设置一个唯一的标识符。
不安全代码-这极易受到SQL注入的攻击。强烈建议正确使用事先准备好的陈述
基于函数名称:
function DuplicateMySQLRecord ($table, $id_field, $id) {
$result = $dbconn->query("SELECT * FROM ".$table."
WHERE ".$id_field." = '".$id."' LIMIT 1");
$row = $result[0];
$SQL = "INSERT INTO ".$table." (";
$first = true;
foreach($row as $key=>$val) {
if($key != $id_field) {
if(!$first) {
$SQL.=',';
$SQL .=$key;
}
}
}
foreach($row as $key=>$val) {
if($key != $id_field) {
if(!$first) {
$SQL.=',';
$SQL .="'".$val."'";
}
}
}
$dbconn->exec($SQL);
}
}