Jump to content

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;
}
?>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.