Request info and save it to a file ...

2012-01-20 08:16:34 0 comments

In this example we will use a form to request information to our visitors and we will saved that information to a file. As we may get information from different visitors, in this example we will create a new file each time we get info from a new visitor. The script will create all necessary folders and files automatically. This script has been generated specifically for you (in your next visit the code will be prepared to save the information from your visitors in a different place within your server) All the information obtained from our form will be saved in a subdirectory within cgi-bin folder (p.e .: "c: \mydir\cgi- bin\messages143718\ "), and the information will be saved in a ".txt" file (p. e.: "c:\mydir\cgi -bin \messages143718\1 .txt "). That way we will prevent other users form getting information without permission (a ".txt" file located in the cgi-bin directory is not accessible by the client) . The subdirectory necessary to save the information will be create automatically. We will also need a file with a number as its unique content .This file will be used as a counter, and each time a visitor fills in our form the information provided will be save to a file (for example information from the first visitor will be save in file "1.txt", information from the second one in "2.txt "...). The counter file will be create automatically. This script will allow us to add any kind and number of input fields within the form, so that we may use the same response page for all forms in our site ("saveinfo. asp" may be used to save information from "form1. html", "form2. html" etc.) form.html Example code
saveinfo.asp <% Set fs = CreateObject("Scripting .FileSystemObject") Folderpath =server. mappath("\") & "/cgi-bin/ messages143718" Wcounter =Folderpath &"/counter.txt " Set fs = CreateObject("Scripting .FileSystemObject") if fs.FolderExists( Folderpath) then Set a = fs.OpenTextFile(Wcounter ) hits = Clng(a. ReadLine) hits = hits + 1 a.close else Set a = fs.CreateFolder( Folderpath) hits=1 end if Set a = fs.CreateTextFile(Wcounter ,True) a.WriteLine (hits) a.Close Set fs=nothing Set fs = CreateObject("Scripting .FileSystemObject") Set a = fs.CreateTextFile(Folderpath & "\" & hits & ".txt") For Each x In Request.Form a.WriteLine (x &": " & Request.Form( x)) Next a.Close Set a=nothing Set fs=nothing %> Thanks for providing the requested information
I will contact you very soon. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 Lines 2-18 . In case the folder where information will be saved does not exits, it will be create. The counter file will be also create. If they already exits, the counter will be open, the content read to a variable named "hits", and increased by one. Lines 20-23 . the value for variable h"hits" will be save in "counter.txt" file in our folder. Lines 25-32 , information provided per input field will be saved to a file. The name of the file will be composed by the variable hits (a number) and ".txt" Lines 34-35 . Write here your response. The response may be a text, as in this example, You may redirect the visitor to a different page. The code will be this one: <% response.redirect(" http:// www.mysite. com") %> You may include as a response page the content in a page within your site I In order to access the information saved to files we may use the script bellow. That way we will be able to access the information from all visitors in an unique page. Access to information is password protected (Name and password to access the information are shown in line two. If the name and password are not correct the form will be send (Subroutine "Sendform ()"), and in case they are correct the info is send (Subroutine "Sendinfo ()"). getinfo.asp Try ! <% if request.form("name ")="Peter" and request.form ("password")=" yes " then Sendinfo () else Sendform () end if %> <% Sub Sendform() %>
Name: < br> Password: < br>
<% End Sub %> <% Sub Sendinfo() FolderToCheck = server.mappath ("\") & "/cgi-bin / messages143718" Dim fs, f, f1, fc, s Set fs = CreateObject("Scripting .FileSystemObject") Set f = fs.GetFolder(FolderToCheck ) Set fc = f.Files For Each f1 in fc Wfile=f1 .name Response.write("< hr>" & Wfile & "/" & "

") FiletoCheck=FolderToCheck & Wfile Set a= fs.OpenTextFile(FiletoCheck ) theinfo=a .ReadAll Response.write("< pre>" & Theinfo & "") Next Response.write("< hr>Script provided by asptutorial.info< / a>") End sub %>

ree Active Servers Counter (.asp)...

2012-01-20 08:16:34 0 comments

With this script we will be able to know and show in our pages the number of active visitors in a given moment. The script has two parts: a file name global.asa (check information on "global.asa" file in this tutorial), and a small code you must insert in your pages to show the number of active users. Just copy the code in the table to a text file and save it in the main directory of your site ("/global.asa") . global.asa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 The first time a visitor gets to our pages, global.asa will be executed, and consequently, application ("activevisitors") in line 4 will get a value equal to "0". Immediately (as a new session has started), in line 12, application("activevisitors") will be increased by one. Each time a new visitor gets to our pages application ("activevisitors") will be increased by one, and identically, each time a session is finished, this parameter will be reduce by one (line 18). In case we want to show the number of visitors in our page, we must use this kind of code : index.asp There are <% =application("activevisitors ") %> active visitors.

Mailing list subscription/unsubscri...

2012-01-20 08:16:34 0 comments

This script will add or remove emails to a list. It will not send emails. For this second porpouse you may check this script The script code bellow has been split in different parts, each one corresponding to a subroutine. After each section of the script an explanation is provided. Explanation of each part of the script is provided bellow. The form asking for emails (included in the last subroutine of the script) may be place in a different page (but it must point to the script). This script will createa file in the server the first time an email is submit (at this moment is set up to create the file at "/cgi-bin/ subscribers.txt") . index.asp <% DIM Responsetext if request.form(" email")="" AND request.querystring="" then Sendform () else if request.form(" email")<>"" and request.form ("action")=" Subscribe" then GetrandomnamberandSavetoSession() CheckEmailandSendEmail () SendResponse () end if if request.form(" email")<>"" and request.form ("action")=" Unsubscribe" then RemoveEmail() SendResponse () end if if request.querystring<>"" then CheckrandonnumberandSaveEmailtoFile () SendResponse () end if end if %> Explanation : The first time the page is visited the form will be send to the client. If it is not the first time (request.form ("email") or request.querystring has a value), depending on the situation, the corresponding subroutines will be run. Options are three: 1. A new request for additon to the list request.form(" email")<>"" and request.form ("action")=" Subscribe" 2. A request to unsubscribe from the list request.form(" email")<>"" and request.form ("action")=" Unsubscribe" 3. A confirmation to add the email to the list. request.querystring<>"" <% sub GetrandomnamberandSavetoSession() Randomize session ("randonnumber")= INT(Rnd ()*1000000) session ("email ")=request.form(" email") end sub %> Explanation : Random number is generate (lines 3-4 ) Random number is stored in a session variable (line 4) The email is stored in a session variable (line 5) This random number will be send to the subscriber. It will be included in the url the subscriber must visit a confirm the inclusion in the mailing list. <% Sub CheckEmailandSendEmail () Wemail=request. form("email ") test1= instr(Wemail, "@") ' value must be >1 test2= instr(Wemail, ".") ' value must be >4 test3= len(Wemail) ' value must be >6 test4= InStr (test1 ,Wemail,".",1) ' value must be >test1 +2 if test1< 2 OR test2< 5 OR test3< 7 OR test4 Explanation : It is check whether email provided is valid If email is not valid, Responsetext variable is provided a appropiate value (you may change it) If email is valid Sendmessage () subroutine will be run Responsetext above may be change to meet your preferences. This variable will be used in the response page which may be also customized in the corresponding subroutine. <% Sub Sendmessage () message= "Dear Sir/madam," & CHR(10 ) & CHR(10 ) message= message & "A request to join our mailing list has been get at mydomain.com. " & CHR(10 ) message= message & "Please visit the following link to make efective you subscription to our mailing list." & CHR(10 ) & CHR(10 ) message= message & Request.servervariables ("SERVER_NAME") & Request.servervariables ("URL") & "?" & session ("randonnumber") & CHR (10) & CHR(10 ) message= message & "Take care" & CHR(10 ) & CHR(10 ) message= message & "John Smith" & CHR(10 ) set smtp=Server. CreateObject("Bamboo. SMTP") smtp.Server=" mail.yourdomain .com " smtp.Rcpt= request.form("email ") smtp.From=" webmaster@yourdomain. com" smtp.FromName=" John Smith" smtp.Subject=" Mailing list inclusion request " smtp.Message = message on error resume next smtp.Send if err then response.Write(" Internal server error") response.end end if set smtp = Nothing Responsetext=" One more thing to do: you must visit the link you will get by email within next minutes in order to confirm your inclusion in our mailing list.< p> This operation must be done suring this session, otherway your information will be lost " End Sub %> Explanation : An email will be send to the user for verification. The message is defined in the first part of the subroutine Withing the message an url the user must visit is provided. This url is formed this way: Request.servervariables(" SERVER_NAME") & Request.servervariables(" URL") will deffine the url as for example www.mydomain/ mydir/myfile.asp. This code will allow as to change the name or location of the script in our server withou changing the code of the script "?" & session ("randonnumber") will add the random number generated in advance to the url, so that it may be recornize by using Request.querystring The resulting url will be like this one: www.mydomain/ mydir/myfile.asp? 123456 You must change in the script some parameters (mail server, email address, your name, subject of the message) and you may also change the complete body of the message in the first part of the subroutine. Responsetext above may be change to meet your preferences. This variable will be used in the response page which may be also customized in the corresponding subroutine. <% sub CheckrandonnumberandSaveEmailtoFile() if Clng(request.querystring )=session ("randonnumber") then SaveEmailtoFile() else Responsetext=" We have no data related to your previous visit to this site

Probably your session has espired, so we are unable to add your email to our mailing list< p>Please try to join our mailing list again, and visit to the corresponding link as soon as possible, before the session is expired. " end if end sub %> Explanation : In case the subscriber confirms he wants to subscribe the mailing list he will click in the url send by email to him. In this url is included the random number we generated before sending the email to the subscriber, and this random number will be the value we may recover with the code "Request.querystring". As this value is a string, it is transformed to a number with instruction "Clng()" and it is compared with the random number stored at "session ("randonnumber")" . If they are the same number the email of the subscriber will be save to our file. In case they are not the same number, the most probable reason may be the subscriber has responded by clicking in the url send to him by email a bit late, so his session has expired and the value for "session ("randonnumber")" is null. In this case "Responsetext" is set up. Responsetext above may be change to meet your preferences. This variable will be used in the response page which may be also customized in the corresponding subroutine. <% Sub SaveEmailtoFile() email= session ("email") email= lcase(email ) email="<" & email & ">" Wfile=server .mappath("\") &" /cgi-bin /subscribers.txt " Set fs = CreateObject("Scripting .FileSystemObject") on error resume next Set a = fs.OpenTextFile(Wfile) allemails = a.ReadAll a.close if instr(allemails ,email)>0 then Responsetext=" You are already a subscriber to this mailing list " else allemails= allemails & email Set a = fs.CreateTextFile(Wfile,True ) a.Write( allemails) a.Close Responsetext=" Your email has been added to our list successfully " end if end sub %> Explanation : The email which was stored at session("email ") is save to a variable named email, transformed to lower case and added to it "<" and ">" in the first and last positions. Adding this characters in those positions is very usefull, as it will allow us to better control the list (see subroutine bellow). Then we will open the file where emails are stored and it will be checked whether the email is already in the list. If so, the apropiate Responsetext is defined. If not, the email (including the additional characters) will be added to the list. In case "/cgi-bin /subscribers.txt " is not present in the server, it will be created when adding the first email to the liost(it s not necessary to crate it in advance). T location the serverof the fila and its named can be changed without problems. The file where the emails are stored will look like this one: After adding the email Responsetext is defined. <% Sub RemoveEmail() email= lcase(request. form("email ")) email="<" & email & ">" Wfile=server .mappath("\") &" /cgi-bin /subscribers.txt " Set fs = CreateObject("Scripting .FileSystemObject") on error resume next Set a = fs.OpenTextFile(Wfile) allemails = a.ReadAll a.close if error then Responsetext=" The mailing list is not available at the moment " else if instr(allemails ,email)> 0 then allemails= replace(allemails,email ,"") Set a = fs.CreateTextFile(Wfile,True ) a.Write( allemails) a.Close Responsetext=" Your email has been remove from our mailinglist" else Responsetext=" Your email is not included in this mailing list " end if end if end sub %> Explanation : The email (which was stored in a session obhect) will suffer the same transformation as in the previous subroutine.Then the file contain the list of emails is open and read (in case an error occurs when trying to open the file a Responsetext is defined), I the email is included in the list it will be deleted. If not the corresponding response will be set up. When trying to delete the email (see subroutine bellow), this additional character added in first and last position ("<> and "<") will prevent the script to delete aditional emails: p.e . when deleting from the list "a@domain .com" we will avoit deleting "ana@domain .com" (because we will delete ""). After deleteing the email the corresponding answer will be set up. <% Sub SendResponse() %> Request to join mailing list</ title>< /head> <body bgcolor="# FFFFFF" text="# 000000"> <% =Responsetext %> </body ></html > <% End Sub %> Explanation : This subroutine is used to display our answer ae corresponding action and it may be totally customized. Just keep "<% =Responsetext %>" within the code. "Responsetext" is the piece of tee defined somewhereelse in the script depending on what action has took place. <% Sub SendForm() %> <html ><head><title >Request to join mailing list</ title>< /head> <body bgcolor="# FFFFFF" text="# 000000"> <center > Add your email to our mailing list <FORM METHOD=POST ACTION="<% =Request. servervariables("URL") %>"> <BR> Email address:   <INPUT TYPE="text" NAME=" email" Size="60 " MAXLENGTH="128"> <BR>< BR> <input type=radio name="action" value=" Subscribe" checked> Subscribe    ;   <input type=radio name="action" value=" Unsubscribe"> Unsubscribe< BR><BR> <INPUT TYPE="SUBMIT" VALUE="Submit/ Enviar"><INPUT TYPE="RESET " VALUE="Clear/ Borrar"> </FORM > </center > </body ></html > <% End Sub %> Explanation : This subroutine is used to introduce the email o the user the first time he to the page. The form may be place in different page as far as it points to the script. </div></div></div></div><div class='post'> <div class='post-bgtop'> <div class='post-bgbtm'> <h2 class='title'><a href='artikel-lassen.php?aid=6'>Add a search utility to your site...</a></h2> <p class='meta'><span class='date'><img src='../images/ico-time.png' /> 2012-01-20</span> 08:16:34 <img src='../images/ico-com.png' /> 0 comments <img src='../images/ico-user.png' /> <a href='benutzer.php?id=1'></a> <img src='../images/ico-cat.png' /> </a></p> <div class='entry'> This search utility will allow you to search for terms or phrases within your site, and the resulting page will show your visitors the title of the page and a link to it. You only need to include the form bellow in your page: searchfiles .html <form method=" POST" action="/cgi -bin/ searchfiles .asp"> <table border= 0 cellpadding=5 bgcolor=AAAAAA ><tr> <td align=center > Search term or phrase   <input type=text name=term size= 15>   <input type=submit value=" search"></td > </tr>< /table> </form > And you will need to create a file with the content in the table bellow named searchfiles .asp in the corresponding directory. Active Server Pages must be available in the server. Instructions are in the bottom. searchfiles .asp <% SearchTerm = request.form(" term") Novalid=" a b c d e f g h i j k l m n o p q r s t u v w x y z yes no and more" NovalidResponse ="Go back and try again. Your search term is very common" if instr(SearchTerm, Novalid)=0 then Response. Write ("<CENTER>< H2> Search results </ H2 ></CENTER>") FolderName= "FolderName " ShowList() else Response.Write NovalidResponse End if SearchResponse="" %> <% Sub ShowList() FolderToCheck = server.mappath ("\") &"/" & FolderName & "/" Dim fs, f, f1, fc, s Set fs = CreateObject("Scripting .FileSystemObject") Set f = fs.GetFolder( FolderToCheck) Set fc = f.Files For Each f1 in fc Wfile = f1. name if right(Wfile, 5)=".html " OR right(Wfile, 4)=". htm" then Wfile2 = FolderToCheck & Wfile Set fs = CreateObject ("Scripting. FileSystemObject") Set a = fs.OpenTextFile(Wfile 2) ct = a.ReadAll a.close ct2= lcase(ct) SearchTerm2 = lcase(SearchTerm) if instr( ct2,SearchTerm2 )>0 then if instr(ct ,"")>0 then longitud=instr (ct,"") longitud=longitud -1 ct=left( ct,longitud) longitud2=len( ct) longitud=instr (ct,"") longitud=longitud2 -longitud -6 ct=right(ct ,longitud) else if instr(ct,"< /TITLE>")>0 then longitud=instr (ct,"< /TITLE>") longitud=longitud -1 ct=left( ct,longitud) longitud2= len(ct) longitud=instr (ct,"< TITLE>") longitud=longitud2 -longitud -6 ct=right( ct,longitud) end if end if SearchResponse= SearchResponse +"< TR><TD>"+ ct + "</TD>< TD ALIGN=CENTER VALIGN=MIDDLE >" + " <A HREF=" + "/" + FolderName + "/" + Wfile +"> More </A>< /TD></ TR>" longitud=0 ct="" end if end if Next Response.Write ("<HTML>< HEAD><TITLE >Search results< /TITLE></ HEAD><BODY BGCOLOR=FFFFFF>< CENTER>") Response.Write ("<TABLE BORDER= 0 WIDTH= 550><TR>< TD BGCOLOR=C 0C0 C0 ><FONT SIZE=5 ><B> Search Results</B ></FONT></ TD></TR>< / TABLE>") Response.Write ("<TABLE BORDER= 0 WIDTH=550 >") if SearchResponse<>"" then Response.Write SearchResponse else Response.Write ("<TR><TD >The specified term or phrase was not found</TD ></TR>") end if Response.Write ("</TABLE >") Response.Write ("</CENTER ></BODY>< /HTML>") End Sub %> You may include the terms you do not want to be searched in the variable "Novalid". In case a term included in "Novalid" is request, write your response in the variable "NovalidResponse ". "Search results" is the text which will be shown in the top of the search results page. "FolderName " is the directory you want to search. Only ".htm " and ".html " files in this directory will be searched. Subdirectories are not search. In case you want to search your top directory, set FolderName="". This script is only useful in top directories only. I do not recommend to check more than 50 files (Try to be friendly with your server!) This script will show as a response a list of the titles of pages with the requested term of phrase. </div></div></div></div><div class='post'> <div class='post-bgtop'> <div class='post-bgbtm'> <h2 class='title'><a href='artikel-lassen.php?aid=5'>Access to remote URLsAccess to remo...</a></h2> <p class='meta'><span class='date'><img src='../images/ico-time.png' /> 2012-01-20</span> 08:16:34 <img src='../images/ico-com.png' /> 0 comments <img src='../images/ico-user.png' /> <a href='benutzer.php?id=1'></a> <img src='../images/ico-cat.png' /> </a></p> <div class='entry'> In this tutorial we will used Microsoft's XMLHTTP Object to request a page to a remote address from our server. This Object is included in Microsoft's XML DOM component, which is probably installed in your server. The traditional usage of Microsoft's XMLHTTP Object is to access remote XML files. In this basic tutorial we will used it to obtain the text code from a remote server. It will be the same information our browser will get when visiting that page. In the example bellow we have set up a variable named GotothisURL which contains the url of the page we will asked our server to visit. The response to this visit will be saved to variable ResponsePage. GetremoteURL.asp <% ' Intruduce the url you want to visit GotothisURL = "http://www .asptutorial.info " ' Create the xml object Set GetConnection = CreateObject ("Microsoft.XMLHTTP") ' Conect to specified URL GetConnection.Open "get", GotothisURL, False GetConnection.Send ' ResponsePage is the response we will get when visiting GotothisURL ResponsePage = GetConnection.responseText ' We will write Response.write (ResponsePage) Set GetConnection = Nothing %> In the example avobe we may use a URL like http:// www.asptutorial. info? name=Joe&lastname =Zarzandi . The example above will work with get method. You may try http:// www.google .asp?q= asp to search for asp in google search engine (unfortunatelly is not legal to do so without visiting their site unless we used the method shown in the script bellow). In the example above we have request for all content of the response page, but it is possible to request only headers (check code in bold in the script), but we may request only for specific headers. You will need to change line 12 in the script: ResponsePage = GetConnection.getallResponseHeaders The response page will be something similar to this: Server: Microsoft-IIS/5. 0 Date: Thu, 31 Apr 2002 14:25: 20 GMT MicrosoftOfficeWebServer: 5.0 _Pub Connection: keep-alive Connection: Keep-Alive Content-Length: 11063 Content-Type: text/ html Cache-control: private We may also request for specific parts of the information included in the headers (check a regular : To request for Server: ResponsePage = GetConnection.getResponseHeader ("Server") To request for Date: ResponsePage = GetConnection.getResponseHeader ("Date") To request for Content Length: ResponsePage = GetConnection.getResponseHeader ("Content-Length") ... In the example bellow we have add some code to avoid error messages when url is not available, so that we will get a alternative text (line 17) GetremoteURL.asp <% ' Intruduce the url you want to visit GotothisURL = "http://www .asptutorial.info " ' Create the xml object Set GetConnection = CreateObject ("Microsoft.XMLHTTP") ' Conect to specified URL GetConnection.Open "get", GotothisURL, False on error resume next GetConnection.Send ' ResponsePage is the response we will get when visiting GotothisURL ResponsePage = GetConnection.responseText ' We will write if ResponsePage="" then Response.write(" The page is not available") else Response.write(ResponsePage ) end if Set GetConnection = Nothing %> </div></div></div></div><div class='post'> <div class='post-bgtop'> <div class='post-bgbtm'> <h2 class='title'><a href='artikel-lassen.php?aid=4'>Access MySQL Database: open connect...</a></h2> <p class='meta'><span class='date'><img src='../images/ico-time.png' /> 2012-01-17</span> 22:39:15 <img src='../images/ico-com.png' /> 0 comments <img src='../images/ico-user.png' /> <a href='benutzer.php?id=1'></a> <img src='../images/ico-cat.png' /> </a></p> <div class='entry'> import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class SimpleProgramToAccessOracleDatabase { public static Connection getConnection() throws Exception { // load the Oracle JDBC Driver Class.forName("oracle.jdbc.driver.OracleDriver"); // define database connection parameters return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:database", "userName", "password"); } public static void main(String[] args) throws SQLException { Connection conn = null; // connection object Statement stmt = null; // statement object ResultSet rs = null; // result set object try { conn = getConnection(); // without Connection, can not do much // create a statement: This object will be used for executing // a static SQL statement and returning the results it produces. stmt = conn.createStatement(); // start a transaction conn.setAutoCommit(false); // create a table called cats_tricks stmt.executeUpdate("CREATE TABLE cats_tricks " + "(name VARCHAR2(30), trick VARCHAR2(30))"); // insert two new records to the cats_tricks table stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'r')"); stmt.executeUpdate("INSERT INTO cats_tricks VALUES('mono', 'j')"); // commit the transaction conn.commit(); // set auto commit to true (from now on every single // statement will be treated as a single transaction conn.setAutoCommit(true); // get all of the the records from the cats_tricks table rs = stmt.executeQuery("SELECT name, trick FROM cats_tricks"); // iterate the result set and get one row at a time while (rs.next()) { String name = rs.getString(1); // 1st column in query String trick = rs.getString(2); // 2nd column in query System.out.println("name=" + name); System.out.println("trick=" + trick); System.out.println("=========="); } } catch (ClassNotFoundException ce) { // if the driver class not found, then we will be here System.out.println(ce.getMessage()); } catch (SQLException e) { // something went wrong, we are handling the exception here if (conn != null) { conn.rollback(); conn.setAutoCommit(true); } System.out.println("--- SQLException caught ---"); // iterate and get all of the errors as much as possible. while (e != null) { System.out.println("Message : " + e.getMessage()); System.out.println("SQLState : " + e.getSQLState()); System.out.println("ErrorCode : " + e.getErrorCode()); System.out.println("---"); e = e.getNextException(); } } finally { // close db resources try { rs.close(); stmt.close(); conn.close(); } catch (Exception e) { } } } } </div></div></div></div><div class='post'> <div class='post-bgtop'> <div class='post-bgbtm'> <h2 class='title'><a href='artikel-lassen.php?aid=3'>Connecting to the MySQL Server...</a></h2> <p class='meta'><span class='date'><img src='../images/ico-time.png' /> 2012-01-17</span> 22:39:15 <img src='../images/ico-com.png' /> 0 comments <img src='../images/ico-user.png' /> <a href='benutzer.php?id=1'></a> <img src='../images/ico-cat.png' /> </a></p> <div class='entry'> To connect to the MySQL server, register the JDBC driver you plan to use, then invoke its getConnection() method. The following short program, Connect.java, shows how to connect to and disconnect from a server running on the local host. It accesses a database named test, using a MySQL account with a user name and password of testuser and testpass: import java.sql.*; public class Connect { public static void main (String[] args) { Connection conn = null; try { String userName = "testuser"; String password = "testpass"; String url = "jdbc:mysql://localhost/test"; Class.forName ("com.mysql.jdbc.Driver").newInstance (); conn = DriverManager.getConnection (url, userName, password); System.out.println ("Database connection established"); } catch (Exception e) { System.err.println ("Cannot connect to database server"); } finally { if (conn != null) { try { conn.close (); System.out.println ("Database connection terminated"); } catch (Exception e) { /* ignore close errors */ } } } } } Compile Connect.java to produce a class file Connect.class that contains executable Java code: % javac Connect.java Then invoke the class file as follows and it should connect to and disconnect from your MySQL server: % java Connect Database connection established Database connection terminated If you have trouble compiling Connect.java, double check that you have a Java Software Development Kit installed and make sure that the MySQL Connector/J driver is listed in your CLASSPATH environment variable. The arguments to getConnection() are the connection URL and the user name and password of a MySQL account. As illustrated by Connect.java, JDBC URLs for MySQL consist of jdbc:mysql:// followed by the name of the MySQL server host and the database name. An alternate syntax for specifying the user and password is to add them as parameters to the end of the connection URL: jdbc:mysql://localhost/test?user=testuser&password=testpass When you specify a URL using this second format, getConnection() requires only one argument. For example, the code for connecting to the MySQL server in Connect.java could have been written like this: String userName = "testuser"; String password = "testpass"; String url = "jdbc:mysql://localhost/test?user=" + userName + "&password=" + password; Class.forName ("com.mysql.jdbc.Driver").newInstance (); conn = DriverManager.getConnection (url); getConnect() returns a Connection object that may be used to interact with MySQL by issuing queries and retrieving their results. (The next section describes how to do this.) When you're done with the connection, invoke its close() method to disconnect from the MySQL server. To increase the portability of your applications, you can store the connection parameters (host, database, user name, and password) in a Java properties file and read the properties at runtime. Then they need not be listed in the program itself. This allows you to change the server to which the program connects by editing the properties file, rather than by having to recompile the program. </div></div></div></div><div class='post'> <div class='post-bgtop'> <div class='post-bgbtm'> <h2 class='title'><a href='artikel-lassen.php?aid=2'>Sending form results to multiple re...</a></h2> <p class='meta'><span class='date'><img src='../images/ico-time.png' /> 2012-01-17</span> 22:20:37 <img src='../images/ico-com.png' /> 0 comments <img src='../images/ico-user.png' /> <a href='benutzer.php?id=1'></a> <img src='../images/ico-cat.png' /> </a></p> <div class='entry'> Need to send a copy of form results to your business partner? To your friend? To someone helping you with a project? So, how do you send the e-mail with form results to multiple recipients? The answer is: easy! All you need to do is separate multiple e-mail addresses in the PHP mail() function (remember the Form to Mail tutorial?) with a comma ( , ). As shown before to send an e-mail to john@doe.com you would use this PHP code: mail("john@doe.com", "Test e-mail", "Hi, this is a test message!"); Now if you wanted to send a copy of the same e-mail also to jane@mail.com and frank@domain.com you would just use all three (separated with a comma) as the first parameter in the mail() function: "john@doe.com , jane@mail.com , frank@domain.com" Now the code would look like this: mail("john@doe.com , marry@mail.com , frank@domain.com", "Test e-mail", "Hi, this is a test message!"); That's it! </div></div></div></div><div class='post'> <div class='post-bgtop'> <div class='post-bgbtm'> <h2 class='title'><a href='artikel-lassen.php?aid=1'>Dynamic Multi-level CSS Menu with P...</a></h2> <p class='meta'><span class='date'><img src='../images/ico-time.png' /> 2012-01-17</span> 22:20:37 <img src='../images/ico-com.png' /> 0 comments <img src='../images/ico-user.png' /> <a href='benutzer.php?id=1'></a> <img src='../images/ico-cat.png' /> </a></p> <div class='entry'> Since writing this post i have enhanced the script and now use V2 which you can check out here: Single Query Dynamic Multi-level Menu I was recently working on a project for a client and couldn’t find a menu solution to fit my needs. I was looking to use a menu style similar to those found on Cssplay.co.uk, but i wanted to build the menu on the fly from a MySQL database. After many search attempts and several posts on php/mysql boards i realized i was going to have to work this out myself. I needed infinite levels and most tutorials only had options for 1 or 2 sub levels or weren’t completely dynamic and would require a table rebuild every time you add a new page. Creating The Menu My solution was a mix of several menus i found online. I decided to use a flat table and a simple recursive php function. The first step is working out the table structure. Here is a look at the table i used. The MySQL Table id label link parent sort The id is you Primary Key field here, followed by label and link being the name and action of the option. The parent will be the id of the parent menu item and finally the sort field is used if you want any control over the order of your menu items. Here is the sql view source print? 1 CREATE TABLE `menu` ( 2 `id` int(11) NOT NULL auto_increment, 3 `label` varchar(50) NOT NULL default '', 4 `link` varchar(100) NOT NULL default '#', 5 `parent` int(11) NOT NULL default '0', 6 `sort` int(11) default NULL, 7 PRIMARY KEY (`id`), 8 ) ENGINE=MyISAM AUTO_INCREMENT=248 DEFAULT CHARSET=latin1; Now that we have a table to take information from we need some data id label link parent sort 1 Home #home 0 0 2 Code #code 0 0 3 Contact #contact 0 0 4 PHP #php 2 0 5 CSS #css 2 0 6 Scripts #scripts 4 0 7 Help #help 4 0 8 Archive #archive 6 0 9 Snippet #snippet 8 0 The links can be in any form as you will build them later. eg. ?p=84, http://url, #anchor. The PHP Function Now lets take a look at the php. This is a simplified version view source print? 01 function display_children($parent, $level) { 02 $result = mysql_query("SELECT a.id, a.label, a.link, Deriv1.Count FROM `menu` a LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `menu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent=" . $parent); 03 echo "<ul>"; 04 while ($row = mysql_fetch_assoc($result)) { 05 if ($row['Count'] > 0) { 06 echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a>"; 07 display_children($row['id'], $level + 1); 08 echo "</li>"; 09 } elseif ($row['Count']==0) { 10 echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a></li>"; 11 } else; 12 } 13 echo "</ul>"; 14 } So lets start with the query. view source print? 1 $result = mysql_query("SELECT a.id, a.label, a.link, Deriv1.Count FROM `menu` a LEFT OUTER JOIN (SELECT parent, COUNT(*) AS Count FROM `menu` GROUP BY parent) Deriv1 ON a.id = Deriv1.parent WHERE a.parent=" . $parent); It looks complicated but all it is doing is getting the information for each menu item for a parent and a count of how many children it has. The results would look like this: id label link count 1 Home #home 0 2 Code #code 2 3 Contact #contact 0 These results are the contents of the top layer or main menu, just after the sql query comes a simple echo to create our opening <ul> tags. Followed by the brains of the function inside this while statement: view source print? 1 while ($row = mysql_fetch_assoc($result)) { 2 if ($row['Count'] > 0) { 3 echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a>"; 4 display_children($row['id'], $level + 1); 5 echo "</li>"; 6 } elseif ($row['Count']==0) { 7 echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a></li>"; 8 } else; 9 } This statement simply outputs the appropriate <li> tags and links for each item on the menu and then checks to see if that item has any children. If the count is more than zero then it calls the entire function over to build the child menu. Then a simple closing </ul> tag to finish it off. To call the menu simply run the function with the level you want to display for example: view source print? 1 display_children(0, 1); Would return: * Home * Code o PHP + Scripts # Archive * Snippet # Help o CSS * Contact view source print? 1 display_children(4, 1); Would return only the children of PHP or (id #4) * Scripts o Archive + Snippet o Help This second use can come in handy if you want to build a sub menu any where in your site. The menu can be further customized as i mentioned above with css as can be seen in use at B&B Metals. The code for the menu on that site is slightly more complex due to different css classes being used for lower levels in the menu. You can easily sort the menu by adding a sort statement to the sql statement and giving your menu items a sort order. Styling The Menu Now after all that it doesnt look like much yet. But im gonna show you how to make this into a horizontal dropdown menu although you could use this to make any sort of menu type. Modifying the PHP The first thing we have to do now is add add a class to the output of the php script. Start by replacing: view source print? 1 echo "<li><a href='" . $row['link'] . "'>" . $row['label'] . "</a></li>"; With: view source print? 1 echo "<li class='list'><a class='list_link' href='" . $row['link'] . "'>" . $row['label'] . "</a></li>"; If you want a different style for your lower levels then you will want to use the code below instead of the one above. view source print? 1 echo "<li class='level".$level."'><a class='level".$level."' href='" . $row['link'] . "'>" . $row['label'] . "</a></li>"; Now that our links have been assigned a class we can style them any way we choose. If you want to style layer 2 differently then simply use the .layer2 class to change that. Now that you have your menu in the right format ie. Unordered and Ordered lists you can use just about any css menu around. I recommend checking out the ones over at Cssplay.co.uk, of course if you like there stuff make sure you donate. Another way that you can code your css menus is to give your menu a class, lets say .menu, apply that class to your top container and assign the levels of the menu as view source print? 1 .menu ul{color:#FFF;} /* Main container, includes the background of the static portion of the menu */ 2 .menu ul li{color:#FFF;} /* This is the style for the main menu items */ 3 .menu ul ul{color:#FFF;} /* This is the container for the first submenu */ 4 .menu ul ul li{color:#FFF;} /* This is the style for the submenus */ And so on and so on. You can style the links themselves as well by using the .menu a{}. This will alter all links in the menu. To define a different style for a lower level in the menu you would simply change it to .menu ul ul a{} for the second level. I wont go over all the styling as we would be here forever so if you have any questions feel free to ask and ill be glad to help. Since writing this post i have enhanced the script and now use V2 which you can check out here: Single Query Dynamic Multi-level Menu </div></div></div></div> </div> <!-- end #content --> <div id="sidebar"> <ul> <li> <h2>Pages</h2> <ul> <li><a href="index.php">Home</a></li> </ul> </li> <li> <h2>Categories </h2> <ul> <li><a href='seite-anzeigen.php?sid=7'>Asp<font color='red'>(5)</font></a></li><li><a href='seite-anzeigen.php?sid=12'>Asp.NET<font color='red'>(0)</font></a></li><li><a href='seite-anzeigen.php?sid=6'>Assembly<font color='red'>(0)</font></a></li><li><a href='seite-anzeigen.php?sid=5'>C#<font color='red'>(0)</font></a></li><li><a href='seite-anzeigen.php?sid=3'>C/C++<font color='red'>(0)</font></a></li><li><a href='seite-anzeigen.php?sid=13'>Delphi<font color='red'>(0)</font></a></li><li><a href='seite-anzeigen.php?sid=11'>Electronics<font color='red'>(0)</font></a></li><li><a href='seite-anzeigen.php?sid=2'>Java<font color='red'>(2)</font></a></li><li><a href='seite-anzeigen.php?sid=8'>Linux<font color='red'>(0)</font></a></li><li><a href='seite-anzeigen.php?sid=10'>Mechatronics<font color='red'>(0)</font></a></li><li><a href='seite-anzeigen.php?sid=1'>PHP<font color='red'>(2)</font></a></li><li><a href='seite-anzeigen.php?sid=4'>Phyton<font color='red'>(0)</font></a></li><li><a href='seite-anzeigen.php?sid=9'>Windows<font color='red'>(0)</font></a></li> </ul> <h2>Search </h2> <form name="input" action="suchen.php" method="get">         <input type="text" name="q" /> <input type="submit" value="Go" /> <p><p> </form> </li> <li> </li> </ul> </div> <!-- end #sidebar --> </div> </div> </div> <div id="footer"> <br /> <b>Warning</b>: mysql_free_result(): supplied argument is not a valid MySQL result resource in <b>C:\Inetpub\vhosts\tugrulaslan.com\httpdocs\index.php</b> on line <b>99</b><br /> </div> <!-- end #footer --> </body> </html>