我想运行一个需要使用MSSQL DB的一次性查询插入多个值的查询。因此我想使用PDO。
我的问题是我需要插入具有不同日期的值,我不知道如何处理这个问题。
我从html文本框中获取所有帐户,如下所示:
user|pass
user2|pass2
user3|pass3
从表单中我获得了诸如优先级(影响dateCreated),区域等附加信息,这些信息对于整个插入是相同的。根据优先级,我需要插入不同的日期。当优先级正常时,我希望将当前数据库时间与" GETDATE()"一起使用。当优先级是紧急或低时,我想使用硬编码的dateCreated或类似" GETDATE() - 1000"。这就是我尝试过的:
// Divide the textarea by line into a string array
$accounts = explode(PHP_EOL, $_POST['accountData']);
// Prepare the Query
$query = "INSERT INTO accounts (username, password, referral, dateCreated,region,idOrder) VALUES ";
// Create the multiple value placeholder
$qPart = array_fill(0, sizeof($accounts), "(:username, :password, :referral, :dateCreated, :region, :idOrder)");
$query .= implode(",",$qPart);
$stmt = $dbh->prepare($query);
switch($priority)
{
case("low"):
$date="2050-01-01 00:00:00.000";
foreach($accounts as $item){
list($user, $pass) = explode("|", $item[$key]);
$stmt->bindParam(':username', $user);
$stmt->bindParam(':password', $pass);
$stmt->bindParam(':referral', $refid);
$stmt->bindParam(':dateCreated', $date);
$stmt->bindParam(':region', $region);
$stmt->bindParam(':idOrder', $idOrder);
}
break;
case("mid"):
// Here I want to call the getDate() function of the Database for the current Date
$date="getDate()";
foreach($accounts as $item){
list($user, $pass) = explode("|", $item[$key]);
$stmt->bindParam(':username', $user);
$stmt->bindParam(':password', $pass);
$stmt->bindParam(':referral', $refid);
$stmt->bindParam(':dateCreated', $date);
$stmt->bindParam(':region', $region);
$stmt->bindParam(':idOrder', $idOrder);
}
break;
case("high"):
$date="2000-01-01 00:00:00.000";
foreach($accounts as $item){
list($user, $pass) = explode("|", $item[$key]);
$stmt->bindParam(':username', $user);
$stmt->bindParam(':password', $pass);
$stmt->bindParam(':referral', $refid);
$stmt->bindParam(':dateCreated', $date);
$stmt->bindParam(':region', $region);
$stmt->bindParam(':idOrder', $idOrder);
}
break;
}
$stmt->execute();
答案 0 :(得分:1)
你在做什么:
$stmt = $dbh->prepare("INSERT INTO accounts
(username, password)
VALUES (:username, :password), (:username, :password)");
我不确定您是否可以在预准备语句中使用重复的命名参数,但由于bindParam是引用的,因此值将是相同的。
每个人都谈论有关preps的安全性,但(以dbms术语表示)它们的开发是为了更快地执行重复查询。
所以在你的情况下你可以这样做
$stmt = $dbh->prepare("INSERT INTO accounts
(username, password, refreferral, dateCreated,region,idOrder)
VALUES(:username, :password, :referral, :dateCreated, :region, :idOrder)";
$stmt->bindParam(':referral', $refid);
$stmt->bindParam(':region', $region);
$stmt->bindParam(':idOrder', $idOrder);
$stmt->bindParam(':username', $user);
$stmt->bindParam(':password', $pass);
foreach($accounts as $item) {
list($user, $pass) = explode("|", $item[$key]);
switch($priotity) {
case ('low'):
$stmt->bindParam(':dateCreated', '2050-01-01 00:00:00.000');
break;
case('mid'):
$stmt->bindParam(':dateCreated', 'getDate()', PDO_PARAM_NULL);
break;
default:
$stmt->bindParam(':dateCreated', '2000-01-01 00:00:00.000');
}
$stmt->execute();
}
我不确定PDO是否接受了解决方法,即如果它检查变量是否保持'NULL'