Alpha Software Mobile Development Tools:   Alpha Anywhere    |   Alpha TransForm subscribe to our YouTube Channel  Follow Us on LinkedIn  Follow Us on Twitter  Follow Us on Facebook

Announcement

Collapse

The Alpha Software Forum Participation Guidelines

The Alpha Software Forum is a free forum created for Alpha Software Developer Community to ask for help, exchange ideas, and share solutions. Alpha Software strives to create an environment where all members of the community can feel safe to participate. In order to ensure the Alpha Software Forum is a place where all feel welcome, forum participants are expected to behave as follows:
  • Be professional in your conduct
  • Be kind to others
  • Be constructive when giving feedback
  • Be open to new ideas and suggestions
  • Stay on topic


Be sure all comments and threads you post are respectful. Posts that contain any of the following content will be considered a violation of your agreement as a member of the Alpha Software Forum Community and will be moderated:
  • Spam.
  • Vulgar language.
  • Quotes from private conversations without permission, including pricing and other sales related discussions.
  • Personal attacks, insults, or subtle put-downs.
  • Harassment, bullying, threatening, mocking, shaming, or deriding anyone.
  • Sexist, racist, homophobic, transphobic, ableist, or otherwise discriminatory jokes and language.
  • Sexually explicit or violent material, links, or language.
  • Pirated, hacked, or copyright-infringing material.
  • Encouraging of others to engage in the above behaviors.


If a thread or post is found to contain any of the content outlined above, a moderator may choose to take one of the following actions:
  • Remove the Post or Thread - the content is removed from the forum.
  • Place the User in Moderation - all posts and new threads must be approved by a moderator before they are posted.
  • Temporarily Ban the User - user is banned from forum for a period of time.
  • Permanently Ban the User - user is permanently banned from the forum.


Moderators may also rename posts and threads if they are too generic or do not property reflect the content.

Moderators may move threads if they have been posted in the incorrect forum.

Threads/Posts questioning specific moderator decisions or actions (such as "why was a user banned?") are not allowed and will be removed.

The owners of Alpha Software Corporation (Forum Owner) reserve the right to remove, edit, move, or close any thread for any reason; or ban any forum member without notice, reason, or explanation.

Community members are encouraged to click the "Report Post" icon in the lower left of a given post if they feel the post is in violation of the rules. This will alert the Moderators to take a look.

Alpha Software Corporation may amend the guidelines from time to time and may also vary the procedures it sets out where appropriate in a particular case. Your agreement to comply with the guidelines will be deemed agreement to any changes to it.



Bonus TIPS for Successful Posting

Try a Search First
It is highly recommended that a Search be done on your topic before posting, as many questions have been answered in prior posts. As with any search engine, the shorter the search term, the more "hits" will be returned, but the more specific the search term is, the greater the relevance of those "hits". Searching for "table" might well return every message on the board while "tablesum" would greatly restrict the number of messages returned.

When you do post
First, make sure you are posting your question in the correct forum. For example, if you post an issue regarding Desktop applications on the Mobile & Browser Applications board , not only will your question not be seen by the appropriate audience, it may also be removed or relocated.

The more detail you provide about your problem or question, the more likely someone is to understand your request and be able to help. A sample database with a minimum of records (and its support files, zipped together) will make it much easier to diagnose issues with your application. Screen shots of error messages are especially helpful.

When explaining how to reproduce your problem, please be as detailed as possible. Describe every step, click-by-click and keypress-by-keypress. Otherwise when others try to duplicate your problem, they may do something slightly different and end up with different results.

A note about attachments
You may only attach one file to each message. Attachment file size is limited to 2MB. If you need to include several files, you may do so by zipping them into a single archive.

If you forgot to attach your files to your post, please do NOT create a new thread. Instead, reply to your original message and attach the file there.

When attaching screen shots, it is best to attach an image file (.BMP, .JPG, .GIF, .PNG, etc.) or a zip file of several images, as opposed to a Word document containing the screen shots. Because Word documents are prone to viruses, many message board users will not open your Word file, therefore limiting their ability to help you.

Similarly, if you are uploading a zipped archive, you should simply create a .ZIP file and not a self-extracting .EXE as many users will not run your EXE file.
See more
See less

xbasic - insert into sql table

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    xbasic - insert into sql table

    I have a server-side event 'beforesearch' that basically every time a search is made in a grid, I have data that is captured and collected into a table called 'user_tracking'. This has been working fine as a .dbf. But I am converting everything over to sql. I went through all of the xbasic help videos, and created what I thought would be the correct statement to write to this table, but it is not working. Wondering if someone can take a look at this and tell me where my error(s) are:


    function BeforeSearch as v (SearchDataSubmitted as P, Args as p, PageVariables as p)
    with PageVariables
    end with

    'Declare session variables
    DIM session.UserID as c
    DIM session.Account_Number as c
    DIM session.Sales_Rep as c
    DIM session.Vendor as c
    DIM session.Part as c
    DIM session.Int_Ext as c

    'Get currrent user id
    session.UserID = a5ws_getcurrentuser()

    'Check for specific vendor search
    session.Vendor = if(SearchDataSubmitted.Manufacturer = null_value(),"None",SearchDataSubmitted.Manufacturer)

    'Check for specific part number search
    session.Part = if(SearchDataSubmitted.Part_number = null_value(),"None",SearchDataSubmitted.Part_number)

    'Open usersregistered table to retrieve account number and sales rep based on user id
    tbl = table.open("[PathAlias.ADB_Path]\usersregistered_sql")
    query.filter = "username="+quote(var->session.UserID)
    query.order = ""
    qry = tbl.query_create()
    session.Account_Number = alltrim(tbl.ACCOUNT_NUMBER)
    session.Sales_Rep = alltrim(tbl.SALES_REP)

    tbl.close()



    'check if user is internal or external
    session.Int_Ext = if(session.Sales_Rep = "Internal","Internal","External" )


    'write info to user tracking table

    dim cn as sql::Connection
    flag = cn.open("::Name::snap-sql")

    dim sqlCommand as c

    sqlInsert = "Insert into user_tracking (userid, account_number, date, page_title, event_type, sales_rep, vendor_specified, part_specified, int_ext, client_type, ip_address) Values (:newuserid, :newaccount_number, :newdate, :newpage_title, :newevent_type, :newsales_rep, :newvendor_specified, :newpart_specified, :newint_ext, :newclient_type, :newip_address)"

    dim args as sql::arguments
    args.add("newuserid", "session.UserID")
    args.add("newaccount_number", "session.Account_Number")
    args.add("newdate", "date()")
    args.add("newpage_title", "Cameras")
    args.add("newevent_type", "Product Search")
    args.add("newsales_rep", "session.Sales_Rep")
    args.add("newvendor_specified", "session.Vendor")
    args.add("newpart_specified", "session_Part")
    args.add("newint_ext", "session_Int_Ext")
    args.add("newclient_type", "Desktop")
    args.add("newip_address", "request.remote_addr")


    flag = cn.execute(sqlCommand, sqlInsert, args)



    end function

    #2
    Re: xbasic - insert into sql table

    Here's what I see...

    Do not dim session vars... it is unnecessary.
    Use args.set... not args.add. .add just adds. .set adds or re-sets if already established.
    You are putting quotes around the session vars you're using in the args... therefore the session var values are not being evaluated. Same with that one request var... and the date().

    Code:
    args.add("newuserid", session.UserID)
    args.set("newaccount_number", session.Account_Number)
    args.set("newdate", date())
    args.set("newpage_title", "Cameras")
    args.set("newevent_type", "Product Search")
    args.set("newsales_rep", session.Sales_Rep)
    args.set("newvendor_specified", session.Vendor)
    args.set("newpart_specified", session_Part)
    args.set("newint_ext", session_Int_Ext)
    args.set("newclient_type", "Desktop")
    args.set("newip_address", request.remote_addr)
    Using date() will also mess you up since SQL wants to see yyyy-MM-dd format.

    What you can do for date() is use the SQL_Date() function... which is horribly documented.

    Do something like this...

    args.set("newdate",sql_date(date(),2))

    sql_date results in your date being properly formatted, but enclosed in {}... which will blow up a sql statement. Why this could ever be considered a sql date is an Alpha trademark.

    The optional 2 of sql_date fixes this issue. Completely undocumented, of course.
    Last edited by Davidk; 03-05-2018, 07:27 PM.

    Comment


      #3
      Re: xbasic - insert into sql table

      Thanks for the feedback. I made the suggested changes, so now it all looks like this:


      function BeforeSearch as v (SearchDataSubmitted as P, Args as p, PageVariables as p)
      with PageVariables
      end with

      'Get currrent user id
      session.UserID = a5ws_getcurrentuser()

      'Check for specific vendor search
      session.Vendor = if(SearchDataSubmitted.Manufacturer = null_value(),"None",SearchDataSubmitted.Manufacturer)

      'Check for specific part number search
      session.Part = if(SearchDataSubmitted.Part_number = null_value(),"None",SearchDataSubmitted.Part_number)

      'Open usersregistered table to retrieve account number and sales rep based on user id
      tbl = table.open("[PathAlias.ADB_Path]\usersregistered_sql")
      query.filter = "username="+quote(var->session.UserID)
      query.order = ""
      qry = tbl.query_create()
      session.Account_Number = alltrim(tbl.ACCOUNT_NUMBER)
      session.Sales_Rep = alltrim(tbl.SALES_REP)

      tbl.close()



      'check if user is internal or external
      session.Int_Ext = if(session.Sales_Rep = "Internal","Internal","External" )


      'write info to user tracking table

      dim cn as sql::Connection
      flag = cn.open("::Name::snap-sql")

      dim sqlCommand as c

      sqlInsert = "Insert into user_tracking (userid, account_number, date, page_title, event_type, sales_rep, vendor_specified, part_specified, int_ext, client_type, ip_address) Values (:newuserid, :newaccount_number, :newdate, :newpage_title, :newevent_type, :newsales_rep, :newvendor_specified, :newpart_specified, :newint_ext, :newclient_type, :newip_address)"

      dim args as sql::arguments
      args.set("newuserid", session.UserID)
      args.set("newaccount_number", session.Account_Number)
      args.set("newdate", sql_date(date(),2))
      args.set("newpage_title", "Cameras")
      args.set("newevent_type", "Product Search")
      args.set("newsales_rep", session.Sales_Rep)
      args.set("newvendor_specified", session.Vendor)
      args.set("newpart_specified", session_Part)
      args.set("newint_ext", session_Int_Ext)
      args.set("newclient_type", "Desktop")
      args.set("newip_address", request.remote_addr)


      flag = cn.execute(sqlCommand, sqlInsert, args)



      end function





      For some reason it is still not writing to my table. I also opened up code editor to verify a few things and this was my result:


      dim cn as sql::Connection
      flag = cn.open("::Name::snap-sql")
      ?flag
      = .T.


      dim sqlCommand as c

      sqlInsert = "Insert into user_tracking (userid, account_number, date, page_title, event_type, sales_rep, vendor_specified, part_specified, int_ext, client_type, ip_address) Values (:newuserid, :newaccount_number, :newdate, :newpage_title, :newevent_type, :newsales_rep, :newvendor_specified, :newpart_specified, :newint_ext, :newclient_type, :newip_address)"

      dim args as sql::arguments
      args.set("newuserid", session.UserID)
      args.set("newaccount_number", session.Account_Number)
      args.set("newdate", sql_date(date(),2))
      args.set("newpage_title", "Cameras")
      args.set("newevent_type", "Product Search")
      args.set("newsales_rep", session.Sales_Rep)
      args.set("newvendor_specified", session.Vendor)
      args.set("newpart_specified", session_Part)
      args.set("newint_ext", session_Int_Ext)
      args.set("newclient_type", "Desktop")
      args.set("newip_address", request.remote_addr)


      flag = cn.execute(sqlCommand, sqlInsert, args)
      ?flag
      = .T.




      end function
      ERROR: Mismatched end of loop or if-block


      Not sure if the error at the end here has anything to do with my issue or not. Any additional thoughts? Thanks!

      Comment


        #4
        Re: xbasic - insert into sql table

        You really need to add a debug(1) statement to your code and debug through it in Live or Working Preview.

        This statement is wrong...

        flag = cn.execute(sqlCommand, sqlInsert, args)
        I don't know what sqlCommand is. It should be...

        Code:
        flag = cn.execute(sqlInsert, args)

        Comment


          #5
          Re: xbasic - insert into sql table

          Thanks for the suggestion. I removed sqlCommand. After running in live preview with debug(1) statement, here are the errors that I saw:

          args.set("newpart_specified", session_Part) --------------> Variable "session_Part" not found.
          args.set("newint_ext", session_Int_Ext) -----------------------> Variable "session_Int_Ext" not found.
          flag = cn.execute(sqlinsert,args) -------------------------> Argument 2 must be an object of type SQL::Arguments or SQL::TableInfo

          Comment


            #6
            Re: xbasic - insert into sql table

            session.Part and session.Int_Ext. You've got a "_" after session instead of a "."

            Comment


              #7
              Re: xbasic - insert into sql table

              Oh wow, you are absolutely right on that. So then really the last error I can't figure out is this one:

              flag = cn.execute(sqlinsert,args) -------------------------> Argument 2 must be an object of type SQL::Arguments or SQL::TableInfo

              Comment


                #8
                Re: xbasic - insert into sql table

                You'd have to post the full function again... I don't see anything wrong with that statement.

                Comment


                  #9
                  Re: xbasic - insert into sql table

                  Here is the entire function:

                  function BeforeSearch as v (SearchDataSubmitted as P, Args as p, PageVariables as p)
                  with PageVariables
                  end with


                  'Get currrent user id
                  session.UserID = a5ws_getcurrentuser()

                  'Check for specific vendor search
                  session.Vendor = if(SearchDataSubmitted.Manufacturer = null_value(),"None",SearchDataSubmitted.Manufacturer)

                  'Check for specific part number search
                  session.Part = if(SearchDataSubmitted.Part_number = null_value(),"None",SearchDataSubmitted.Part_number)

                  'Open usersregistered table to retrieve account number and sales rep based on user id
                  tbl = table.open("[PathAlias.ADB_Path]\usersregistered_sql")
                  query.filter = "username="+quote(var->session.UserID)
                  query.order = ""
                  qry = tbl.query_create()
                  session.Account_Number = alltrim(tbl.ACCOUNT_NUMBER)
                  session.Sales_Rep = alltrim(tbl.SALES_REP)

                  tbl.close()

                  'check if user is internal or external
                  session.Int_Ext = if(session.Sales_Rep = "Internal","Internal","External" )


                  'write info to user tracking table

                  dim cn as sql::Connection
                  flag = cn.open("::Name::snap-sql")


                  sqlinsert = "insert into user_tracking (userid, account_number, date, page_title, event_type, sales_rep, vendor_specified, part_specified, int_ext, client_type, ip_address))values (:newuserid, :newaccount_number, :newdate, :newpage_title, :newevent_type, :newsales_rep, :newvendor_specified, :newpart_specified, :newint_ext, :newclient_type, :newip_address)"

                  Dim args as sql::arguments


                  args.set("newuserid", session.UserID)
                  args.set("newaccount_number", session.Account_Number)
                  args.set("newdate", sql_date(date(),2))
                  args.set("newpage_title", "Cameras")
                  args.set("newevent_type", "Product Search")
                  args.set("newsales_rep", session.Sales_Rep)
                  args.set("newvendor_specified", session.Vendor)
                  args.set("newpart_specified", session.Part)
                  args.set("newint_ext", session.Int_Ext)
                  args.set("newclient_type", "Desktop")
                  args.set("newip_address", request.remote_addr)



                  flag = cn.execute(sqlinsert, args)



                  As a side note, I installed the pre-release for today, which includes an xbasic SQL actions code generator. I ran through the genie, and this is what it created:

                  dim cn as sql::connection
                  dim flag as l
                  flag = cn.open("::Name::snap-sql")
                  if flag = .f. then
                  'there was an error
                  dim errorText as c
                  errorText = cn.callresult.text
                  end
                  end if
                  'turn on portable SQL
                  cn.PortableSQLEnabled = .t.
                  dim SQL as c
                  sql = "INSERT INTO user_tracking(USERID,ACCOUNT_NUMBER,DATE,PAGE_TITLE,EVENT_TYPE,SALES_REP,VENDOR_SPECIFIED,PART_SPECIFIED,INT_EXT,CLIENT_TYPE,IP_ADDRESS) VALUES (:USERID,:ACCOUNTNUMBER,:DATE,:PAGETITLE,:EVENTTYPE,:SALESREP,:VENDORSPECIFIED,:PARTSPECIFIED,:INTEXT,:CLIENTTYPE,:IPADDRESS)"
                  dim args as sql::arguments
                  args.add("USERID","session.UserID")
                  args.add("ACCOUNTNUMBER","session.Account_Number")
                  args.add("DATE","sql_date(date(),2)")
                  args.add("PAGETITLE","Cameras")
                  args.add("EVENTTYPE","Product Search")
                  args.add("SALESREP","session.Sales_Rep")
                  args.add("VENDORSPECIFIED","session.Vendor")
                  args.add("PARTSPECIFIED","session.Part")
                  args.add("INTEXT","session.Int_Ext")
                  args.add("CLIENTTYPE","Desktop")
                  args.add("IPADDRESS","request.remote_addr")
                  'execute the SQL
                  flag = cn.execute(sql,args)
                  if flag = .f. then
                  'there was an error
                  dim errorText as c
                  errorText = cn.callresult.text
                  cn.close()
                  end
                  end if
                  dim rowsInserted as n
                  'get the number of rows that were inserted
                  rowsInserted = cn.CallResult.rowsaffected
                  cn.close()


                  Note: It did not work either. Also, it uses "add" instead of "set", and it ended up putting quotes around my session variables. I changed all of that as a test and still it failed. And the line with 'flag = cn.execute(sql,args)' also kicked out a similar error message during debug: Argument 2 must be an object of type SQL::Arguments or SQL::TableInfo

                  Comment


                    #10
                    Re: xbasic - insert into sql table

                    That genie output is garbage... that's really bad. You should report that.

                    You're fixing old errors, but introducing new errors. You sqlinsert statement has an extra ")" near ip_address.

                    I also wonder if your insert data is creating a problem. If fixing the extra ")" doesn't work, then post the values that are being in the Insert for the arguments. Maybe there's something odd in the data.

                    I just ran that corrected code and had no issues using sample data. All my table fields are varchar - so that won't match yours, but if you want to dump your table definition
                    and post it I'll test with that.

                    Comment


                      #11
                      Re: xbasic - insert into sql table

                      I corrected the extra ")". Same issue. Here is some info on my data, let me know if you need anything else. And thanks again for looking at this.

                      table.png

                      Here is some example data:
                      record_id: xxxxx
                      userid: [email protected]
                      account_number: 800167
                      Date: 2018-03-05
                      Page_title: Wireless
                      Event_type: product search
                      Sales_rep: Joe Smith
                      Vendor_specified: Samsung
                      Part_specified: None
                      Int_Ext: Internal
                      Client_type: desktop
                      IP_address: x.x.x.x

                      Comment


                        #12
                        Re: xbasic - insert into sql table

                        Ok... thanks... here's the problem. Using this code where you are using it... you already have an variable named "Args"... it's one of the parameters...

                        Code:
                        function BeforeSearch as v (SearchDataSubmitted as P, Args as p, PageVariables as p)
                        Change your dim statement to myArgs... and all the args.set statements to myArgs.set... and change the cn.execute statement... and all will be ok.

                        dim myArgs as sql::arguments
                        myArgs.set("newuserid", session.UserID)
                        flag = cn.execute(sqlinsert, myArgs)

                        Comment


                          #13
                          Re: xbasic - insert into sql table

                          You nailed it. That was my issue. Thank you so much!

                          Comment


                            #14
                            Re: xbasic - insert into sql table

                            Glad you got your problem resolved. Didn't see your message till now, I've used SQL from Xbasic a great deal and have ended up with some function for troubleshooting this. I've posted them to the Code Archive maybe they would be of help to someone else that comes across this posting.
                            https://www.alphasoftware.com/alphaf...ead.php?122003

                            Comment


                              #15
                              Re: xbasic - insert into sql table

                              Thanks. But the thread you reference has a link that doesn't do anything when I click on it.

                              Comment

                              Working...
                              X