Display Part of Database Field

There may be times when you only need to display part of the data from a complex database field on your web page.  For example, let’s say we have Definition field that contains a term and it’s definition and they are separated by a colon.  So how do you separate this and only display part of the field on the web?

The first thing you need to do is create a database called MyData.  Then create a table called tblDefinitions with these fields:
ID – autonumber
Definition – text field
DateEntered – date/time field *** Also add “=Date()” as the default value for the field.  This will add the date automatically, every time a new record is entered. ***

Then, add a new record with this term and definition:  “Webmaster : A person who designs, develops, markets, or maintains a website.”

Enter a few more records with other terms and definitions.

Next, create a page called /DisplayPartOfField.asp and copy the below code into your page:

<!--#INCLUDE VIRTUAL="/includes/connection.asp" -->

<%
DIM mySQL, objRS
mySQL = "SELECT * FROM tblLocations"
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open mySQL, objConn
%>

<table>
<% DO WHILE NOT objRS.EOF %>
<tr><td>
<%
DIM strLocation
strLocation = Left(objRS("Location"), InStr(1, objRS("Location"), ":") - 1)
Response.Write strLocation
%>
<tr><td>
<%
objRS.MoveNext
Loop

objRS.Close
Set objRS = Nothing
objConn.Close
Set objConn = Nothing
%>
</table>

This script will return all of the records in your database and will display only the data to the left of the “:” in your Definition field.  If you want to display only the data to the right of the “:” , substitute the below code for the above.

<%
DIM strLocation
strLocation = Mid(objRS("Location"), InStr(1, objRS("Location"), ":") + 1)
Response.Write strLocation
%>

That’s it, happy displaying!

< Back to ASP Scripts