Jump to content

Problem with sqlsrv_query inserting then selecting inserted record?


benphp

Recommended Posts

I apolgize for submitting this question on another thread - it occurred to me that it's more of a SQL Server problem.

 

This script is somehow inserting a row then returning to the SELECT statement and re-SELECTING the row. How do I prevent that from happening? I need to 1) select to make sure the record doesn't exist, then INSERT if it doesn't or post a message saying "already there" if it exists.

 

I've been pulling my hair out all day on this one. No matter what I do, I can't get it to say "You are now enrolled!". Instead, it always finds rows...

 

<?php
$serverName = "myserv";
$mainDb = "mydb";
$connectionInfo = array( "Database"=>"mydb");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( !$conn ) {
     echo "Connection could not be established.\n";
     die( print_r( sqlsrv_errors(), true));
}

/////ENROLL SINGLE MANUAL
if(isset($_POST['btnEnrollMe'])) {
	$CLID = $_POST['CLID'];
	$EID = $_POST['EID'];
	$month = $_POST['month'];
	$year = $_POST['year'];
	
	$classTitle = $_POST['classTitle'];
	
	$sqlSelect = "
	Select 
		$mainDb.dbo.Class_Students.EID
	FROM 
		$mainDb.dbo.Class_Students 
	WHERE 
		$mainDb.dbo.Class_Students.EID = $EID 
	AND
		$mainDb.dbo.Class_Students.CLID = $CLID
	";

	$params = array();
	$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
	$stmt = sqlsrv_query( $conn, $sqlSelect , $params, $options );
	$numrows = sqlsrv_num_rows($stmt);
	sqlsrv_free_stmt($stmt);
	$stmt = NULL;
	
	print "found:$numrows";
	if ($numrows > 0) {
		echo "<p>There are rows. </p>";
	} else {
		$sqlInsert = "
		INSERT INTO $mainDb.dbo.Class_Students 
		($mainDb.dbo.Class_Students.EID, $mainDb.dbo.Class_Students.CLID) VALUES ('$EID', '$CLID')
		";
		$stmt = sqlsrv_query($conn, $sqlInsert);
		print "<P style=\"color:green\">You are now enrolled! <P>";
		sqlsrv_free_stmt($stmt);
	}
	sqlsrv_close($conn);
	exit;
}
?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.