所以我有这个代码(下面),我想将这一堆重复行简化为一个简单的循环,给定和imput(比如说9)为URL和LISTNUM提供这些值。这可能非常简单,但由于某些原因我无法理解它 - 只是因为我不确定如何处理变量INSIDE其他变量...就像$ _POST [$ n]
if ($_POST[subby] == "subby" )
{
try {
$dbh = new PDO('mysql:host=db2asdfasdf.net;dbname=adsfasdf04', $user, $pass);
echo "Connected\n";
}
catch (Exception $e) {
die("Unable to connect: " . $e->getMessage());
}
try {
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();
$dbh->exec("insert into vim_playlist4 (url, listnum) values ($_POST[video1], 1)");
$dbh->exec("insert into vim_playlist4 (url, listnum) values ($_POST[video2], 2)");
$dbh->exec("insert into vim_playlist4 (url, listnum) values ($_POST[video3], 3)");
$dbh->exec("insert into vim_playlist4 (url, listnum) values ($_POST[video4], 4)");
$dbh->exec("insert into vim_playlist4 (url, listnum) values ($_POST[video5], 5)");
$dbh->exec("insert into vim_playlist4 (url, listnum) values ($_POST[video6], 6)");
$dbh->exec("insert into vim_playlist4 (url, listnum) values ($_POST[video7], 7)");
$dbh->exec("insert into vim_playlist4 (url, listnum) values ($_POST[video8], 8)");
$dbh->exec("insert into vim_playlist4 (url, listnum) values ($_POST[video9], 9)");
$dbh->commit();
}
catch (Exception $e) {
$dbh->rollBack();
echo "Failed: " . $e->getMessage();
}
}
else
{}
答案 0 :(得分:-1)
你可以像这样插入:
insert into vim_playlist4 (url, listnum) values
($_POST[video1], 1),
($_POST[video2], 2),
($_POST[video3], 3),
($_POST[video4], 4)
在插入数据之前不要忘记清理数据,因为您目前有很多SQL注入区域。
以下是清理数据的方法:
<?php
$dbh->beginTransaction();
$sql = $dbh->prepare("insert into vim_playlist4 (url, listnum) values
(?, 1), (?, 2), (?, 3), (?, 4), (?, 5), (?, 6), (?, 7), (?, 8), (?, 9)");
$sql->execute(array($_POST["video1"], $_POST["video2"], $_POST["video3"],
$_POST["video4"], $_POST["video5"] ,$_POST["video6"], $_POST["video7"],
$_POST["video8"], $_POST["video9"]));
$dbh->commit();