PDOを使用してすべてのコードを書き直しています。PDOでDuplicateMySQLRecord関数を書き直して行き詰まっています。
関数DuplicateMySQLRecord($ 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);
}
}