简体   繁体   中英

mssql pdo If Exists insert prepared statement in a loop

I have a prepared statement which is designed to insert row if a row didn't previously exist. If only one row is to be done it works fine. If there's two, the first row is added and the second ignored. If the first row exists and the second doesn't, the second is added and all following rows fail.

Effectively the insert works once and it's as if the IF NOT EXISTS doesn't update the binding of the new parameters.

Here is the sample code:

$dbConn = 'mssql:host=' . $server . ';dbname=' . $base;
$dbh = new PDO( $dbConn, $user, $pass);

// Go through each course code and add it
// Ignore if it already exists
$stmt = $dbh->prepare('IF NOT EXISTS (SELECT * FROM _ExamCoursesTEMP 
                       WHERE ExamCourseCode = :examCode AND CourseCode = :courseCode )
                       BEGIN
                             INSERT INTO _ExamCoursesTEMP ( ExamCourseCode, CourseCode ) VALUES ( :examCode2, :courseCode2 )
                       END');

$counter = 0;

foreach( $courseCodes as $courseCode )
{
    $stmt->bindParam(':examCode', $examCode );
    $stmt->bindParam(':courseCode', $courseCode );
    $stmt->bindParam(':examCode2', $examCode );
    $stmt->bindParam(':courseCode2', $courseCode );

    $updateCount = $stmt->execute();

    $counter++;
}

The first updateCount returns 1 and all the rest are empty.

I'm not sure if this is an issue with my code, the prepared statement bindings though PDO or a quirk of mssql.

Any help would be appreciated.

Thanks.

The second parameter to bindParam is passed by reference. Thus, it is only necessary to bind the parameter to the variable once, then change the value assigned to that same variable in your loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM