ASP.NET Database error - sql
I am trying to follow a tutorial online and I have followed the steps exactly however i keep getting an error when trying to write to a database.
Here Is the code for a simple form
#{
var name = string.Empty;
var email = string.Empty;
var subject = string.Empty;
var message = string.Empty;
if (IsPost){
name = Request["txtName"];
email = Request["txtEmail"];
subject = Request["txtSubject"];
message = Request["txtMessage"];
var db = Database.Open("FormAndDataDB");
db.Execute("INSERT INTO ContactLog (Name, Email, Subject, Message, DateSent) " +
"VALUES (#0, #1, #2, #3, #4)", name, email, subject, message, DateTime.Now);
}
}
<doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form action="contact.cshtml" method="POST">
<p>
<label for="txtName">Name:</label><br />
<input type="text" name="txtName" id="txtName" value="#name"/>
</p>
<p>
<label for="txtEmail">Email:</label><br />
<input type="text" name="txtEmail" id="txtEmail" value="#email" />
</p>
<p>
<label for="txtSubject">Subject:</label><br />
<input type="text" name="txtSubject" id="txtSubject" value="#subject" />
</p>
<p>
<label for="txtMessage">Message:</label><br />
<textarea name="txtMessage" id="txtMessage" cols="40" rows="10" >#message</textarea>
</p>
<p>
<input type="submit" value="send" />
</p>
</form>
</body>
</html>
Here is the error i get in visual studio on attempt of execution of the SQL insert statement:
"An exception of type 'System.Data.SqlServerCe.SqlCeException' occurred in System.Data.SqlServerCe.dll but was not handled in user code"
This is the error text returned from SQL and displayed on the webpage:
"The column cannot contain null values. [ Column name = ID,Table name = ContactLog ]"
I have filled out the form completely
Your errors in the question notwithstanding, the problem seems to be that you've got a table (contactLog) with a column (id) that has the NOT NULL attribute attached to it. You are trying to insert a row without a value in said column, and that is causing this error.
To fix this either insert a value into the [ID] column or set the identity attribute to TRUE instead of FALSE on said column and allow it to autogenerate / autoincrement.
My assumption is that even when you fixed the syntax of the insert statement you still couldn't process the insert properly.
You have five columns, but only 3 values.
Your statement is
INSERT INTO ContactLog (Name, Email, Subject, Message, DateSent)
VALUES (#0, #1, #3)
What happened to #2 and #4?
Maybe you need
db.Execute("INSERT INTO ContactLog (Name, Email, Subject, Message, DateSent) "+
"VALUES (#0, #1, #2, #3, #4)",
name, email, subject, message, DateTime.Now);
Related
Using MSXML2.XMLHTTP in MS Access VBA Returning Blank Body Response
I have an MS Access application that sends a unique identifier to a webpage, and the page is SUPPOSED to respond with First Name, Last Name, and DOB. This recently broke, and my best trace at root cause is that the request is returning a blank body from the webpage, and our code uses the body to parse out the returned data. No body, no parsing. There are NO errors as I step through the code. A coworker and I have a combined 3 days fighting with this. We've found the breaking points, but no leads on fixing it. Here's an outline of what's supposed to happen, and details on where troubleshooting has led us: On Click of "Lookup Button" on Access form, Validate ID Number Format Dim sHTML as String If ValidIDFormat(Me.ID.Value & "") Then sHTML = GetDOCData(Me.ID.Value) (I'll spare you the code behind "ValidIDFormat" as that's not the source of the issue) GetDocData (above) is (I think?) the issue. GetDocData is a function that takes the ID Number and sends it as a request to the webpage as follows: Public Function GetDOCData(aID As String) As String Const SUB_NAME As String = "GetDOCData" On Error GoTo ErrCond Dim myurl As String Dim t As Single Dim TimedOut As Boolean Dim Tries As Integer Dim xHTTP As MSXML2.xmlhttp Set xHTTP = New MSXML2.xmlhttp myurl = "http://doclookup.com/GCA00P00/WIQ1/WINQ000" 'Upon inspecting the webpage, I found /GCA00P00/WIQ1/WINQ000 corresponds to the webpage's Form Method "Post" Action ( <form method="post" action="/GCA00P00/WIQ1/WINQ000"> ) TryAgain: xHTTP.Open "POST", myurl, True xHTTP.setRequestHeader "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" xHTTP.setRequestHeader "Accept-Encoding", "gzip, deflate" xHTTP.setRequestHeader "Accept-Language", "en-US,en;q=0.9,ru;q=0.8" xHTTP.setRequestHeader "Cache-Control", "max-age=0" xHTTP.setRequestHeader "Content-Length", "213" xHTTP.setRequestHeader "Host", "doclookup.com" xHTTP.setRequestHeader "Origin", "http://doclookup.com" xHTTP.setRequestHeader "Proxy-Connection", "keep-alive" xHTTP.setRequestHeader "Referer", "http://doclookup.com/GCA00P00/WIQ1/WINQ000" xHTTP.setRequestHeader "Upgrade-Insecure-Requests", "1" xHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" xHTTP.send "K01=WINQ000&DFH_STATE_TOKEN=&DFH_MAP_STATE_TOKEN=&M00_LAST_NAMEI=&M00_FIRST_NAMEI=&M00_MID_NAMEI=&M00_NAME_SUFXI=&M00_DOBCCYYI=&M00_ID_FLD1I=" & left(aID, 2) & "&M00_ID_FLD2I=" & Mid(aID, 3, 1) & "&M00_ID_FLD3I=" & Right(aID, 4) & "&M00_MISCID_FLD1I=&M00_MISCID_FLD2I=" t = Timer Tries = 1 Do While (True) DoEvents If ((Timer - t) > 5) Then TimedOut = True xHTTP.abort GetDOCData = "" Exit Do End If If (xHTTP.ReadyState = 4) Then If (xHTTP.Status <> 200) Then If (Tries < 3) Then Tries = Tries + 1 xHTTP.abort GoTo TryAgain Else TimedOut = True xHTTP.abort GetDOCData = "" Exit Do End If Else TimedOut = False GetDOCData = xHTTP.responseText Debug.Print xHTTP.responseText Exit Do End If End If DoEvents Loop Set xHTTP = Nothing Exit Function ErrCond: EventLogging AppSession.UserName, MSG_TYPE_ERROR, Err.Number, Err.Description, MOD_NAME & "." & SUB_NAME, AppSession.AppSilent Set xHTTP = Nothing End Function Debug.Print output of the response: <!DOCTYPE html> <html><head> <meta http-equiv="Pragma" content="no-cache"/> <meta http-equiv="Expires" content="-1"/> <meta http-equiv="CacheControl" content="no-cache"/> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <link rel="shortcut icon" href="data:;base64,iVBORw0KGgo="/> <script> (function(){ window["bobcmn"] = "11111110101010200000005200000005200000001282ff3ca2200000096300000029application%2fx%2dwww%2dform%2durlencoded300000000300000006/TSPD/300000008TSPD_101300000004http3000000b008f09154e8ab2000c866a39c833f24d99d84e7901aac5a13c0c8ad737654afb25b96b27aba9f9b9008c421cc190a28006d5c954f4b5b362cf850d4f70b2a1ff8e8fcfb526acb91a5740a4c0e36f7d3e7e790a51f2ffbaf98300000107K01%3dWINQ000%26DFH_STATE_TOKEN%3d%26DFH_MAP_STATE_TOKEN%3d%26M00_LAST_NAMEI%3d%26M00_FIRST_NAMEI%3d%26M00_MID_NAMEI%3d%26M00_NAME_SUFXI%3d%26M00_DOBCCYYI%3d%26M00_ID_FLD1I%3d95%26M00_ID_FLD2I%3db%26M00_ID_FLD3I%3d1929%26M00_MISCID_FLD1I%3d%26M00_MISCID_FLD2I%3d200000000"; window.OYm=!!window.OYm;try{(function(){(function(){var S={decrypt:function(S){try{return JSON.parse(function(S){S=S.split("l");var I="";for(var l=0;l<S.length;++l)I+=String.fromCharCode(S[l]);return I}(S))}catch(l){}}};return S={configuration:S.decrypt("123l34l97l99l116l105l118l101l34l58l34l110l111l34l44l34l100l101l98l117l103l103l105l110l103l34l58l34l110l111l34l44l34l109l111l100l117l108l101l49l34l58l34l101l110l97l98l108l101l100l34l44l34l109l111l100l117l108l101l50l34l58l34l101l110l97l98l108l101l100l34l44l34l109l111l100l117l108l101l51l34l58l34l101l110l97l98l108l101l100l34l44l34l109l111l100l117l108l101l52l34l58l34l101l110l97l98l108l101l100l34l125")}})(); var iS=91;try{var JS,LS,OS=_(200)?0:1,ZS=_(567)?0:1,S_=_(300)?0:1;for(var __=(_(912),0);__<LS;++__)OS+=_(989)?1:2,ZS+=(_(404),2),S_+=(_(437),3);JS=OS+ZS+S_;window.jj===JS&&(window.jj=++JS)}catch(i_){window.jj=JS}var o_=!0;function J(S){var I=arguments.length,l=[];for(var Z=1;Z<I;++Z)l.push(arguments[Z]-S);return String.fromCharCode.apply(String,l)} function z_(S){var I=69;!S||document[L(I,187,174,184,174,167,174,177,174,185,190,152,185,166,185,170)]&&document[J(I,187,174,184,174,167,174,177,174,185,190,152,185,166,185,170)]!==J(I,187,174,184,174,167,177,170)||(o_=!1);return o_}function L(S){var I=arguments.length,l=[],Z=1;while(Z<I)l[Z-1]=arguments[Z++]-S;return String.fromCharCode.apply(String,l)}function _i(){}z_(window[_i[O(1086763,iS)]]===_i);z_(typeof ie9rgb4!==O(1242178186108,iS)); z_(RegExp("\x3c")[O(1372114,iS)](function(){return"\x3c"})&!RegExp(O(42798,iS))[O(1372114,iS)](function(){return"'x3'+'d';"})); var ii=window[L(iS,188,207,207,188,190,195,160,209,192,201,207)]||RegExp(J(iS,200,202,189,196,215,188,201,191,205,202,196,191),O(-73,iS))[O(1372114,iS)](window["\x6e\x61vi\x67a\x74\x6f\x72"]["\x75\x73e\x72A\x67\x65\x6et"]),ji=+new Date+(_(283)?392128:6E5),Ji,li,si,SI=window[J(iS,206,192,207,175,196,200,192,202,208,207)],iI=ii?_(896)?24437:3E4:_(789)?7473:6E3; document[L(iS,188,191,191,160,209,192,201,207,167,196,206,207,192,201,192,205)]&&document[L(iS,188,191,191,160,209,192,201,207,167,196,206,207,192,201,192,205)](L(iS,209,196,206,196,189,196,199,196,207,212,190,195,188,201,194,192),function(S){var I=87;document[L(I,205,192,202,192,185,192,195,192,203,208,170,203,184,203,188)]&&(document[J(I,205,192,202,192,185,192,195,192,203,208,170,203,184,203,188)]===O(1058781896,I)&&S[J(I,192,202,171,201,204,202,203,188,187)]?si=!0:document[J(I,205,192,202,192, 185,192,195,192,203,208,170,203,184,203,188)]===L(I,205,192,202,192,185,195,188)&&(Ji=+new Date,si=!1,II()))});function II(){if(!document[J(33,146,150,134,147,154,116,134,141,134,132,149,144,147)])return!0;var S=+new Date;if(S>ji&&(_(848)?582451:6E5)>S-Ji)return z_(!1);var I=z_(li&&!si&&Ji+iI<S);Ji=S;li||(li=!0,SI(function(){li=!1},_(257)?0:1));return I}II();var jI=[_(425)?18598439:17795081,_(80)?2147483647:27611931586,_(166)?1983416588:1558153217]; function JI(S){var I=35;S=typeof S===O(1743045641,I)?S:S[J(I,151,146,118,151,149,140,145,138)](_(696)?24:36);var l=window[S];if(!l[L(I,151,146,118,151,149,140,145,138)])return;var Z=""+l;window[S]=function(S,I){li=!1;return l(S,I)};window[S][J(I,151,146,118,151,149,140,145,138)]=function(){return Z}}for(var LI=(_(728),0);LI<jI[L(iS,199,192,201,194,207,195)];++LI)JI(jI[LI]);z_(!1!==window[J(iS,170,180,200)]);window.IJ={Ll:"08d706d6c9018000e5822dadf90337bb593587216c9ab6a9c485b83578c4437a79e29efc9f34e830ff2af64ab8efa8fb630e6dd1e0826eb0daddd2bd5edfb2a1b1e82309950dfc445dbcd7cec14c66aad4477867c752f7bbeff0a97475a6bb1261632c2feef07f430cba4664d7e896295e4276a6c7e8e1303b350f2e5189a8f59b760816d0b62a13"};function O(S,I){S+=I;return S.toString(36)} function oI(S){var I=+new Date,l;!document[J(46,159,163,147,160,167,129,147,154,147,145,162,157,160,111,154,154)]||I>ji&&(_(911)?801408:6E5)>I-Ji?l=z_(!1):(l=z_(li&&!si&&Ji+iI<I),Ji=I,li||(li=!0,SI(function(){li=!1},_(609)?0:1)));return!(arguments[S]^l)}function _(S){return 55>S}(function zI(I){I&&"number"!==typeof I||("number"!==typeof I&&(I=1E3),I=Math.max(I,1),setInterval(function(){zI(I-10)},I))})(!0);})();}catch(x){}finally{ie9rgb4=void(0);};function ie9rgb4(a,b){return a>>b>>0}; })(); </script> <script type="text/javascript" src="/TSPD/08f09154e8ab20002596bec38bbab41a56da7004c2247af39c737e1fdd1f8257d17ddc6579566094?type=10"></script> <noscript>Please enable JavaScript to view the page content.<br/>Your support ID is: 1436304770756522234.</noscript> </head><body> </body></html> We noticed there is NOTHING returned between the "body" tags in the last 2 lines above ... I also note the "Please enable JavaScript..." message, before the empty tags. However, if this is the root issue, I'm unaware of how to enable JS in VBA. I tried researching this, and couldn't find anything helpful. Between #2 and #3 is where the disconnect occurs: Take webpage response (above) and check if ID that was entered in Access correlates to 1, or multiple records for this person - housed in this website. If (IsSingleID(sHTML)) Then ' "sHTML" here is the returned string from the webpage response in "GetDocData" Function above Person = ParseDOCRecord(Me.ID.Value, sHTML) 'sometimes there are multiple returned values - housed in the website - for the person in question. One person can have multiple records, each given a unique ID. There's a different section of code, and different parsing, if multiple records/multiple IDs are returned. IsSingleID is a Function defined as follows Public Function IsSingleID(aHTML As String) As Boolean Const SUB_NAME As String = "IsSingleID" On Error GoTo ErrCond Dim doc As New MSHTML.HTMLDocument Dim o As Variant IsSingleID = False doc.Body.innerHTML = aHTML For Each o In doc.getElementsByTagName("h2") If (Trim(o.innerText) = "Person Information") Then IsSingleID = True Exit For End If Next Set doc = Nothing Exit Function ErrCond: EventLogging AppSession.UserName, MSG_TYPE_ERROR, Err.Number, Err.Description, MOD_NAME & "." & SUB_NAME, AppSession.AppSilent End Function The code EXITS here! There is no "o" in in doc.getElementsByTagName("h2") Could this be because " doc.Body.innerHTML = aHTML " returns a Blank body? I tried adding a watch to "aHTML" variable to confirm what part(s) of the webpage response (sHTML) is/are sent to "aHTML" variable in above function. But the variable/response was too long for the Watch window. Regardless, the run never reaches the "ParseDOCRecord" Function in: If (IsSingleID(sHTML)) Then Person = ParseDOCRecord(Me.ID.Value, sHTML) The run EXITS "IsSingleID" function, returns to "Lookup Button" Function (#1), and drops to a 'catch all' kind of message box, hard coded to return: MsgBox "Unable to get information from DOC site." I'm scratching my head on this. Troubleshooting steps we've tried: We tried updating references to Microsoft XML,v6.0 and using MSXML2.XMLHTTP60 instead. My reasoning was maybe there was a change to the older library that was picked up in the latest version. Tried removing "/GCA00P00/WIQ1/WINQ000" from the URL, and simply using "doclookup.com" Tried replacing "h2" tag with "form" tag, in doc.getElementsByTagName("h2") because I noticed I didn't see an "h2" tag in the inspected webpage Here is the code from Form section of the webpage: <form method="post" action="/GCA00P00/WIQ1/WINQ000"> <div class="border"> <input type="hidden" name="K01" value="WINQ000"> <input type="hidden" name="DFH_STATE_TOKEN" value="adyqlisv"> <input type="hidden" name="DFH_MAP_STATE_TOKEN" value=""> <div class="pair"> <label for="M00_LAST_NAMEI">Last Name:</label> <input type="text" size="18" maxlength="18" name="M00_LAST_NAMEI" value="" id="M00_LAST_NAMEI"> </div> <div class="pair"> <label for="M00_FIRST_NAMEI">First Name:</label> <input type="text" size="11" maxlength="11" name="M00_FIRST_NAMEI" value="" id="M00_FIRST_NAMEI"> </div> <div class="pair"> <label for="M00_MID_NAMEI">Middle Init:</label> <input type="text" size="1" maxlength="1" name="M00_MID_NAMEI" value="" id="M00_MID_NAMEI"> </div> <div class="pair"> <label for="M00_NAME_SUFXI">Name Suffix:</label> <input type="text" size="3" maxlength="3" name="M00_NAME_SUFXI" value="" id="M00_NAME_SUFXI"> (SR, JR, etc.) </div> <div class="pair"> <label for="M00_DOBCCYYI">Birth Year:</label> <input type="text" size="4" maxlength="4" name="M00_DOBCCYYI" value="" id="M00_DOBCCYYI"> (Optional, see above) </div> <div class="pair"> <label for="M00_DIN_FLD1I">DIN:<span class="hide"> Two digit number </span></label> <input type="text" size="2" maxlength="2" name="M00_ID_FLD1I" value="" id="M00_DIN_FLD1I" onfocus="select()" onkeyup="KeyPress(this,event,2,'WINQM00.form.M00_DIN_FLD2I.focus()')"> - <label for="M00_DIN_FLD2I" class="hide">One character alpha</label> <input type="text" size="1" maxlength="1" name="M00_ID_FLD2I" value="" id="M00_DIN_FLD2I" onfocus="select()" onkeyup="KeyPress(this,event,1,'WINQM00.form.M00_DIN_FLD3I.focus()')"> - <label for="M00_DIN_FLD3I" class="hide">Four digit number</label> <input type="text" size="4" maxlength="4" name="M00_ID_FLD3I" value="" id="M00_DIN_FLD3I" onfocus="select()"> (ID Number, format 99-A-9999, example 95-A-9876) </div> <div class="pair"> <label for="M00_NYSID_FLD1I">NYSID:<span class="hide"> Eight digit number</span></label> <input type="text" size="8" maxlength="8" name="M00_MISCID_FLD1I" value="" id="M00_MISCID_FLD1I" onfocus="select()" onkeyup="KeyPress(this,event,8,'WINQM00.form.M00_MISCID_FLD2I.focus()')"> - <label for="M00_MISCID_FLD2I" class="hide">One character alpha</label> <input type="text" size="1" maxlength="1" name="M00_MISCID_FLD2I" value="" id="M00_MISCID_FLD2I" onfocus="select()"> (For InterDepartmental Use Only; MISC ID Number) </div> <div class="aligncenter "> <input type="submit" value="Submit"> <input type="button" onclick="javascript: location.href = location.href;" value="Reset"> </div> </div> </form> What am I missing? I hope I've explained this with the right amount of detail... How can I get this request to return data again? Follow up based on comments/comment threads below... I did a search for a record on the website (not one within the application) in order to generate response log from Network tab of webpage. DIN # 18B3079 screenshot of response as follows:
Converting Pdo OOP To Mysqli Procedural
Folks, :) My 3+ pages are all in mysqli procedural. I cannot just switch to pdo and oop and throw 6 mnths of work down the drain! And so, let's try converting the following code suggestion by another to mysqli procedural. I really need the following code converted to mysqli procedural from pdo oop. Once that is done, my 7 months project will come to an end. And, I can move-on to learning pdo. Right now, can't afford to jump into pdo without finishing my current project. So, who will help me convert ? Other newbies would learn from your conversion. Thanks! [code] /* ERROR HANDLING */ declare(strict_types=1); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); include 'config.php'; // check if user is already logged in if (is_logged() === true) { //Redirect user to homepage page after 5 seconds. header("refresh:2;url=home.php"); exit; // } if ( array_key_exists('login_username_or_email', $_POST) && array_key_exists('login_password' , $_POST) ) { $usernameoremail = trim($_POST["login_username_or_email"]); // $password = $_POST["login_password"]; // don't bother trimming, they can't enter it right, don't let them log in! $stmt = $conn->prepare('SELECT ids, usernames, passwords, emails, accounts_activations_statuses FROM users WHERE ' . ( strpos($usernameoremail, '#') === false) ? 'usernames' : 'emails' ) . ' = ? '); $stmt->bind_param('s', $_POST['login_username_or_email']); $stmt->execute(); $stmt->bind_result( $db_id, $db_username, $db_password, $db_email, $db_account_activation_status ); if ( $stmt->fetch() && password_verify($_POST['login_password'], $db_password) ) { echo ' <p>Login Successful</p> <dl> <dt>User Id</dt> <dd>', $db_id, '</dd> <dt>E-Mail</dt> <dd>', $db_email, '</dd> <dt>Username</dt> <dd>', $db_username, '</dd> <dt>Activation Stats</dt> <dd>', $db_account_activation_status, '</dd> </dl> '; } else echo '<p>Invalid username or password</p>'; $stmt->close(); } else echo '<p>Missing username or password</p>'; ?> <!DOCTYPE html> <html> <head> <title><?php $site_name?> Member Login Page</title> <meta charset="utf-8"> </head> <body> <div class = "container"> <form method="post" action=""> <h3><?= $site_name ?> Member Login Form</h3> <fieldset> <label for="login_name">Username/Email:</label> <input type="text" name="login_username_or_email" id="login_name"> <br> <label for="login_pass">Password:</label> <input type="password" name="login_password" id="login_pass"> </fieldset> <div class="submitsAndHiddens"> <button type="submit">Login</button><br> Forgot your Password?<br> Register New Account </div> </form> </div> </body> [/code]
Dreamweaver ASP command INSERT INTO not passing value
Hi I am trying to create an INSERT INTO script in Dreamweaver Command and ASP. If I use a static value it works fine, but when I try to declare a variable I get the following error message Microsoft OLE DB Provider for ODBC Drivers error '80040e14' [Sybase][ODBC Driver][Adaptive Server Anywhere]Primary key for table 'testing' is not unique /coding/Untitled-3.asp, line 30 Now the reason it is telling me the primary key is not unique is it is passing a null value, rather than the value of my field. Code below; <%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%> <% Dim Command1__product Command1__product = Request.Form("product") %> <!--#include file="Connections/Conn_PSCRM_Demo.asp" --> <% ' IIf implementation Function MM_IIf(condition, ifTrue, ifFalse) If condition = "" Then MM_IIf = ifFalse Else MM_IIf = ifTrue End If End Function %> <% Set Command1 = Server.CreateObject ("ADODB.Command") Command1.ActiveConnection = MM_Conn_PSCRM_Demo_STRING Command1.CommandText = "INSERT INTO testing (prodref) VALUES (?)" Command1.Parameters.Append Command1.CreateParameter("product", 201, 1, 25, MM_IIF(Request.Form("Field1") , Request.Form("Field1") , Command1__product & "")) Command1.CommandType = 1 Command1.CommandTimeout = 0 Command1.Prepared = true Command1.Execute() %> <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> </head> <body> <form action="" method="post" name="form" id="form"> <label for="Field1"></label> <input name="Field1" type="text" id="Field1" value="33399"> </form> </body> </html>
According to my comment - you'll have to check if your form has been posted or your site has just been initially loaded. In your question the code will be executed everytime the site has been loaded - that's why it works when you provide hardcoded values. Anything like this code will do the trick <%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%> <% If Request.Form("SUBMITBUTTON") <> "" then Dim Command1__product Command1__product = Request.Form("product") ' all your code goes here! %>
Bit of a rookie error, I wasn't declaring the form variable. I have added a Bindings Request.Form and all is working.
ASP.NET Razor split record and increase by one
in my code I'm trying to display in a text box the record that follows the last one of my database. For example, if my last record is A560 I want to display A561. To achieve this I know I have to split the record and then manipulate it, but I haven't had any luck. Here is what the database looks like: Point_ID Project No. Project Manager Comments A558 1304 Oscar Duran Found destroyed A559 1304 Oscar Duran Helicopter access A560 1356 Julio Bravo Airport parking lot This is my code so far: #{ Layout = "~/_Layout.cshtml"; var db = Database.Open("ControlPoints"); var SelectCommand = "SELECT * FROM( SELECT TOP 5 * FROM AllControlMergedND WHERE Point_ID LIKE 'A___' ORDER BY Point_ID DESC )AS BaseData Order BY Point_ID ASC"; var SearchTerm = ""; if(!Request.QueryString["SearchCP"].IsEmpty() ){ SelectCommand = "SELECT * FROM AllControlMergedND WHERE Point_ID = #0"; SearchTerm = Request.QueryString["SearchCP"]; } if(!Request.QueryString["SearchProject"].IsEmpty() ){ SelectCommand = "SELECT * FROM AllControlMergedND WHERE [Project Used on] LIKE #0"; SearchTerm = "%" + Request["SearchProject"] + "%"; } var SelectData = db.Query(SelectCommand, SearchTerm); var grid = new WebGrid(source: SelectData, rowsPerPage: 10); } #{ Validation.RequireField("Point_ID", " Required"); Validation.RequireField("ProjectNo", " Required"); Validation.RequireField("ProjectManager", " Required"); var Point_ID = ""; var ProjectNo = ""; var ProjectManager = ""; if(IsPost && Validation.IsValid() ){ Point_ID = Request.Form["Point_ID"]; ProjectNo = Request.Form["ProjectNo"]; ProjectManager = Request.Form["ProjectManager"]; db = Database.Open("ControlPoints"); var InsertCommand = "INSERT INTO AllControlMergedND ([Point_ID], [Project No.], [Project Manager]) VALUES(#0, #1, #2)"; db.Execute(InsertCommand, Point_ID, ProjectNo, ProjectManager); } var SelectLastCP = "SELECT TOP 1 Point_ID FROM AllControlMergedND WHERE Point_ID LIKE 'A___' ORDER BY Point_ID DESC"; var SelectData2 = db.QuerySingle(SelectLastCP); var SuggestedPoint_ID = SelectData2.Point_ID; } <h2>Airborne Imaging Control Points Database</h2><br/><br/> <form method="get"> <fieldset> <legend>Search Criteria</legend> <div> <p><label for="SearchCP">Control Point ID:</label> <input type="text" name="SearchCP" value="#Request.QueryString["SearchCP"]" /> <input type="submit" value="Search"/></p> </div> <div> <p><label for="SearchProject">Project:</label> <input type="text" name="SearchProject" value="#Request.QueryString["SearchProject"]" /> <input type="Submit" value="Search" /></p> </div> </fieldset> </form> <div> #grid.GetHtml( tableStyle: "grid", headerStyle: "head", alternatingRowStyle: "alt", columns: grid.Columns( grid.Column("Point_ID"), grid.Column("Project No."), grid.Column("Project Used on"), grid.Column("WGS84 Lat"), grid.Column("WGS84 Long"), grid.Column("Ellips_Ht"), grid.Column("Project Manager"), grid.Column("Comments") ) ) <br/><br/> </div> <form method="post"> <fieldset> <legend>Create Control Point(s)</legend> <p><label for="Point_ID">Point ID:</label> <input type="text" name="Point_ID" value="#SuggestedPoint_ID" /> #Html.ValidationMessage("Point_ID")</p> <p><label for="ProjectNo">Project No:</label> <input type="text" name="ProjectNo" value="#Request.Form["ProjectNo"]" /> #Html.ValidationMessage("ProjectNo")</p> <p><label for="ProjectManager">Project Manager:</label> <input type="text" name="ProjectManager" value="#Request.Form["ProjectManager"]" /> #Html.ValidationMessage("ProjectManager")</p> <p><input type="submit" name="ButtonConfirm" value="Confirm" /></p> </fieldset> </form> As you can see, all I am able to do is to display the last record of my database in the text box, which in this case would be A560. The variable 'SuggestedPoint_ID' is holding that record. I have tried converting the data type, but had no success. Any help would be greatly appreciated. Update: What I need is to do the following. Split A560 in two parts 'A' and '560'. Then increment '560' by one to obtain '561' and finally attach 'A' again to '561' in order to obtain the next increment 'A561'.
If you are trying to convert "A560" to int for example then it won't work because you don't have a valid number. A needs to be removed. var SuggestedPoint_ID = SelectData2.Point_ID.Replace("A", ""); This is not my recommended way to do it as A could be anything such as AA or B or ZZZZ. My point is that you need to describe what you need to get a better solution to your problem. UPDATE var source = "A560"; var lhs = source.Substring(0, 1); var tmp = source.Replace(lhs, ""); int rhs; if(int.TryParse(tmp, out rhs)) { rhs++; } var result = string.Format("{0}{1}", lhs, rhs);
Oracle SQL Error: How to Debug this issue
Using: select name, id from "TEST" where id :2 AND name :1 order by id desc I am getting ORA: 00904 "TEST"."NAME": invalid identifier error but the wierd part is that I have checked my test table and it does not have NAME field but it has name field, I have also checked all the references which is made from that table and all other constraints but still it gives me same error. I do not know why, is there a way where I can check all the columns of the database for NAME column name or any other debuggind approach recommended would be highly welcomed. DESC TEST; Name Null Type id NOT NULL NUMBER(11) name VARCHAR2(29) 2 rows selected EDIT DESC TEST Name Null Type ------------------------------ -------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ID NOT NULL NUMBER(11) NAME VARCHAR2(29) 2 rows selected Java Code public String searchExecute(HttpServletRequest req, javax.servlet.ServletContext ctx, String nextPage){ // ESCA-JAVA0266: System.out.println("This is Awesome"); // ESCA-JAVA0266: System.out.println("id:"+req.getParameter("s_1985")); // ESCA-JAVA0266: System.out.println("name:"+req.getParameter("s_1984")); boolean bDisplayAll = StringUtils.stringToBoolean(req.getParameter("display_all")); if(bDisplayAll) // ESCA-JAVA0034: req.setAttribute("c_display_all", "Y"); req.setAttribute("c_search_submitted", "Y"); return nextPage; } JSP Code <%# page import="att.leadx.dbutils.AppUtils" %> <%# page import="java.util.*" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859- 1"> </head> <link rel=stylesheet type=text/css href="leadx.css"> <body bgcolor="#FFFFFF"><BR> <form NAME="forma" ACTION="dispatcher" METHOD="post"> <INPUT TYPE="hidden" name="action" value=""> <input type=hidden name="c_master" value="TEST_SEARCH"> <% request.setAttribute("c_form", "TEST_SEARCH"); request.setAttribute("c_top_title","PROFILE > TEST_SEARCH"); request.setAttribute("c_top_link_image","images/setup_sm.gif"); request.setAttribute("c_top_link_action","user.search.setup"); request.setAttribute("c_top_link_app_func","search_setup"); request.setAttribute("c_top_link_alt_display","Setup search criteria"); %> <jsp:include page="j_custom_search.jsp" flush="true" /> <table width="94%" border="0" cellspacing="1" cellpadding="3" align=center> <tr> <td colspan=4 align=center> <INPUT TYPE="submit" value="Search" class=prismsbutton onclick="document.forma.action.value ='cep.project.search.execute'"> </td> <td colspan=4 align=center> <INPUT TYPE="button" value="Cancel" class=prismsbutton onclick="window.history.back()"> </td> </tr> </table> </form> <form NAME="formd" ACTION="dispatcher" METHOD="post"> <input type="hidden" name="c_jsp" value="j_test_dynamic_search.jsp"> <% request.setAttribute("c_master", "TEST_SEARCH"); request.setAttribute("c_html_form","formd"); request.setAttribute("c_list_id","1984"); request.setAttribute("c_search_form","TEST_SEARCH"); Object args[] = att.utils.DataStore.arg(att.leadx.dbutils.AppUtils.getLoggedInUser(request), att.utils.DataStore.TYPE_NUMERIC); request.setAttribute("c_args", args); if (att.utils.StringUtils.stringToBoolean((String)request.getAttribute("c_search_submitted"))){ %> <jsp:include page="j_master_detail_dlist.jsp" flush="true" /> <% } %> </form> <%! private void o(String s){ if (att.leadx.dbutils.AppUtils.inDebug()) System.out.println("[J_USER_SEARCH.JSP] " + s); } %> SQL Statement select name, id from TEST where name = :1 AND id = :2 order by id desc Error Message Aug 16, 2010 5:22:21 PM org.apache.catalina.core.ApplicationDispatcher invoke SEVERE: Servlet.service() for servlet jsp threw exception java.sql.SQLException: ORA-00936: missing expression at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:180) at oracle.jdbc.ttc7.TTIoer.processError(TTIoer.java:208) at oracle.jdbc.ttc7.Oall7.receive(Oall7.java:543) at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1451) at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:651) at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2110) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2324) at oracle.jdbc.driver.OracleStatement.executeQuery(OracleStatement.java:627) at att.utils.DataStore.retrieve(DataStore.java:724) at org.apache.jsp.j_005fmaster_005fdetail_005fdlist_jsp._jspService(j_005fmaster_005fdetail_005fdlist_jsp.java:566) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:659) at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:565) at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:493) at org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:965) at org.apache.jsp.j_005ftest_005fdynamic_005fsearch_jsp._jspService(j_005ftest_005fdynamic_005fsearch_jsp.java:102) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:659) at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:457) at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:395) at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:311) at att.leadx.nav.Dispatcher.service(Dispatcher.java:113) at javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:172) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:470) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:108) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:174) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:879) at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:665) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:528) at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:81) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:689) at java.lang.Thread.run(Unknown Source) Thanks
SELECT * FROM ALL_TAB_COLS WHERE UPPER(COLUMN_NAME) = 'NAME'; will show you all columns called NAME EDIT: Based on your comment, aren't you missing the operators in your WHERE clause? ie = select name, id from "TEST" where id :2 -- Surely you mean: id = :2 AND name :1 -- Surely you mean: name = :2 order by id desc EDIT 2: Based on the SQL*Plus output, it looks like you've created the table with lower-case column names. Whilst this is possible and valid it's usually just hard work. I'd recreate the columns with upper case names. (as Alex said) EDIT 3: I think... SELECT "id", "name" FROM TEST WHERE "id" = :1 AND "name" = :2 ORDER BY "id" desc; should work
It's a good idea not to surround column and table names with double-quotation marks unless you are know what you are doing and confident you need that. In Oracle, database object names (including table and columns) are not case-sensitive and assumed upper-case unless you include them into double-quotes. E.g, if a table created as TEST, it can be referred to as test, Test or TesT or "TEST". But if it is created as "Test", you will only be able to refer to it as "Test" (in double quotation marks). All the other ways will result in "invalid identifier" error.