benphp Posted March 26, 2013 Share Posted March 26, 2013 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; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/276198-problem-with-sqlsrv_query-inserting-then-selecting-inserted-record/ Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.