232 75 7MB
English Pages 361 Year 2006
Foundation ASP for Dreamweaver 8 Omar Elbaga and Rob Turnbull
Foundation ASP for Dreamweaver 8 Copyright © 2006 by Omar Elbaga and Rob Turnbull All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN (pbk): 978-1-59059-568-8 ISBN (pbk): 1-59059-568-8 Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1 Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax 201-348-4505, e-mail [email protected], or visit www.springeronline.com. For information on translations, please contact Apress directly at 2560 Ninth Street, Suite 219, Berkeley, CA 94710. Phone 510-549-5930, fax 510-549-5939, e-mail [email protected], or visit www.apress.com. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. The source code for this book is freely available to readers at www.friendsofed.com in the Downloads section.
Credits Lead Editor Chris Mills Technical Reviewer Jason Nadon Editorial Board Steve Anglin, Dan Appleman, Ewan Buckingham, Gary Cornell, Tony Davis, Jason Gilmore, Jonathan Hassell, Chris Mills, Dominic Shakeshaft, Jim Sumser Project Manager Beth Christmas Copy Edit Manager Nicole LeClerc Copy Editors Damon Larson, Nicole LeClerc
Assistant Production Director Kari Brooks-Copony Production Editor Ellie Fountain Compositor Dina Quan Proofreader Lori Bring Indexer John Collin Artist April Milne Interior and Cover Designer Kurt Krames Manufacturing Director Tom Debolski
I would like to dedicate this book to my mom; dad; brothers and sister, Tamer, Hesham, Soliman, and Yasmine; my fiancée, Mona; my entire family; and all my faithful readers. —Omar Elbaga This book is dedicated to my family and friends who always support me. Special thanks go to baby Theo who always puts an even bigger than usual smile on my face. —Rob Turnbull
CONTENTS AT A GLANCE About the Authors
About the Technical Reviewer Acknowledgments Introduction
xiv
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xvi
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 1 Dreamweaver and Dynamic Sites Chapter 2 The Dreamweaver Environment
xvii
. . . . . . . . . . . . . . . . . . . .
1
. . . . . . . . . . . . . . . . . . . .
19
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
45
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
83
Chapter 3 A First Taste of ASP Chapter 4 Databases
xv
Chapter 5 Working with Forms
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 6 Building a Random Quote Generator
. . . . . . . . . . . . . . .
Chapter 7 Completing the Quotes Administration System
133 175
. . . . . .
195
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
223
Chapter 9 Creating a Blog
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
245
Chapter 10 Image Gallery
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
287
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
327
Chapter 8 Restricting Access
Index
v
CONTENTS About the Authors
About the Technical Reviewer Acknowledgments Introduction
xiv
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xv
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xvi
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 1 Dreamweaver and Dynamic Sites
xvii
. . . . . . . . . . . . . . . . . . . .
1
Data exchange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Dynamic takes over static . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Dreamweaver server models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 The ASP VBScript server model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 What Dreamweaver 8 offers you as an ASP developer . . . . . . . . . . . . . . . . . . . . 9 Checking out data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Connecting to databases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Where is ASP in Dreamweaver? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 ASP features supported by Dreamweaver . . . . . . . . . . . . . . . . . . . . . . . . 10 Insert bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 The Insert bar’s ASP tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 The Insert bar’s Application tab . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Application panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 The Databases tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 The Bindings tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Chapter 2 The Dreamweaver Environment Workspace layout . . . . . . . . . . The Multiple Document Interface . The CSS panel . . . . . . . . . . The Application panel group . The Databases panel . . . . The Bindings panel . . . . The Server Behaviors panel The Tag Inspector panel group The Attributes panel . . . The Behaviors panel . . . .
0e197eab08414336a67d4228a6088055
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
19
. . . . . . . . . . . . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
. . . . . . . . . .
19 20 21 22 22 23 24 25 26 26
vii
CONTENTS
The Files panel group . . . . . . . . . . . . The Files panel . . . . . . . . . . . . . . The Assets panel . . . . . . . . . . . . . The Snippets panel . . . . . . . . . . . The Properties panel . . . . . . . . . . . . . The Results panel group . . . . . . . . . . . The Search panel . . . . . . . . . . . . . The Validation panel . . . . . . . . . . . The Target Browser Check panel . . . . The Link Checker panel . . . . . . . . . The Site Reports panel . . . . . . . . . . The FTP Log panel . . . . . . . . . . . . The Server Debug panel . . . . . . . . . The Reference panel . . . . . . . . . . . Toolbars . . . . . . . . . . . . . . . . . . . . . . The Insert toolbar/panel group . . . . . . . The Document toolbar . . . . . . . . . The Standard toolbar . . . . . . . . . . The Style Rendering toolbar . . . . . . The Coding toolbar . . . . . . . . . . . New tools in Design view . . . . . . . . . . Zoom . . . . . . . . . . . . . . . . . . . Magnification . . . . . . . . . . . . . . . Hand . . . . . . . . . . . . . . . . . . . . Guides . . . . . . . . . . . . . . . . . . . Defining an ASP VBScript site in Dreamweaver Local Info screen . . . . . . . . . . . . . . . Remote Info screen . . . . . . . . . . . . . Testing Server screen . . . . . . . . . . . . . Creating the site . . . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . .
Chapter 3 A First Taste of ASP
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
27 27 28 28 29 30 30 30 31 31 31 31 32 32 32 32 33 35 35 36 37 37 37 37 37 39 39 40 41 42 43
45
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specify your language: VBScript . . . . . . . . . ASP delimiters . . . . . . . . . . . . . . . Insensitive case! . . . . . . . . . . . . . . . . . . Variables . . . . . . . . . . . . . . . . . . . . . . Declaring and printing variables . . . . . . Letting VBScript declare variables implicitly Syntax rules for variables . . . . . . . . . . Data types: string, integer, and Boolean . . Variable concatenation . . . . . . . . . . . Watching out for “adding” numbers . . . . Variable naming conventions . . . . . . . . Prefixes . . . . . . . . . . . . . . . . . . Using understandable variable names . Commenting code . . . . . . . . . . . . . . . .
viii
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . .
46 46 47 48 49 52 52 52 54 55 56 56 56 57
CONTENTS
VBScript’s house of built-in functions . . . . . . Conversion functions . . . . . . . . . . . . . . String functions . . . . . . . . . . . . . . . . . Operators . . . . . . . . . . . . . . . . . . . . . . Assignment operators . . . . . . . . . . . . . Logical operators . . . . . . . . . . . . . . . . AND, OR . . . . . . . . . . . . . . . . . . NOT . . . . . . . . . . . . . . . . . . . . . Comparison operators . . . . . . . . . . . . . Mathematical operators . . . . . . . . . . . . Operator precedence . . . . . . . . . . . . . Conditional logic . . . . . . . . . . . . . . . . . . The If statement . . . . . . . . . . . . . . . . The If . . . Then . . . Else statement . . . . . . The If . . . Then . . . ElseIf statement . . . . . Looping logic . . . . . . . . . . . . . . . . . . . . The Do . . . Loop statement . . . . . . . . . . The While . . . Wend statement . . . . . . . . Cookies (ASP cookies, not chocolate chip!) . . . Response.Cookies and Request.Cookies . . . Cookie expiration . . . . . . . . . . . . . . . . Updating cookies . . . . . . . . . . . . . . . . Deleting cookies . . . . . . . . . . . . . . . . A word of warning about the use of cookies Session variables . . . . . . . . . . . . . . . . . . Setting the session timeout interval . . . . . Creating and retrieving session variables . . . Updating session variables . . . . . . . . . . . Deleting session variables . . . . . . . . . . . Note on sessions . . . . . . . . . . . . . . . . Environment variables . . . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . .
Chapter 4 Databases
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
58 58 59 61 62 62 62 63 64 65 66 68 68 69 69 71 71 72 72 73 75 75 76 76 76 77 77 78 78 79 79 81
83
Creating a database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Inside Microsoft Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 Inside Microsoft SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Preparing a SQL Server database for Internet use . . . . . . . . . . . . . . . . . . . . . . 88 Creating the IUSR account in SQL Server . . . . . . . . . . . . . . . . . . . . . . . . 89 Database design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Object naming conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Creating tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 Creating tables in Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Creating tables in SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 Relational databases and referential integrity . . . . . . . . . . . . . . . . . . . . . . . . 97 Creating a relationship in Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 Creating a relationship in SQL Server . . . . . . . . . . . . . . . . . . . . . . . . . . 100 SQL Server views and Access queries . . . . . . . . . . . . . . . . . . . . . . . . . . 102
ix
CONTENTS
Fundamental SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Selecting all records from a table . . . . . . . . . . . . . . . . . . . . . Selecting all records that meet one criterion . . . . . . . . . . . . . . . Selecting all records that meet several criteria (using AND) . . . . . . Selecting records that meet one or more of several criteria (using OR) Useful SQL keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . COUNT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SUM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . TOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . BETWEEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ORDER BY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . GROUP BY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DISTINCT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Going on a DATE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Making the connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Setting up a DSN to an Access database . . . . . . . . . . . . . . . . . Setting up a DSN to a SQL Server database . . . . . . . . . . . . . . . Connecting from Dreamweaver . . . . . . . . . . . . . . . . . . . . . . The Simple Recordset builder . . . . . . . . . . . . . . . . . . . . . . . . . The Advanced Recordset builder . . . . . . . . . . . . . . . . . . . . . . . Using commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Inserting a record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Updating a record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Updating multiple records (a simple example) . . . . . . . . . . . . . . Deleting a record . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Deleting multiple records (simple example) . . . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 5 Working with Forms
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
103 104 104 105 105 106 107 107 108 108 109 110 111 112 113 113 114 114 115 116 119 122 124 125 127 128 129 131
133
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
Form attributes: Action and Method . . . . . . . . . . . . . get method . . . . . . . . . . . . . . . . . . . . . . . . . post method . . . . . . . . . . . . . . . . . . . . . . . . . Retrieving form values with Request.Form . . . . . . . . . . Creating sample login forms . . . . . . . . . . . . . . . . . . Forms with text box elements . . . . . . . . . . . . . . . Forms with list/menu elements . . . . . . . . . . . . . . Menu element selection form with conditional logic Forms with check box elements . . . . . . . . . . . . . . Receiving data from a URL parameter . . . . . . . . . . Retrieving URL parameters with Request.QueryString Sending form values to e-mail . . . . . . . . . . . . . . . . . Setting up your SMTP server . . . . . . . . . . . . . . . . ASP mail components . . . . . . . . . . . . . . . . . . . General requirements for mail components . . . . . Sending e-mail with mail components . . . . . . . . . . Sending e-mail with CDO . . . . . . . . . . . . . . . Sending mail with AspEmail . . . . . . . . . . . . . . Sending e-mail with JMail . . . . . . . . . . . . . . .
x
. . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . .
134 134 135 135 135 136 137 138 139 141 141 143 143 146 147 148 148 151 154
CONTENTS
Dynamic e-mail interaction . . . . . . . . . . . . . . . . Sending e-mail by hyperlink . . . . . . . . . . . . . Sending e-mail via a form button . . . . . . . . . . Making e-mail property values dynamic . . . . . . Sending e-mail with dynamic values . . . . . . Sending e-mail with dynamic form field values Sending a page to a friend . . . . . . . . . . . . Real-world examples using forms . . . . . . . . . . . . Sending a user a forgotten password . . . . . . . Creating a mailing list . . . . . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
Chapter 6 Building a Random Quote Generator Creating the quotes database table Building the form . . . . . . . . . . The Insert Record server behavior . Adding conditional code . . . . The Repeat Region server behavior The Update Record server behavior The Delete Record server behavior Conclusion . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
176 177 179 180 182 186 189 192
195
. . . . . .
. . . . . . . . . . . . . . . . . . . . . .
156 156 158 160 160 162 164 167 167 170 173
175
. . . . . . . . . . . . . . .
Chapter 7 Completing the Quotes Administration System Updating the quotes database table . . . . . . . . . . Author administration . . . . . . . . . . . . . . . . . Building the Insert Author page . . . . . . . . . . Category administration . . . . . . . . . . . . . . . . Building the Insert Category page . . . . . . . . . Updating the Insert Quote page . . . . . . . . . . . . Creating the recordsets . . . . . . . . . . . . . . . Building the Authors recordset . . . . . . . . Building the Categories recordset . . . . . . . Building dynamic select lists . . . . . . . . . . . . Updating the Insert server behavior . . . . . . . . . . Updating the edit page . . . . . . . . . . . . . . . . . Copying recordsets . . . . . . . . . . . . . . . . . Adding authors and categories to the edit page . Updating the Quotes recordset . . . . . . . . . . Binding dynamic select lists with a selected item Updating the Update server behavior . . . . . . . The random quote generator . . . . . . . . . . . . . Creating a join in the database . . . . . . . . . . Displaying a random quote . . . . . . . . . . . . Building the Quotes recordset . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . .
196 199 199 201 201 203 203 203 204 204 207 208 208 210 211 211 213 214 214 216 217 220
xi
CONTENTS
Chapter 8 Restricting Access
Creating the administrators database table . . . Creating the login system . . . . . . . . . . . . . Building the login form . . . . . . . . . . . . Adding the Log In User server behavior . . Restricting access . . . . . . . . . . . . . . . Adding the Log Out User server behavior . Registering new users . . . . . . . . . . . . . . . Checking the new username . . . . . . . . . Creating a user-friendly login . . . . . . . . . . Expanding the Log In User server behavior code Implementing the “remember me” feature . . . Updating the login form . . . . . . . . . . . Baking the cookies . . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . .
Chapter 9 Creating a Blog
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
224 225 225 227 229 231 233 235 236 237 239 239 241 243
245
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Blogging application overview . . . . . . . . . The database . . . . . . . . . . . . . . . . The blog display . . . . . . . . . . . . . . . Administrative controls . . . . . . . . . . . Administrative login/logout . . . . . . . . The search function . . . . . . . . . . . . . Creating your blog database . . . . . . . . . . Creating the database tables . . . . . . . . Table 1: tbl_onews . . . . . . . . . . . Table 2: tbl_users . . . . . . . . . . . . Populating the database tables . . . . . . Populating tbl_onews . . . . . . . . . Populating tbl_users . . . . . . . . . . Setting user permissions for tables . . . . Connecting Dreamweaver to your database . Connection strings . . . . . . . . . . . . . DSN . . . . . . . . . . . . . . . . . . . . . . Displaying blog entries . . . . . . . . . . . . . Creating onews_main.asp . . . . . . . . . Designing onews_main.asp . . . . . . Wiring up onews_main.asp . . . . . . Creating onews_details.asp . . . . . . . . Designing onews_details.asp . . . . . . Wiring up onews_details.asp . . . . . Creating onews_archives.asp . . . . . . . Designing onews_archives.asp . . . . . Wiring up onews_archives.asp . . . . . Blog administration . . . . . . . . . . . . . . . Creating onews_admin_archives.asp . . . Designing onews_admin_archives.asp Wiring up onews_admin_archives.asp
xii
223
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
246 246 246 247 247 247 247 249 249 250 250 251 251 251 253 253 254 255 255 256 257 261 262 262 264 264 265 266 266 267 268
CONTENTS
Creating onews_admin_details.asp . . . . . . . . . . . . . . . . . . . . . . . Designing onews_admin_details.asp . . . . . . . . . . . . . . . . . . . . Wiring up onews_admin_details.asp . . . . . . . . . . . . . . . . . . . . Securing the blog administration pages and creating login/logout functionality Designing login.asp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Wiring up login.asp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating logout.asp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Searching your blog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating the search form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Creating the results page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Designing onews_searchresults.asp . . . . . . . . . . . . . . . . . . . . . . . Wiring up onews_searchresults.asp . . . . . . . . . . . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Chapter 10 Image Gallery
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
270 271 273 276 277 278 279 281 281 281 283 283 285
287
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Overview of the image gallery application . . . . . . . . . . . . . . Storing information in the database . . . . . . . . . . . . . . . Inserting, editing, and displaying albums . . . . . . . . . . . . . Uploading and displaying photos . . . . . . . . . . . . . . . . . Editing captions and deleting photos . . . . . . . . . . . . . . . Creating the database for the image gallery . . . . . . . . . . . . . Table 1: tbl_photoalbums . . . . . . . . . . . . . . . . . . . . . Table 2: tbl_photos . . . . . . . . . . . . . . . . . . . . . . . . . The relationship between tbl_photos and tbl_photoalbums . . Connecting Dreamweaver to your database . . . . . . . . . . . . . Connection strings . . . . . . . . . . . . . . . . . . . . . . . . . Data Source Name (DSN) . . . . . . . . . . . . . . . . . . . . . Inserting, editing, and displaying albums in the image gallery . . . Creating myphotos_main.asp . . . . . . . . . . . . . . . . . . . Designing the main web page . . . . . . . . . . . . . . . . . Implementing the dynamic features of the main web page Creating addalbum.asp . . . . . . . . . . . . . . . . . . . . . . . Designing the Add Album page . . . . . . . . . . . . . . . . Wiring up the Add Album page . . . . . . . . . . . . . . . . Creating edit_photo_album.asp . . . . . . . . . . . . . . . . . . Implementing the dynamic features . . . . . . . . . . . . . Creating pages for uploading and displaying photos . . . . . . . . Creating upload.asp . . . . . . . . . . . . . . . . . . . . . . . . . Designing upload.asp . . . . . . . . . . . . . . . . . . . . . . Wiring up upload.asp . . . . . . . . . . . . . . . . . . . . . . Creating upload_action.asp . . . . . . . . . . . . . . . . . . . . Creating the Edit Caption and Delete Photo pages . . . . . . . Creating edit_caption.asp . . . . . . . . . . . . . . . . . . . Creating delete_action.asp . . . . . . . . . . . . . . . . . . . Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Index
. . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
287 288 288 288 288 289 289 290 292 294 294 295 295 295 297 298 301 301 302 304 304 307 307 308 309 312 316 317 320 322
327 xiii
ABOUT THE AUTHORS Omar Elbaga has been passionately involved in web development for over six years, over which time he has completed several projects for small businesses and nonprofit organizations, including personal sites. He has previously coauthored two books on Dreamweaver web development, and maintains his own Dreamweaver tutorial/resource site, now known as dmxfire.com. Because he did not start out as a programmer himself, he has a knack for teaching dynamic web development to those who do not have programming backgrounds. He is also a postsecondary language arts instructor, artist, independent filmmaker, and graduate student at New Jersey City University, currently finalizing his master thesis as a reading specialist. You can find some of his work in these areas and more information at http://elbaga.net. Rob Turnbull is the senior developer for Lighthouse – design for business limited, an established new media design and marketing company based in Shrewsbury, UK. Clients across Europe, from small businesses to blue chip companies, provide an increasing workload, which includes the development of databases, websites, multimedia presentations, interactive CD-ROMs, promotional videos, and 3D artwork (animations and stills). His personal website, http://robgt.com, is primarily focused on offering help and guidance to fellow Dreamweaver users, including tutorials and links to helpful resources and some useful extensions. You’ll also find links to relevant books on web development and design, including his three previous books about Dreamweaver.
xiv
ABOUT THE TECHNICAL REVIEWER Jason Nadon has been in the information technology field for the past nine years, and building web applications and solutions with Macromedia tools for the past six. He holds several industry certifications and is currently employed by Thomson Creative Solutions as a web services administrator. Jason also manages the Ann Arbor Area Macromedia User Group and enjoys being an active member of the Macromedia developer community.
xv
ACKNOWLEDGMENTS Thanks to my mom and dad for raising me, supporting me, and pushing me toward fulfilling all of my educational goals and aspirations. Thanks to Uncle Ibrahim and Uncle Salah for being two of the greatest male role models in my life. Thanks to Aunt Khadiga and Aunt Hanem for being like second mothers to me. Thanks to my classy fiancée, Mona, for always being there, standing beside me and supporting me whether things are up or down, and always making my heart smile. Thanks to my brothers and sister, Tamer, Hesham, Soliman, and Yasmine—I couldn’t ask for better siblings to have in my life! Thanks to my baby niece, Safiya; I can’t wait to see you grow up. Also, thanks to all spouses and relatives of the people I have mentioned who have also been there for me. Thanks to the true and caring educators who taught me at NJCU, and my sincere and faithful teachers at McNair Academic High School. Thanks to all of my own students at Middlesex County College and Hudson County Community College. Thanks to Ihsan, and all my friends who stand by me; you know who you are. Thanks to you, dear reader, for entrusting me with your learning. —Omar Elbaga
xvi
INTRODUCTION We’re glad you picked up this book to begin learning about building dynamic websites using Dreamweaver 8 with ASP technology. This book is geared for both beginners who know little about dynamic and database-driven websites, and intermediate users who want to begin building more powerful web applications—such as blogs and photo albums—along with working administration systems to effectively manage those data-driven applications. To complete all of the activities in this book, you will only need Dreamweaver 8, a server running Microsoft’s classic ASP (Active Server Pages), and Windows 2000 or above. If you do not use the Windows platform, you can run the code remotely, such as on your web host’s server—just make sure your web host allows ASP scripts to run on its server. You should also have either Microsoft Access 97 or higher, or SQL Server 2000 or higher, to build the databases that you will connect your pages to. You can download a 180-day trial of the new SQL Server 2005 at www.microsoft.com/sql. Alternatively, you can make use of the new (and free) Express edition of SQL Server 2005, which is available from the same location. You can also download a 30-day trial of Dreamweaver 8 at www.macromedia.com. It is possible that throughout your reading of this book, you will have some questions or comments, so feel free to drop the authors a note. Omar Elbaga can be contacted directly through the feedback/contact section of his website, http://elbaga.net, and Rob Turnbull can be contacted through the contact form on his website, http://robgt.com. We have written this book for you, and we are here for you. Please give us time to respond due to the large amount of responses we have to deal with. We look forward to helping you learn more about building dynamic websites using Dreamweaver 8 with ASP!
xvii
Chapter 1
DREAMWEAVER AND DYNAMIC SITES
In this chapter, you’ll learn about a number of important concepts, including what a dynamic website is and how it’s different from a static site, what awesome dynamic features Dreamweaver offers you as a progressing web developer, and how ASP (Active Server Pages) fits into the mix. You’ll also discover which ASP features are supported by Dreamweaver, where ASP features are located in Dreamweaver, and how Dreamweaver automates ASP code to create dynamic sites. The first thing going through your mind is probably “What in the world is a dynamic website?” Well, I want you to figure this out with me. Take two minutes and jot down some things you know about the word “dynamic.” What do you think a dynamic site is? And what do you think it can do? Do that, and then come back and continue reading. Remember, you’re thinking of the word “dynamic” in the context of computers and web development. All right, you’re back! That was fast! What did you write down? If you said something like “strong,” you’re right. If you said something like “powerful,” you’re also right; however, these meanings are a little different from what the word “dynamic” means in the context we’re talking about. If you said anything like “changing” or “moving,” you’re right on target—that’s exactly what it means! You can also look it up in the dictionary—if you have access to the Internet, do a quick search at www.dictionary.com or http://m-w.com (Merriam-Webster Online).
1
CHAPTER 1 According to the American Heritage Dictionary, dynamic means “characterized by continuous change, activity, or progress.” That’s it! It’s all about change. See Figure 1-1 for further clarification on the definition.
Figure 1-1. Here is a screenshot of the definition of the word “Dynamic” at Dictionary.com. “Dynamic” means “changing.”
So sit back, relax, and let’s have some dynamic fun! The first thing I want you to ask yourself is “What do I personally do with web development now?” and “What more do I want to be able to do?” If you said to yourself that you’re writing back-end database models for Amazon.com, you might want to stop right here! If you said something like one of the following, though, this book will definitely help you take your web development skills to the next level: I am designing websites for myself and family. I am working for a company whose managers want me to upgrade the site so that they can begin adding content to the site on their own. I want to start doing more dynamic things to my site, such as allowing web surfers to register and log in. I want to start collecting information from my site visitors. I want to start protecting site content from particular web surfers.
Data exchange As a web developer, you need to make your website interesting and interactive. Thus, you need to tailor your website according to the web surfer. Shoving the same static data at all of your users is bound to leave someone (or many people) behind. The greatest problem with a static website is the
2
DREAMWEAVER AND DYNAMIC SITES simple fact that it doesn’t change. Imagine Amazon.com without the personal wish list, or without the capability of tracking your recent purchases, or without the feature that says “Customers interested in this title may also be interested in . . .” Dynamic websites can spontaneously reconstruct themselves according to an individual web surfer’s needs. These sites change depending on how each user interacts with them. This is what data exchange is all about, and data exchange is what enables Dreamweaver 8 with ASP to save your website from static doom! You want to exchange data between yourself and the web surfer; technically, the web surfer’s computer will be doing the exchanging. Basic HTML can’t handle this kind of data exchange, which is why we now use web programming technologies to do this for us—in our case, the particular technology is ASP. The web programming aspect takes care of all the dynamic stuff and then tells HTML what to print out. So instead of having to tell HTML what to do every time you want to change your data (by recreating HTML web pages), you set up an interactive system in which ASP tells HTML what to do. You’re saying, “HTML, we’ve already designed you. From now on, let ASP deal with you for major changes in terms of data.” Let me show you a quick example. If you’ve already set up your environment, you should be up and running to view ASP pages on your local server. (You’ll learn all about setting up the Dreamweaver environment in Chapter 2.)
1. Load Dreamweaver. 2. Choose File ➤ New, and select the General tab. Select Basic Page from the Category menu (on the left) and HTML from the Basic page menu (on the right), and click the Create button at the lower right of the window (see Figure 1-2).
Figure 1-2. View of Dreamweaver’s options for creating a new document
3
CHAPTER 1
3. On your new “basic” page, type in the following message in design view: Hi, I don't know who you are because I'm just a plain ol' HTML web page. You might want to change the title of your document. I changed the title of my document to Plain ‘ol HTML. View the page in your web browser by selecting File ➤ Save As, naming the file, and finally loading it into your browser. You can also press F12 to have Dreamweaver automatically load the page into your browser (see Figure 1-3).
Figure 1-3. View of static HTML page in the web browser
4. Next, within Dreamweaver, select File ➤ New. Select the General tab, highlight Dynamic page from the left-hand Category list and ASP VBScript from the right-hand Dynamic page list, and click the Create button at the lower right of the window (see Figure 1-4).
Figure 1-4. View of Dreamweaver’s New Document options, in which Dynamic page and ASP VBScript are selected
4
DREAMWEAVER AND DYNAMIC SITES Your cursor will now be within the design body of the document. From the standard toolbar, select Insert ➤ ASP Objects ➤ Output. Dreamweaver will now create the following ASP brackets for you: . (We’ll go into more detail about these brackets in Chapter 3.)
5. Within the brackets, type the following code: Request.ServerVariables("REMOTE_ADDR") In Code view, your final code should look like the following:
In Design view, you’ll see an ASP textual placeholder that represents the dynamic code. Highlighting the dynamic text in Design view will automatically highlight the same code from within Code view. Switch to Design view, take the focus off the dynamic text by moving your cursor to the right of the text, and hit Enter. Now type the following message: I know who you are now. Your IP address is listed. Don't try anything funny!
6. Save your page as dynamic_asp.asp and view it in your web browser (see Figure 1-5).
Figure 1-5. View of the dynamic_asp.asp page in the web browser
See the difference? With HTML, you’re unable to recognize the web surfer; you can only share your information with him or her. But with ASP, you can collect information from the user. In this vein, you can also have the web surfer provide you with specific information, which can be accomplished through forms. We’ll go into further detail about this in the chapters to come, but most importantly, we want to drive the following point home:
ASP gives you the ability to interact with your web surfers by allowing you to exchange data with them. What’s more, once you have that data from the user, you can update data on your web pages accordingly.
5
CHAPTER 1 With a static HTML website, your data is merely sent to the web surfer’s web browser, unchanged and unprocessed, by a dynamic web programming language such as ASP (see Figure 1-6).
Figure 1-6. Illustration of data flow from a static site
With a dynamic ASP website, data can be sent back and forth between the website and the web surfer’s web browser (see Figure 1-7). As a web developer, you can do a variety of things with the data, such as collecting it for statistical purposes or processing it with a dynamic web programming language such as ASP. In the latter case, ASP processes the data on the server and then recreates the HTML page, sending the data back to the web surfer’s browser with new data.
Figure 1-7. Illustration of how data is exchanged between a dynamic site and the web surfer
Data that you provide, and data you collect from the web surfer’s computer, can be stored in a database. The ASP page can then connect and interact with the database while interacting with the web user. The flow of the interaction is all up to you (see Figure 1-8). For example, you can send data that you specify (such as contact info or “about” info) from a database to the web surfer’s browser without allowing the user to alter the data, or you can actually allow the surfer direct access to the database so they can add, edit, and delete data.
Figure 1-8. Illustration of database-driven data exchange between a dynamic site and the web surfer
6
DREAMWEAVER AND DYNAMIC SITES
Dynamic takes over static What do I mean by dynamic “taking over” static? I mean that we’re now in a new era of web development and we need to pick up the pace and get with the times. Web development has been zooming right by us, and you’re just sitting around doing nothing! Well, not you, since you picked up this book. Web development has progressed from displaying simple pictures to streaming live video footage. Even more drastically, it has gone from displaying basic text to regenerating huge reports on the fly, in seconds, at the touch of a web button. It has gone from static text to dynamic text—for example, you were once able to write up your own resume, create a website with basic HTML pages, and upload it to the Web. Now, websites are able to generate your resume and a thousand others on the fly, at the same time, based on the simple submission of a couple of online forms! If you don’t believe me, go visit Yahoo’s Hotjobs (http://hotjobs.yahoo.com) or www.monster.com.
Dreamweaver server models How exactly does Dreamweaver make your sites dynamic? In the past, you could create HTML pages through Dreamweaver’s powerful visual layout system, but you would then have to edit the content of the actual HTML page and hand-code the HTML tags over again to make the pages more dynamic. Now, Dreamweaver integrates what Macromedia calls server models. You, as a web developer creating websites with Dreamweaver, get to choose whichever server model you want to create dynamic websites with, almost seamlessly. And the best part about it is that Dreamweaver generates the web programming code for you through its robust internal storage of stock code. It does so based on the server model you select.
The ASP VBScript server model When developing web applications in Dreamweaver, it’s a good idea to choose a server model that you’re familiar with, or at least one that you want to become more familiar with. When you use server models, Dreamweaver will generate full-blown programming code—but you’ll want to be able to know what Dreamweaver is doing, and you’ll also want the ability to tweak code to attain more desirable results. As such, this book will familiarize you with ASP as a language before teaching you how to develop using Dreamweaver’s drag-and-drop ASP server behaviors. We’ll show you how to set up your environment in the next chapter—but for now, fire up Dreamweaver. Let’s take a look at the server models that Dreamweaver supports.
1. From the toolbar at the top, select Site ➤ New Site. 2. Select the Advanced tab, and then highlight Testing Server in the Category list.
7
CHAPTER 1
3. You’ll see a drop-down list of the server models. Take a look at all of the server models Dreamweaver supports (also shown in Figure 1-9).
Figure 1-9. The listing of server models Dreamweaver supports
ASP can be coded using either JavaScript or VBScript. Throughout this book, you’ll be using ASP with VBScript, not JavaScript. The reason for this is that VBScript is much easier to code with. JavaScript is much more sensitive—it’s case-sensitive, which can drive a programmer crazy, let alone people like us. One incorrect case and the entire web application can go bananas. Even more importantly, there is loads of free information on ASP with VBScript; but it’s hard to get support with ASP coded with JavaScript because it’s rarely used. VBScript is the most popular language to code ASP pages in, and you’ll find tons of resources on the Web. Go ahead and do a Google search if you don’t believe me, but I know you trust your teacher!
Throughout the book, you’ll be working with the ASP VBScript server model. Since Dreamweaver automatically generates all the code for you, it’s technically possible to use the ASP JavaScript built-in server behaviors (or any server model for that matter) for these exercises. As you progress through the book, however, you’ll be enhancing Dreamweaver’s automatically generated code, as well as the VBScript code itself, so it’s important that you stick with the ASP VBScript server model throughout.
8
DREAMWEAVER AND DYNAMIC SITES
What Dreamweaver 8 offers you as an ASP developer Earlier, I said that ASP makes web pages dynamic by allowing the exchange of data between your website and the web server. ASP does this in two main ways. One way is through ASP’s own unique language, which makes use of conditional logic, functions, sessions, and cookies. (You’ll learn more about all of these in Chapter 3.) Another way ASP does this is through connecting to databases.
Checking out data Regarding the first way mentioned, ASP can respond to a user’s interaction in various ways depending on the criteria you specify. For example, you could have ASP detect which browser your web surfer is using to view your site, and then you could have ASP automatically redirect the user to a different page of your choice. Before ASP, you couldn’t do this sort of thing with ease—now, you no longer have to be there when it’s all happening. You can set the conditions and then let ASP do the work. (You’ll learn more about this in Chapter 3.) With ASP functions, you can verify data submitted through a form on your site and have ASP respond accordingly. For example, say you want to make sure that a user reads a “Terms and Conditions” page before proceeding on your site. In such a case, you can make sure the user ticks an appropriate check box before submitting a form—if the user fails to do this, you can redirect him or her to an error page. More generally, you can make sure the user provides you the data you need in order for him or her to go on interacting with your site.
Connecting to databases The second way that ASP allows the exchange of data is one of the most unique and fun features about Dreamweaver: ASP can actually connect to a database, and Dreamweaver automates the whole process for you. Being that ASP code itself can qualify data, imagine how much more ASP can do when it has the ability to connect to a database. Now you’re talking about qualification on a much grander scale. As you know, databases can store huge amounts of data efficiently. Databases make it easy to store, edit, and view data once an efficient database schema is set up. I’m sure you’re familiar with Microsoft Access—this is one of the most popular database systems used around the world, but it’s mainly used for local office use, and not to store huge amounts of data, because it’s simply not as robust as others. When it comes to companies that need to store massive amounts of data, SQL Server is more popular. Anything you can do with databases on your computer locally you can now do online with ASP—not only querying data, but also inserting, editing, and deleting it. Now that’s dynamic. For example, instead of having to create a static HTML web page for every one of your products, you can create one master template—that is, one ASP page that connects to the database and has the ability to display any product selected by the user. The ASP code requests the desired item from the database and simply inserts it into the ASP page, preventing you from having to create a separate HTML page for each product.
9
CHAPTER 1
Where is ASP in Dreamweaver? Great question! Now you’ll take a quick look at where the heck your ASP stock code is located within Dreamweaver, and how you access it.
ASP features supported by Dreamweaver Anything you can do in ASP can be done within Dreamweaver. Dreamweaver’s versatile page layout options allow you to view your pages in three different views: Design, Code, and Split (shown in Figures 1-10, 1-11, and 1-12, respectively). Design view allows you to use Dreamweaver’s built-in functions for HTML, JavaScript, and ASP. Code view gives you the option to insert ASP code directly onto the page. Split view allows you to switch easily between Design and Code view, or have a look at both views at the same time. This is helpful when you want to make changes to code directly and see instantly how they affect the design of the page.
Figure 1-10. Example of Dreamweaver page development in Design view
Figure 1-11. Example of Dreamweaver page development in Code view
10
DREAMWEAVER AND DYNAMIC SITES
Figure 1-12. Example of Dreamweaver page development in Split view
Before you dive into any ASP, which will naturally be a bit foreign to you, you’ll briefly look at two main sections of Dreamweaver: the Insert bar and the Application panel.
Insert bar Once you select the server model you’ll be using—ASP VBScript—you can gain access to ASP from two main sections in Dreamweaver: the Insert bar and the Application panel. Let’s take a look at the Insert bar first, which is located above the Dreamweaver document window and below the standard toolbar. It’s displayed by default—but to be sure it’s open in your Dreamweaver window, go to View ➤ Toolbars and make sure Insert is checked. Once it’s open, you can view the Insert bar in two different styles. The first style is the Show as Menu view, in which each category in the bar is displayed separately (this is Dreamweaver’s default style). With this view, you have to click your selection from a drop-down menu on the left-hand side of the Insert bar each time you want to view a new category. Figure 1-13 shows this style, in which the Application category is displayed.
Figure 1-13. The Application category of the Insert bar in the Show as Menu view
If you click the Application text, you’ll see a menu displaying the other elements. The other Insert bar style, which I personally prefer, is the Show as Tabs style. In this style, elements are grouped as tabs that form one panel (see Figure 1-14). You can select this style by clicking Application on the Insert bar, and then clicking Show as Tabs. This view allows you to switch between different elements easily.
Figure 1-14. The Insert bar in the Show as Tabs view
11
CHAPTER 1 Switch to the Show as Tabs view, and try clicking the ASP tab Your Insert bar should now look like Figure 1-15.
Figure 1-15. The ASP tab of the Insert bar in the Show as Tabs view
You can also access these same menus through the standard toolbar by selecting Insert ➤ Application Objects and Insert ➤ ASP Objects. This is where the majority of your ASP functionality is located. Before I describe the other place Dreamweaver stores ASP functionality—the Application panel—let’s take a brief look at what’s stored in the ASP and Application tabs of the Insert bar.
The Insert bar’s ASP tab The Insert bar’s ASP tab stores some of your basic ASP hand-coding functionality. Using this menu will help speed up some of your basic hand-coding. This menu doesn’t store your major ASP dynamic functionality, however. You won’t use it that often because it only automates some basic text for you. You should still try it out, though. By the time you get through Chapter 3, you’ll be able to write all of this code yourself with ease. This menu just helps speed up the process slightly. In the sections that follow, I'll briefly describe the functions of each icon on the ASP tab, from left to right. (You can see the name of each button in a tooltip if you hover over the icon.) Note that some of the buttons are described under one heading due to their relationship.
Server Variables. Server variables hold information about your server—the computer server your web pages are hosted on. This information includes data such as IP address, type of computer, location of your web pages, names of files and folders, and so on. ASP can access these variables using code such as the following, which prints out the server’s IP address to the screen:
Dreamweaver stores the different code needed for your convenience so you don’t have to remember it.
Include. Includes, also known as Server Side Includes (SSI), are simply pieces of code saved as separate files and embedded into other web pages. They come in handy very often—for example, say you have some code that you need on every page, such as a footer including a company name and a date. The date can be automatically updated using an ASP function—but what if you want to update the company name? If the company name is stored in an include file, you just need to change the instance in the include, and the name will be updated on every page. Dreamweaver uses ASP includes with the code it generates to connect web pages to databases because every page in a dynamic site generally needs to connect to the same database(s). Since the code for the connection doesn’t change, Dreamweaver creates one document with the code for the connection and then just adds ASP includes on the pages you specify for the connection; then those pages will reference the code from the original document.
12
DREAMWEAVER AND DYNAMIC SITES
Code Block. This is Dreamweaver’s way of adding a new, blank block or line of dynamic code to your web page. All ASP code must be within ASP delimiters (). Here’s an example of how these delimiters are used in code:
53
CHAPTER 3 View this in your web browser, and you should see the output shown in Figure 3-7.
Figure 3-7. View of datatypes.asp in the web browser after the ASP is code is processed
As opposed to some other programming languages, with ASP VBScript, you don’t specify the data type. The VBScript processor on the server picks it up on its own. Remember that when setting the value of a variable, if you surround a number with quotes, the ASP processor will see it as a string and not an integer—which is OK if that’s what the scenario calls for, such as numbers appearing amidst text. Numbers need to be of an integer data type if you’ll be performing mathematical computations with them.
Variable concatenation Concatenation is a fancy word for “joining things together.” It doesn’t mean adding things together mathematically, it simply means putting things together side by side. In VBScript, the ampersand (&) is the operator that concatenates strings. As an example, let’s try concatenating two strings into one variable. Create the following file and save it as my_name.asp. Enter the following code within the tag while in Code view:
View the page in your browser, and you should see the output shown in Figure 3-8.
Figure 3-8. View of my_name.asp in the web browser after the ASP is code is processed
54
A FIRST TASTE OF ASP With the preceding code, you’ve concatenated the values to be displayed as one by using the & operator. You can also recreate a single variable to represent two variables concatenated. Modify the last example as follows, and you should get the same result as before:
The difference is in the code itself. By creating a new variable, you’ve made it simpler for yourself to display the full name—you don’t have to concatenate both variables each time you want to display a user’s full name. You can concatenate variable and literal values too. For example, the following will also give you the same result as before:
Watching out for “adding” numbers Keep in mind that concatenation only joins things together; it doesn’t add them mathematically in the case of numbers. For example, create a new ASP page named adding_numbers.asp and add the following code between the tags:
When you view this in your browser, you’ll see 2631, not 57 (the result of 26 + 31). If you want to add numbers together, you need to use a mathematical operator called the Addition operator (+), which adds numbers together. Now replace the ASP code in the adding_numbers.asp page with the following code and view the page in your browser:
55
CHAPTER 3 This will give you an output of 57, as shown in Figure 3-9.
Figure 3-9. View of adding_numbers.asp in the web browser after the addition code is processed
Also be aware that although strings can contain numeric values, you won’t be able to perform any mathematical computations on them—since they’re enclosed in quotation marks, they aren’t treated as numbers that can be computed. For example, the following code will give you 2631 again, not 57.
The two strings have been concatenated, not added together.
Variable naming conventions This section is about how to name your variables. You can actually name your variables whatever you like, as long as you don’t break any of the syntax rules, such as using a number as the first character of your variable. The other rules are mentioned in the previous section, “Syntax rules for variables,” if you need a refresher.
Prefixes Although you can name your variables whatever you like, there are some conventions you should follow to make your code more readable and consistent. For example, if a variable is a string, you might add an str prefix, making it str_myvariable or even strmyvariable—but the key here is adding a prefix so that you know what data type the variable is. Sometimes, coders will add initial prefixes according to their names or companies, so that their code stands out. For example, Macromedia will often add the prefix MM to their variables, making them MM_RedirectPage or MM_ConnectionString, for example. I might add OE (my initials) to my variables. Prefixes make your variables more understandable, and can add a personal touch.
Using understandable variable names Believe it or not, this is one of the most important aspects of variables, and for your coding in general! How you name your variables is key to the readability of your code. If you want to create a variable that will store a password, don’t call it p. You may remember what it means for the next five minutes, but when you (or other developers) come back to update the code in six months, there’s no way you’ll
56
A FIRST TASTE OF ASP remember what p stands for. Use pwd or user_password instead. By the way, password is a reserved keyword in some languages, such as SQL. The only time you might consider using a variable name like p is if you want to deliberately hide the variable name for security reasons—for example, if the variable name becomes exposed to a user of your site through a querystring. You can learn more about querystrings at the Microsoft Windows 2000 Server Documentation site, found here: www.microsoft.com/windows2000/en/server/iis/default.asp?url=/windows2000/en/server/iis/ htm/asp/vbob53hj.htm
The best advice to give for naming variables is keep it simple, appropriate, and obvious. Avoid naming your variables solely by initials, such as RP, ag1, or str_cdp, unless there’s a good reason to, which is unlikely. Make sure that what the variable represents is obvious, just from glancing at it, such as RedirectPage, ArabicGreeting, etc. After following these guidelines, feel free to add your own prefixes. For example, str_RedirectPage or OE_ArabicGreeting.
Commenting code Commenting your code allows you to display useful textual information about your code—to yourself or whoever has to sift through it—without it actually being parsed by the server; the server will just ignore the text or code that’s commented out. Here’s an example of an HTML comment: delimiters is ignored by the web browser. HTML comments are, however, viewable by users via the View ➤ Source option of their browsers. ASP comments are created by putting a single quotation mark at the beginning of the line. This causes the line to be ignored by the server, even if it has actual ASP code in it. If you were to input the following ASP code within the body of an ASP page and run it in your browser, it would not appear in the source code for the web page:
57
CHAPTER 3 ASP comments aren’t viewable in the source code of the ASP page fed to the browser because they’re never parsed and sent to the client browser; they’re only viewable when the ASP page itself is opened on the actual server it resides on. Dreamweaver displays all comments in gray in its Code view. Commenting code is very important. It allows you to block out code quickly when you want to test the effect of a certain block of code. This is useful if you’re trying to work out where an error lies. It also gives you the opportunity to document your code for yourself and others. Like using understandable variable names, this is helpful when you or others want to update your code.
Commenting your code allows you to provide useful information about your code, and it’s important to do it as you’re coding, while everything is fresh in your mind.
VBScript’s house of built-in functions VBScript has a number of built-in functions that are at your disposal. They simplify things for you tremendously and give you the ability to manipulate variables as desired. There are different categories for built-in functions, as follows: Conversion functions: used to convert a value from one data type to another (such as from a string to an integer). String functions: perform actions on variables of the string data type. Date/time functions: deal with the display of the date and/or time. Format functions: used for formatting data according to how you want it to be displayed. Math functions: perform mathematical operations. Array functions: used to manipulate arrays. An array is like a list in which each item is referenced by a name and an index number (its location in the list). There are around 100 functions—in this section, you’ll be given a general overview of the most important ones. For a complete list of VBScript functions, check out the following websites: www.w3schools. com/vbscript/vbscript_ref_functions.asp and http://devguru.com/technologies/vbscript/ 13896.asp.
Conversion functions This type of function converts a variable from one data type to another. For example, if you want to convert a number that’s a string to an integer, you use the CInt() function. The variable is placed between the empty parentheses.
58
A FIRST TASTE OF ASP Create a new ASP page and save it as convert_to_int.asp. Insert the following code between the tags:
View the page in your browser, and you should see the results shown in Figure 3-11.
Figure 3-11. View of trim.asp in the web browser. Notice the empty spaces between the periods and the text in the first line.
There are also functions to get rid of empty characters on the left or right alone: LTrim() and RTrim(). They’re used in the same way. Another function, Left(), allows you to return a specified number of characters from the left side of a string. It accepts the number as an attribute after the string. For example, Left(string, 5).
60
A FIRST TASTE OF ASP For an example of the Left() function in action, add the following code to the body of a new ASP page and save it as Left.asp:
You should see the following results: I am cool. Notice how only the first ten characters are returned. Many news websites do this kind of thing to display, say, only the first paragraph of several news articles on a summary page. You should now have a general idea about VBScript functions and how to use them. As shown in the preceding examples, a variable is placed inside the parentheses of a function, and in many instances, additional attributes are also required (as in the case of the Left() function). I would suggest keeping a VBScript reference book handy, as there is a lot to learn, and it’s difficult to remember everything. The following websites are both valuable online references, each of which list the VBScript functions and include examples of their use: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/ vtorifunctions.asp http://devguru.com/technologies/vbscript/13896.asp
Operators Operators allow you to manipulate data stored in variables within your code. Operators have four main classes: Assignment operators store the value to the right of the operator inside the variable to its left. Logical operators join the expression on the left of the operator to the expression on the right in a conditional statement (you’ll learn about conditional statements in the “Conditional logic” section later in the chapter) Comparison operators compare two arguments and check whether a specified condition is met. Mathematical operators perform a mathematical operation between the values on the left and right of the operator.
61
CHAPTER 3
Assignment operators There’s only one assignment operator, and that’s the equal sign (=). It simply stores the value to the right of the operator inside the variable to the left. You’ve been doing this throughout the examples in this chapter, so you should be used to it by now. Here’s an example:
The preceding assignment operator simply stores the string Hola inside the variable myGreeting.
Logical operators There are three logical operators. Logical operators simply join together or manipulate Boolean (true or false) expressions in conditional statements. Operator
Meaning
AND
Logical combination
OR
Logical separation
NOT
Logical negation
Let’s have a look at each of these operators and see how they join and manipulate expressions.
AND, OR The AND operator combines two expressions, making a result true only when both expressions are true. The OR operator separates the two expressions, making a result evaluate to true if either expression is true. Let’s see these in action. Create a new page and save it as andor.asp. Insert the following code within the body:
62
A FIRST TASTE OF ASP The preceding example checks whether both the variables number1 and number2 equal 3. Since they do not both equal 3, False is printed out, as shown in Figure 3-12.
Figure 3-12. View of andor.asp in the web browser. The result is False when the AND operator is used.
Now if you use the same code and change the AND to OR, what do you think the results will be? Try it and see. The result is shown in Figure 3-13.
Figure 3-13. View of andor.asp in the web browser when the OR operator is used
In the preceding example, when AND is replaced with OR, the code checks whether either variable number1 or number2 equals 3 (notice that number1 equals 3 but number2 does not). If either of them do, the word Correct prints to the screen.
NOT The NOT operator simply negates the statement to the right of the operator. If an expression is True, NOT will change it to False, and if the expression is False, NOT will make it True. The following two code blocks give a good indication of how the NOT operator works. Create a new ASP page and save it as NOT_1.asp. Insert the following code between the tags:
Since 4 – 1 = 3, Correct will print out. Now add the NOT operator, as shown in the following code, and see what happens:
This time, False is returned—number1 still equals 3, of course, but the NOT operator changes the code to become the opposite of what it would otherwise be.
Comparison operators Comparison operators compare two arguments and check whether a specified condition is met. The following table summarizes each comparison operator and its meaning. Operator
Meaning
=
Equal to
Greater than
=
Greater than or equal to
Not equal to
For example, consider the following code:
View the page in your browser, and you should see the results shown in Figure 3-14. 1.66666666666667 1 2
Figure 3-14. View of divide_operators.asp in the web browser
Operators are used all the time. You’ll use them so much that they’ll become second nature to you. However, it’s a good idea to always have a reference manual available with you. For further reading on VBScript operators, visit http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ script56/html/vbsoperators.asp.
Operator precedence As you know, ASP code executes from left to right, line by line. But there’s an exception to this— some operators execute according to their own order, known as operator precedence. While comparison operators all have equal precedence (and thus execute from left to right), mathematical and logical operators execute in their own order of precedence, regardless of their position in a line. The following table lists the order of precedence of mathematical and logical operators. Operator type
Operation
Precedence order
Mathematical
66
Exponentiate (^)
1
Multiply (*), divide (/), integer divide (\)
2
Modulus (MOD)
3
Add (+), subtract (-)
4
A FIRST TASTE OF ASP
Operator type
Operation
Precedence order
Logical NOT
1
AND
2
OR
3
Note that operators listed on the same line of the preceding table are of equal precedence; they will be processed in left-to-right order when they appear in the same line. As an example, create a new ASP page and save it as operator_order.asp. Insert the following code in the page and view it in your web browser:
In left-to-right order, the answer you would expect is 20, since 3 + 2 = 5, and 5 ✕ 4 = 20. However, since multiplication has a higher precedence than addition, the answer will be 11. With the multiplication command executing before the addition, the equation is actually 2 ✕ 4 + 3. Using parentheses to group expressions allows you to force operators to execute before those with a higher precedence. For example, to force addition to occur before multiplication in the preceding expression, you would replace the code in operator_order.asp with the following:
Figure 3-15 shows the new result.
Figure 3-15. The new result from operator_order.asp, this time using parentheses to override operator precedence
Expressions in parentheses are always evaluated before expressions that aren’t in parentheses, regardless of operator precedence. You should always group mathematical expressions in parentheses, even if the natural order is what you desire, simply to make your code more readable.
67
CHAPTER 3
Conditional logic Like variables, conditional logic is one of the most important aspects of the language, because it allows you to control the flow of your application according to certain criteria—in particular, according to how web users interact with your code. Conditional logic (also known as conditional statements) allows you to use code that says things like “If this happens, then I want you to do this, but if it doesn’t, do that instead.” Let’s take a look at how you can control the interaction you receive with conditional logic.
The If statement The If statement is the mother of all control. It says, “If this is true, then do this; otherwise, do that.” Take a look at the following example. Create a new page and save it as ifstatement.asp. Enter the following code anywhere between the tags:
View the page in your web browser, and you should see the results shown in Figure 3-16.
Figure 3-16. View of ifstatement.asp in the web browser
In the preceding code snippet, the If statement checks to see whether the myExpectedOutput variable equals your desired value; and when it does, you can specify accordingly what action you want to take place when you receive an expected output. In the previous example, the action taking place is the printing of a related message to the user. Keep in mind that when comparing two strings, every character in each string (including spaces) must match for them to be considered equal.
You can also set the conditions around embedded HTML by using multiple code blocks, as follows:
That's what I thought!
This will return the same results as the previous code. However, if the condition is not true, the HTML won’t display. This is often used when you want to check if a user is logged in. To do this, you could use an If statement to verify whether a cookie you previously set exists. If it does, you can allow a user access to a page; if it isn’t, you can simply redirect the user to another page to prevent access.
68
A FIRST TASTE OF ASP
The If . . . Then . . . Else statement You can also add the Else keyword to the statement to introduce another output if the expression doesn’t meet the expected criterion. Create a new ASP page and save it as expectedoutput.asp. Enter the following code between the tags:
This will output to the web browser the results shown in Figure 3-17. In the preceding code, the If statement checks to see whether the myExpectedOutput variable equals your desired value. If it doesn’t, the Else statement causes the comment Hey, think again. to be output. Again, you can set these conditions around embedded HTML using multiple code blocks, as in the previous example.
Figure 3-17. View of expectedoutput.asp in the web browser
The If . . . Then . . . ElseIf statement The If...Then...ElseIf statement allows you to provide two or more possible code continuations. This statement is preferable to using multiple If...Then...Else statements, which can result in inefficient and sloppy code. The ElseIf statement is beneficial in that it allows you to combine multiple If...Then...Else statements in one. Take a look at the following example. Create a new ASP page, save it as user_rating.asp, and enter the following code between the tags:
69
CHAPTER 3 Since the value of the userRating variable is set to 9, this code will output the results shown in Figure 3-18. The preceding code can be used to allow a web user to enter a rating into a form, and then be returned the appropriate response. Let’s see it in action.
1. Create a new dynamic ASP VBScript page and name it user_rating.asp. Feel free to overwrite the last ASP page you created.
2. Switch to Design view and create a simple form with one
Figure 3-18. View of user_rating.asp in the web browser
text field and one Submit button.
3. Name the text field userRating and set the action to go back to the same page. 4. Now switch to Code view and insert the following code anywhere between the HTML tags:
5. Now load the page in your web browser. Try entering 4, 6, 9, and 10, and see how the responses change with each different entry (see Figure 3-19).
Figure 3-19. View of user_rating.asp in the web browser when a 4 is submitted through the form
70
A FIRST TASTE OF ASP You can use an Else keyword for your last check in an ElseIf statement. It gets processed only when none of the other conditions match. Be aware that if you use it, you must put it at the end of the statement, and never before an ElseIf keyword. The following example shows the correct use of the Else statement in such a case:
Looping logic Technically, a loop statement allows you to loop through an action while or until a condition you specify is met. In other words, it gives you the ability to have an action occur over and over until you want it to stop. For example, you may want to loop through the code and list a set of variables or a set of records listed in a database table. In VBScript, there are several different types of loop statements that for the most part accomplish the same task. I’ll demonstrate two of the most commonly used ones.
The Do . . . Loop statement This loop allows you to create a loop while a condition you specify is true. If the statement could talk, it would say something like this: Do While your condition Code to be executed here Loop What will happen is your code will keep going according to the condition you specified. It will stop when the condition is met or not met, depending on the type of condition you specify. You might tell it to keep printing a database record to the screen while the record doesn’t equal a particular value. You can also tell it to keep printing a database record until it equals, say, 10.
71
CHAPTER 3 Let’s take a look at a real example. Create a new ASP page, save it as dowhile.asp, and insert the following code between the tags:
As you can see, the code is very simple. The following creates an instance of the CDO object within your ASP page: Set myMail = CreateObject("CDO.Message") We named the CDO object myMail, but you could call it whatever you like: objSendMail, Mail, CDOmail, and so on. Each object property is referred to in the context of its object (i.e., objCDO.PropertyName). If you named the object objSendMail, for example, you would refer to a property as objSendMail.PropertyName.
148
WORKING WITH FORMS The preceding code contains four properties and one method: the From, To, Subject, and TextBody properties, and the Send method. As you might guess, the From property contains the e-mail address of the sender, and To contains the e-mail address of the receiver. Subject contains the subject of the e-mail, and TextBody contains the body of the e-mail. Lastly, the Send method actually sends the e-mail. The Configuration field is a namespace that defines most fields for the CDO object. These namespaces are stored on the Microsoft website, and you retrieve them in the code to set various configurations for the object, such as whether the object should be sent from a local or remote server, the IP address, username and password authentications, the port, and so on: Configuration.Fields.Item("http://schemas.microsoft.com/cdo/ ➥ configuration/sendusing") After the object does its job, you clear it from the server by destroying the object with the following code: set myMail = nothing You can test the execute_cdo.asp page by loading it into your browser. Once the page loads into the web browser successfully, the CDO code will have just executed, since the ASP code is executed on the server first and then the page is sent to the user’s web browser. The HTML page itself will come up blank, as you haven’t done anything else to it. To ensure that the e-mail was sent, you must check the inbox of whatever e-mail address you defined in the To property. You should see the following as the body of your e-mail: Hi, I was sent because the page execute_cdo.asp on my server was accessed. To send e-mail using CDO remotely, you can change the values of the namespace to send the e-mail through a remote SMTP server:
Notice the additional namespaces where you configure the username and password to connect to the SMTP server. Usually, one of the live e-mail accounts associated with your website and its related password would serve as the username and password. Your web host can provide you with this information, as well as the correct IP address.
Formatting e-mail with HTML in CDO In the preceding code, you used the property for plain text so all text defined for the TextBody property was translated as plain text and any HTML contained within it will not be parsed. To use HTML tags in the body of the e-mail, change the TextBody property to HTMLBody, for example: myMail.HTMLBody = "This is a message." Once you have changed the e-mail format to HTML, you can format the content with any of the HTML tags. For example, you could change the font and even add images. Let’s say your logo (or any other image) exists in a folder on your server (with the URL path http://www.dmxfire.com/images/ logo_main.gif), and you want to embed it in an e-mail with the tag. You can now embed this link as the value of the HTMLBody property, and the HTML will be parsed if the recipient allows HTML e-mails: myMail.HTMLBody = ""
As you recall from Chapter 3, double quotes mark the start and end of a variable value, so another set of quotations within those will confuse the ASP processor and cause erroneous results. You need to escape the double quotes in the HTML tags. You can escape quotes that may need to appear with the value of a variable by using either two double quotes, "", or one single quote, '.
When you check the e-mail, you should see the image in the body. Now you can understand how many big websites send out those newsletters that look like web pages to your inbox! You can add any HTML you like to produce a web page as the body of an e-mail—you could even attach a CSS stylesheet that’s hosted remotely. But before you decide to send all your e-mails in HTML, consider the fact that some of your recipients’ mail programs may disallow HTML to render in e-mails due to the security risks involved. HTML tags will not be parsed in an e-mail program that rejects HTML; in such a case, the e-mail will just appear with unrendered HTML markup, making the e-mail completely unreadable. Plain text e-mails work fine and are the best format for the majority of your e-mails, unless you feel it’s absolutely necessary to send an e-mail in HTML.
150
WORKING WITH FORMS
Sending carbon copies (cc) and blind carbon copies (bcc) with CDO You may be wondering how to send an e-mail to several e-mail addresses. To do this, you can simply repeat the objCDO.To property, inputting a different e-mail address. For example, here’s how you could change the code for the execute_CDO.asp page to send your e-mail to two different addresses: myMail.To = "" myMail.Cc = "" Alternatively, to send a carbon copy of the e-mail to another address, use the cc and bcc properties, myMail.Cc and myMail.Bcc: myMail.To = "" myMail.Cc = "" myMail.Bcc = "" In the first example, both recipients will see the e-mail addresses of all that receive carbon copies, but in the second example, no recipient will be able to see the e-mail address of the recipient who receives the blind carbon copy. However, the bcc recipient will still see the e-mail addresses of the cc recipients.
The IMessage Interface documentation at Microsoft provides more information on CDO’s interface: http://msdn.microsoft.com/library/default.asp?url=/library/ en-us/cdosys/html/39186eaa-c4c1-430a-9715-35e291925c5c.asp. We also recommend perusing the various levels of that documentation for a deeper look at CDO for Windows 2000.
In the next couple of sections, we’ll cover the syntax of two other popular mail components: AspEmail and JMail. However, we won’t go into as much detail for AspEmail and JMail as we have for CDO in this section. It isn’t that one is better than the others—it’s just that you can do the same things with each component once you know the basic syntax (especially the properties).
Sending mail with AspEmail AspEmail is another popular ASP mail component, but unlike CDO it doesn’t come with IIS. It is proprietary software available from Persits Software, Inc. (www.persits.com), which offers a free version of this mail component on its website as well as some commercial premium features. When you download the free version of AspEmail, the commercial premium features will be available for 30 days, but the generic features will always be available. The commercial version comes with a few more useful properties that you can use, but the free version contains all that you need to work through the examples in this chapter, and possibly for most of your own examples down the road. You can download the latest version of the AspEmail component at www.aspemail.com/download. html. Once you download the component, install it by double-clicking the file. Make sure you register the component when prompted during installation. If you will be using this component on your website that is hosted remotely, make sure your web host has this component installed on the server available for your use. Usually when you sign up for a web hosting package, you are informed about which components come with the package.
151
CHAPTER 5 Back in Dreamweaver MX, create a new dynamic ASP web page and save it as execute_aspemail.asp. Add the following code above the tag:
Replace the text set in the From and AddAddress properties with the appropriate e-mail address. The From property holds the sender’s e-mail address, and the AddAddress property holds the recipient’s e-mail address. Just like with the CDO object, you have to create an instance of the object: Set objASPEmail = Server.CreateObject("Persits.MailSender") For the AspEmail component, you need to specify the SMTP server address in a property called Host, something you didn’t have to do with CDO when running it locally. If you are testing locally, you should input your IP address. (You can find out your IP address by typing ipconfig at the command prompt or by simply using 127.0.0.1.) If you are executing the page on a page hosted by a web host, you need to contact the host for the correct SMTP server address, as mentioned previously. The other properties are not new to you. The only differences are the property names, but they all have same functionality as the CDO properties. However, you may be confused by the AddAddress method earlier. This is where you specify the recipient’s e-mail address, and it is no different than the To property of CDO. You can also specify a label for the AddAddress property, displaying a name for the e-mail address. To do so, add a comma after the e-mail address and put the name within double quotes: objASPEmail.AddAddress "", "omar" Also, notice that to define a value for the AddAddress method in AspEmail, you don’t have to use an equal sign; that is because it is a method, not a property, here. It’s a good idea to keep an example of each mail component’s syntax on your PC for quick reference.
The AddAddress does not use an equal sign because the e-mail address is being passed to a method. Properties will always be set using the equal sign, whereas methods will not.
152
WORKING WITH FORMS If you execute the page on a live server and check the e-mail for the e-mail address you specified, you should see the following in the body of the e-mail: Hi, this is an AspEmail component text.
Formatting e-mail with HTML in AspEmail By default, AspEmail sends mail in plain text format. You can send AspEmail e-mail in HTML format by defining the following property as true: IsHTML = True. (If this property is defined as False, AspEmail sends e-mail in plain text.) Change the code for the execute_aspemail.asp page to the following to send an e-mail in HTML format:
If you execute the page on a live server and check the e-mail for the recipient e-mail address you specified, you should see the following in the body of your e-mail: Hi, this is an AspEmail component text.
Sending carbon copies (cc) and blind carbon copies (bcc) with AspEmail AspEmail also has a method for sending carbon copies, called AddCc. To use this method, make the following changes to the execute_aspemail.asp page:
153
CHAPTER 5 As with the AddAddress method, you don’t use an equal sign when giving a value to the AddCc method. Execute the page on a live server and check both e-mail addresses. A copy of the e-mail should have been sent to both. You can also do the same thing by repeating the AddAddress method: objASPEmail.AddAddress "" objASPEmail.AddAddress "" For blind carbon copies, you use the AddBcc method: objASPEmail.AddBcc "email address"
AspEmail extras AspEmail has a couple of extra properties and methods you can use: You can define a display name for the sender e-mail address by using the FromName property, and by using a method called AddReplyTo you can specify a different e-mail address to be used when the recipient clicks the Reply button for that e-mail. Here are some examples: objASPEmail.From = "email address" objASPEmail.FromName = "omar" objASPEmail.AddReplyTo "different email address" For more information on AspMail’s various properties, see the component’s online manual at www.aspemail.com/manual.html.
Sending e-mail with JMail Another popular proprietary mail component is JMail from Dimac Development (www.dimac.net). Look for the product named w3JMail. You can download the free w3JMail version 4.5 from the Dimac website, along with many other commercial products, and install it by simply double-clicking the file after a successful download. (Note that you may be prompted to fill out a registration form.) If you will be using this component on your website that is hosted remotely, make sure your web host has this component installed on the server and available for your use. Back in Dreamweaver, create a new dynamic ASP web page and save it as execute_jmail.asp. Add the following code above the tag:
154
WORKING WITH FORMS Replace the text set for the Sender and AddRecipient properties with the appropriate e-mail addresses. The Sender property holds the sender’s e-mail address and the AddRecipient property holds the recipient’s e-mail address. In the ServerAddress property, you will need to specify your local IP address or, if testing remotely, the IP address of your website, which you can obtain from your web host. Execute the page on your live server. When you check the e-mail, you should see the following in the body: Hi, this is a JMail component test.
Formatting e-mail with HTML in JMail You can change JMail e-mail from plain text format to HTML by defining the ContentType property as "text/html". Change the code for the execute_aspemail.asp page to the following to send an e-mail in HTML format:
Execute the page on a live server and check the e-mail for the recipient e-mail address you specified. You should see the following in the body of your e-mail: Hi, this is a JMail component text.
Sending carbon copies (cc) and blind carbon copies (bcc) with JMail You can also send mail to several different e-mail accounts using the AddRecipientCc method or by simply repeating the AddRecipient property. Here are two examples: JMail.AddRecipient "" JMail.AddRecipientcc "" and JMail.AddRecipient "" JMail.AddRecipient "
155
CHAPTER 5 Sending a bcc to another e-mail address is also easy—you just need to add the AddRecipientBcc property. Here is an example: JMail.AddRecipient "" JMail.AddRecipientBcc "" For more specific information about JMail and its various properties, please visit the Products section of the Dimac site. You can also find the JMail manual on the Products page for w3JMail v4.5.
Dynamic e-mail interaction It’s time for some action! Since everyone is moving from static to dynamic web pages these days, let’s take that attitude with our e-mail also. You now know how to send e-mail through ASP pages, but only how to send it once a page loads and with predefined values. How about sending it after a specific action occurs or allowing the user to define the values for the properties? This is what we will refer to as “dynamic” e-mail, as property values are not hard-coded; rather, they are ever changing. Once you set up the web application, users of your website will be able to alter the property values. How much control you want users to have is up to you. You can allow users to specify the sender e-mail address and predefine the recipient. This is usually the case with feedback or contact forms. You can also allow users to define the sender, subject, and body. The properties will act as regular variables.
In the “Sending e-mail with mail components” section, you learned how to use three different mail components: CDO, AspEmail, and JMail. For the rest of this chapter’s examples, you will use the CDO mail component, because it is more accessible since it comes installed with IIS. Now that you have been exposed to the syntax of all three components, though, you should feel free to modify the code for the mail component of your choice.
In this section, we’ll first cover how to send mail by hyperlink and via a form button, and how to make e-mail property values dynamic.
Sending e-mail by hyperlink You can trigger an e-mail based on many different conditions. Let’s start by triggering an e-mail based on a hyperlink click. In Dreamweaver, open a new document and enter the following script, saving it as email_hyperlink.asp:
Type the following code within the tag: send email Once the page is loaded, nothing happens except that the hyperlink is displayed—but notice the new querystring attached. That lets you know that the mail code was executed, because in the preceding code you attached the querystring based on conditional logic that the code was executed (Figure 5-13).
Figure 5-13. email_hyperlink.asp page before the hyperlink is clicked
The e-mail is not triggered automatically because it is embedded in a conditional statement that tells it to execute on the condition that a URL parameter named hyperlink exists and equals true. When the page is first loaded, there won’t be any URL parameters. Clicking the hyperlink takes you back to the same page, but this time passing the appropriate URL parameter, which triggers CDO to send
157
CHAPTER 5 the e-mail. After CDO is executed, it redirects you back to the same page with a new URL parameter, letting you know that the CDO was executed (Figure 5-14).
Figure 5-14. email_hyperlink.asp page after the hyperlink is clicked
One of the cool things about this method is that everything is on a single page, yet it behaves as though two pages were used. The ASP script is not executed even if the page is consecutively refreshed; it executes only if that particular hyperlink is clicked or the correct URL parameter is passed. The e-mail is executed only when a querystring named hyperlink equals true. After the querystring is passed from the hyperlink, the e-mail is executed, the user is redirected to the same page using Response.Redirect, and the querystring is cleared. For this reason, the e-mail executes only if the hyperlink is clicked. Another way to do this is to have the ASP script on a separate page. You could link to that page and redirect back or to another page, but in this case, the e-mail will be sent whenever the page with the CDO is accessed, whether intentionally or not. At any rate, you could always wrap conditional statements around your ASP script, making sure it is executed only if certain criteria are fulfilled.
Sending e-mail via a form button Sending e-mail based on the click of a form button is fairly simple. To demonstrate, create a new dynamic ASP web page and save it as email_frmbutton.asp, and then follow these steps:
1. 2. 3. 4.
Select Insert ➤ Form ➤ Form. Place your cursor inside the form and select Insert ➤ Form ➤ Button. For Accessibility Attributes, select no label and click OK. Highlight the button in the Dreamweaver document window, and from the Properties panel change the name of the button to email_submit and change the button value to Send Mail. Have the action of the form submit back to this same page. The form’s method should be post, not get. (get will send the form values as URL parameters.)
5. Add the following code above the tag:
The conditional statement surrounding the ASP script checks to see if the form field named email_submit is empty. Once the form is submitted, this form field (the Submit button) will have a value so the ASP script executes. (Please see Chapter 3 for a review of VBScript syntax.)
6. Test the page live and click the form button to send the e-mail (Figures 5-15 and 5-16).
Figure 5-15. email_frmbutton.asp in a web browser before the Send Mail button is clicked
Figure 5-16. email_frmbutton.asp in a web browser after the Send Mail button is clicked. Notice the querystring.
159
CHAPTER 5 Sending e-mail based on your own conditions is the first step in sending dynamic e-mail. You can also send e-mail based on other conditions, such as an event that might occur within the ASP page. For example, you may want to send yourself an e-mail whenever someone accesses a particular page on your website. Once you understand the concept, it is up to you to determine how to best apply it.
Making e-mail property values dynamic So far, you’ve been sending e-mails with predefined values. The next step is to make the e-mail property values themselves dynamic, and not just the execution. An example where this is useful is when you want users to send e-mail from your website to you or to other users. You might also simply want to collect dynamic values from users. For example, web users could send you feedback from a page on your site, and you could collect their IP address as they send you feedback. Web users can send other web users a link from your website. You will look at these applications in the following sections.
Sending e-mail with dynamic values Let’s now add some dynamic values to your e-mails. In this section, you’ll collect the IP address of the sender of an e-mail and the page the user sent the e-mail from in the body of your e-mail. To do so, first create a new dynamic ASP web page and save it as dynamic_values_in_email.asp. Create the same form as in the previous example and follow these steps:
1. 2. 3. 4.
Select Insert ➤ Form ➤ Form. Place your cursor inside the form and select Insert ➤ Form ➤ Button. For Accessibility Attributes, select no label and click OK. Highlight the button in the Dreamweaver document window, and from the Properties panel change the name of the button to email_submit and change the button’s value to Send Mail. Have the action of the form submit back to this same page. The form’s method should be post, not get.
5. Add the following code above the tag:
6. Test the page live and click the form button to send the e-mail. The code is basically the same as in the previous example, except that you’ve added some dynamic variables into the body of the e-mail. You also changed the value of the redirection page to the new page. To create the body of the e-mail with strings and dynamic variables, you have to concatenate them together. (If you need a refresher on concatenation, see Chapter 3.)
If you leave out a concatenation character, you may break the value, so take care to concatenate the strings and variables together properly.
You collected two environment variables: the IP address and the URL to the current page. The only new code in the body is vbcrlf. This is simply a built-in VBScript string constant that creates a carriage return and line feed. If you want to use HTML tags such as
instead, you have to change the e-mail format to HTML format using the properties described earlier in this chapter. You have now added dynamic variables inside the body of your e-mail. You could add the variables into the Subject line, or you could also retrieve other environment variables. Figure 5-17 shows an example of the e-mail the recipient will see.
Figure 5-17. Text specified in an ASP page as it arrives in an e-mail address’s inbox
161
CHAPTER 5
Sending e-mail with dynamic form field values Now let’s replace entire property values with dynamic variables instead of hard-coding them. Start off by creating a new dynamic ASP web page and saving it as send_email_form.asp. Insert into an empty form three text fields and one text area, to parallel the properties of the CDO properties .To, .From, .Subject, and .TextBody. Rename the text fields and add labels and properties as shown in the following table. Text field
Label
txtsender
Sender Email:
txtrecipient
Recipient Email:
txtsubject
Subject:
txtbody
Body:
Properties
TextArea
Also insert a Submit button, set its value to Send Email, and leave the name of your button as is (Submit). Highlight the form and from the Properties window change the action of the form to be sent back to the same page, making sure the method is set to post. The user will insert the CDO property values through this form (Figure 5-18).
Figure 5-18. send_email_form.asp in a web browser before the form is submitted
The convention is to prefix text field names with txt so that when you retrieve them later you recognize quickly that the names stand for form fields, but you do not always have to do this. Feel free to use whatever convention works for you and makes it easiest for you and others to read the code.
162
WORKING WITH FORMS Switch to Code view and type the following ASP script above the tag. You will be using Request.Form to retrieve the values of the form fields.
You need to retrieve the values of the form fields. As you know from Chapter 3, this is done with Request.Form("textfield_name"). Also recall that in order to trim variables from extra spaces left to the right of the value, you can use the VBScript function Trim, like this: Trim(Request.Form("")) For the From property, you want to retrieve the text field named txtsender, so type txtsender between the double quotes. Follow the same procedure for the rest of the properties. Change the name of the form field to reflect the particular one you want to retrieve for the property value you are defining. Test the page live, enter appropriate values for each form field, and submit the form. The CDO will have executed once your page reloads. Finally, check the e-mail you entered for the recipient e-mail account.
163
CHAPTER 5
Sending a page to a friend From the previous two examples, you’ve learned enough to do a lot of different tricks. It’s just a matter of applying the various concepts to create the web application. Let’s now take a look at a complete “send page to friend” application, in which you’ll apply the techniques outlined previously. You will hard-code some of the property values and allow users to define other property values. You will also use HTML in the body this time. You’ll create a new dynamic ASP web page with a form very similar to the form created in the previous example. The difference here is that you will predefine the subject and body in this example, since that is usually the case with “send page to friend” applications. It isn’t practical to run this example locally, so you will use the CDO code (or the code for the other mail components discussed earlier) for connecting to a remote SMTP server. Upload this page to your remote website so that you can see it used practically. Create a new dynamic page in Dreamweaver, save it as send_page_form, and follow these steps:
1. Create a form with two text fields and a Submit button. 2. Rename the first text field "txtsender", and rename the second text field "txtrecipient". 3. Change the value of the Submit button to "Send" and leave the name of the button as is (Submit).
4. Format your form however you like. Make sure the Action attribute specifies the correct page that will process the form; in this case, it is the same page that contains the form.
5. Load this page in Dreamweaver MX and switch to Code view. Enter the following ASP script above the tag:
Make sure that you change the names within brackets, such as , to reflect your name definitions, both where you need to specify your database columns and server information to trigger e-mails from the SMTP server. The To property is set to the e-mail retrieved from the database record. You then append the database column that stores the password for the record to the body and customize your message. Finally, you redirect and close the If statement with End If. We redirect passing a URL parameter until after the e-mail has been sent successfully. It is possible to easily display a related message once the e-mail has been sent by simply checking for the URL parameter’s existence. Add the following code anywhere in the body of the page you want the message to appear:
Congratulations! Your password has been sent to the e-mail address you registered with. Thanks!.
169
CHAPTER 5 Your forgotten password web application is complete! Test the page live, insert a real username, and the password will be sent to the e-mail stored in the e-mail column for that particular user (Figure 5-21).
Figure 5-21. forgotten_pwd.asp in the web browser before submission
Creating a mailing list Before we end this chapter, let’s create one more web application that involves sending e-mail to users. In this example, you’ll learn how you can send e-mails to your users whenever you need to. The e-mail addresses will be pulled from a recordset, and then you will add the mail component code and have it repeat itself to send the e-mail to each e-mail in the recordset. In the database, you’ve stored the e-mail address for each user in a column in the users table. For this example, you’ll pull e-mails from this table and send the same e-mail to each address in one shot. Create a new dynamic ASP web page, save it as mailing_list.asp, and follow these steps:
1. Create a new connection from the Connections menu and select a table that stores email addresses for your users.
2. Create a recordset called rs_mailinglist_emails. Highlight only the column that contains the email addresses and click OK (Figure 5-22).
Figure 5-22. The rs_mailinglist_emails recordset in Dreamweaver after its customization
170
WORKING WITH FORMS
3. Add a form to your page with two text fields and a button. Call the first text field txtsubject and the second one txtbody. From the Properties window, change the txtbody text field to Multi-line. Change the value of the submit button to Send Mail to All Users.
4. Now switch to Code view and right below the closing tag, insert the mail code. Don’t forget to make sure that you change the names within brackets, such as , to reflect your name definitions.
5. You need to manually change the To property to take the e-mail from the rsMailingListEmails recordset as its value. Change the value of this property to the following: objCDO.To = rs_mailinglist_emails.Fields.Item("").Value
6. Go to Design view, highlight the ASP placeholder that represents the CDO code, and select Server Behaviors ➤ Repeat Region.
171
CHAPTER 5
7. Select the rs_mailinglist_emails recordset from the menu and show all records. Click OK (Figure 5-23).
Figure 5-23. The mailing_list.asp page in the Dreamweaver document window
8. Finally, you need to make sure the ASP script along with the repeat region executes only when the form is submitted. In Code view, find this code at the beginning of the repeat region code block:
Add the following code above the start of the repeat region:
9. Then, in Code view, find the end of the repeat region code:
Add the following code directly after the end of the repeat region code:
172
WORKING WITH FORMS That’s it. When the page is tested live, the recordset will retrieve all the e-mails from the users table. Once the form (Figure 5-24) is submitted, the ASP script will execute, repeatedly going through each e-mail address in the table and sending your message. Finally, it will redirect to the same page and add a URL parameter informing you that the e-mail was sent.
Figure 5-24. The mailing_list.asp page in the web browser before form submission. Input your own values and submit the form to test your mailing list application.
Conclusion In this chapter, you learned how to send e-mails from within your own ASP pages. You looked at how to configure your SMTP server, and then you examined the syntax of three popular ASP mail components, CDO, AspEmail, and JMail, and how each can be used to send static e-mails with predefined values from an ASP page. Then you moved on to cover how to send dynamic e-mails based on conditions, how to change the values of the mail component properties on the fly, and even how to allow users to change those values. Finally, you walked through the creation of two full e-mail applications: one for sending users a forgotten password and the other for creating a mailing list. You should now be able to use the knowledge you gained here to create your own custom e-mail web applications for your website.
173
Chapter 6
BUILDING A RANDOM QUOTE GENERATOR
In this chapter, you’ll build a database table to store quotes in, and then build a simple administration system to allow you to add, edit, and delete those quotes. Your application will use Dreamweaver’s Insert Record, Update Record, and Delete Record server behaviors to enable you to add, edit, and delete records in the database; it will also use the Repeat Region server behavior to help you display multiple records from the database on a page. If you need a little guidance on creating database tables, go back to Chapter 4, which covers this in depth. Otherwise, let’s get going.
175
CHAPTER 6
Creating the quotes database table In Access, create a simple database table called tblQuotes, and use the following field names: Field name
Data type
Settings
ID
Autonumber
Primary Key
CategoryID
Number
Default value = 0
AuthorID
Number
Default value = 0
Quote
Text
Size = 255
This very basic table will enable you to add your quotes to the database while catering for future expansion. In Chapter 7, you’ll expand on this database to include categories and authors, but for now, you don’t need to worry about them. The same database table structure in SQL Server would be defined as follows: Field name
Data type
Settings
ID
Int
Primary Key Identity = Yes Seed = 1 Increment = 1
CategoryID
Int
Allow Nulls = Checked Default value = 0
AuthorID
Int
Allow Nulls = Checked Default value = 0
Quote
Text
Allow Nulls = Unchecked Size = 255
In SQL Server, you would also need to give your SQL Server database user access rights to this table. You would need to grant select, insert, update, and delete permissions to the public role if your user was assigned to the public role in this database. With your database structure in place, it’s time to dive into Dreamweaver and begin building your administration system. If you’re not yet familiar with creating connections to databases in Dreamweaver, please refer to the section titled “Making the connection” in Chapter 4.
176
BUILDING A RANDOM QUOTE GENERATOR Once you’ve created a connection to your database, you can then create the administration pages that will allow you to add, edit, and delete the data.
Building the form To add data to your database, you’ll make use of Dreamweaver’s Insert Record server behavior. First, though, you’ll build a simple form to enable you to add quotes to your database.
A quick word about forms and the ways in which you can submit their information between pages—a form has two methods of submitting its information: GET and POST. Using POST passes all a form’s information to its destination (the form’s ACTION property) in a way that doesn’t allow the user to see it. Using GET passes the information through the querystring of the browser in name/value pairs. When information is passed through the browser’s querystring, there’s a much lower limit to the amount of information that can be passed from one page to the next.
Create a new ASP VBScript page and save it to your site with the name insert.asp (Figure 6-1).
Figure 6-1. Saving insert.asp to your site
Once the page is saved to your site, you can begin working on it. The first step is to add a form to the page. The form will contain a single form element into which you’ll type your quotes, and a Submit button to submit the data to the database.
1. From the Insert bar, select Forms and then click the Form icon to add a form tag to the page in Design view (Figure 6-2). A red dotted outline should appear in the layout area of the web page.
Figure 6-2. The Form icon on the Insert bar
To avoid a bug in Dreamweaver, once the empty form has been added to the page, press the Enter key twice to insert a new paragraph (this will actually insert two sets of empty paragraph tags). Then press the Up arrow key to put the cursor back into the first paragraph before continuing.
177
CHAPTER 6
2. Next, click the Text Field icon next to the Form icon to begin adding a text field to the page. From a default installation of Dreamweaver, this will display the Input Tag Accessibility Attributes dialog box, which you can fill out as shown in Figure 6-3.
Figure 6-3. The Input Tag Accessibility Attributes dialog box
You’ve made use of one of Dreamweaver’s accessibility features here. You don’t have to do this—you can turn them off in Dreamweaver’s Preferences if you don’t want to use these features, but it’s advisable to make use of them whenever possible to make your websites accessible to more people. If you simply want to skip the accessibility dialog at this time, click Cancel, and your form element will be created normally. To turn these items off permanently, choose Edit ➤ Preferences ➤ Accessibility, and deselect the check boxes of those items you don’t want to add accessibility attributes for.
Next, you’ll use the label attribute to label the text field accordingly. You’ll also want to change the name given to this text field by Dreamweaver from textfield1 to something more meaningful, such as Quote.
3. Select the text field in Design view and change the name to Quote in the Property inspector. While you’re there, set Char width to 50 and Max Chars to 255, as shown in Figure 6-4. This makes the text field display at 50 characters wide and allows a maximum of 255 characters to be entered. You’re using 255 for the Max Chars value because that’s the maximum field size you set in the database. If you try to insert more data than the table will allow, the operation will fail.
Figure 6-4. Setting the Quote text field properties
178
BUILDING A RANDOM QUOTE GENERATOR Changing the text field name in the Property inspector will at the same time change the ID that Dreamweaver assigned to the text field for you. Unfortunately, it won’t change the for attribute of the label it inserted for you, so you need to manually change that to match the name you just gave the text field (Quote). To change the for attribute, go into Code view and type the correct name into the attributes value.
4. Now you need to add a Submit button to the form, which you do by clicking the Button icon on the Forms toolbar. Fill out the Input Tag Accessibility Attributes dialog box as before, giving the button a label of Submit, an access key of s, and a tab index of 2. With that last step completed, your very basic form should look like Figure 6-5.
Figure 6-5. The basic Quote submission form
Now you’re ready to add the Insert Record server behavior to the page to make this form work.
The Insert Record server behavior To begin adding the Insert Record server behavior to the page, go to the Application panel and select Server Behaviors ➤ Insert Record. The Insert Record server behavior dialog box pops up for you to fill in. If you haven’t yet created a connection to your database, please see the “Making the connection” section in Chapter 4. Select your connection in the Connection dialog box; when the tables list refreshes, select the table you’re going to insert into. You’ll be inserting a quote into the quotes table with this form, so select tblQuotes. You can leave the After inserting, go to field empty. This will force the page to simply reload after an insertion has taken place. To redirect elsewhere after the insertion takes place, you would supply a page name here, along with any parameters that you may need. We’ll return to this later in this chapter in the “Adding conditional code” section. The rest of the dialog box should already be completed appropriately. The Get values from drop-down list should display form1, unless you happen to have renamed your form from the default. The Form elements box should be a single-item list, as you have only one form element on your form. The text entered into the Quote text field is therefore inserted into the Quote column as Text.
179
CHAPTER 6 Your completed dialog box should look something like Figure 6-6.
Figure 6-6. The completed Insert Record dialog box
Click OK to apply the Insert Record server behavior to the page and then save the page. You can now perform a test of your new insert page by previewing the page (press F12 in Dreamweaver). When the page loads, enter a quote into the Quote field and then click Submit. The page will very quickly submit and reload. If you blink, you’ll miss it and think nothing has happened— this is why it’s always a good idea to add a little feedback to a form like this, so you know what’s happening when you click buttons.
If you’re stuck for ideas for quotes, check out www.brainyquote.com, which has some great ones.
Adding conditional code To provide feedback, you’ll need to modify your Insert Record server behavior and then add a little code into the page to conditionally display some text. First, double-click the Insert Record entry in the Server Behaviors panel to edit it. When the dialog box appears, enter the following code into the After inserting, go to field: insert.asp?added=yes. insert.asp is the name of your insert page. With the preceding code, you’re telling the server to return to this same page and also add the name/value parameter pair of added=yes. Your conditional code will check for the added parameter to see if its value is equal to yes, and display some text if it is. Click OK to apply the changes to your page. Switch views to Code view if you’re in Design view, and place your cursor immediately to the left of the opening paragraph tag in the form. Switch back to Design view and press Enter to insert an empty paragraph tag above the Quote field and label.
180
BUILDING A RANDOM QUOTE GENERATOR In this new empty paragraph, enter the following text: Your quote has been added to the database. You’ll now wrap this entire paragraph in some conditional code to make sure it displays only after an insert has taken place. Switch into Code view and add the following code before the opening paragraph tag of the conditional text:
Then add the following code after the closing paragraph tag:
Your final piece of code for this segment of the page should look like the following:
Your quote has been added to the database
tag on the Tag Chooser at the bottom of the Design view window (see Figure 6-10).
Figure 6-10. The Tag Chooser with a paragraph tag selected
You can make doubly sure that the entire paragraph has been selected by switching into Code view and ensuring that the highlighted selection is correct. Switch back to Design view when you’re happy! In the Application panel, choose Server Behaviors ➤ Repeat Region. This will launch the Repeat Region server behavior dialog box. The rsQuotes recordset should be automatically selected for you. If it’s not, select it in the list. Then set the Show option to All. The completed dialog box should look like Figure 6-11.
Figure 6-11. The completed Repeat Region dialog box
Click OK to apply the server behavior to the page. Your Design view will change to show an outline around the databound area with a tab above it labeled Repeat.
183
CHAPTER 6 At this stage, you can preview your page to see the repeat region in action. If you have any quotes stored in your database already, they will all be displayed on this page now. The next step is to make each quote into a link that goes to an edit page to allow you to edit the selected quote. In Design view, click the databound element on the page {rsQuotes:Quote} and go to the Properties dialog box at the bottom of the screen. Click the folder icon to the right of the Link field (Figure 6-12) to launch the Select File dialog box.
Figure 6-12. The folder icon to the far right of the Link field
The file you’ll link to doesn’t yet exist, so you can’t simply click to select it. Instead, type the file name that you’ll use to create your edit quote page (editquote.asp) in the File name field. The editquote.asp page will allow you to edit a single quote. To do this, it will need to know which quote you want to edit. You tell editquote.asp this by passing it the ID of the quote you want to edit as a parameter. To set that parameter in your link, click the Parameters button next to the URL field. In the Name column of the Parameters dialog box, enter the name ID and set its value to the ID column of your rsQuotes recordset by clicking the lightning bolt icon at the end of the field. (The lightning bolt icon is visible only when the value field has focus, so click inside it first). This will launch the Dynamic Data dialog box, in which you can select the ID column of the rsQuotes recordset (Figure 6-13).
Figure 6-13. Selecting the ID column in the Dynamic Data dialog box
184
BUILDING A RANDOM QUOTE GENERATOR Click OK to return that selected value to the Parameters dialog box. The completed Parameters dialog box should look like Figure 6-14.
Figure 6-14. The completed Parameters dialog box
Click OK to return that data to the Select File dialog box that you initially began with. The completed URL, which you’ve been using Dreamweaver’s dialog boxes to populate, will contain the following data: editquote.asp?ID= This is the link that has been created. Click OK to apply this code to the page. You can check that the code has been applied correctly by clicking the databound element on the page—{rsQuotes:Quote}— which is now a link, and checking the code in the Link element of the Properties dialog box. Once you’ve saved your page, you can now preview it to see the full effect. Each of your quotes is now a link on the page; if you watch the status bar of your web browser while rolling over each of them in turn, you’ll notice that the value of the ID parameter of each link is different. Figure 6-15 shows how the completed page looks in a web browser.
Figure 6-15. The completed Quotes page, so far . . .
With this page complete, you now need to create the page that all these links link to: editquote.asp.
185
CHAPTER 6
The Update Record server behavior The Update Record server behavior will enable you to update the contents of each quote in your database individually. You’ve already created a page that lists all the quotes in your database. Each one links to the editquote.asp page and passes it a unique ID that identifies a single record in the database to be updated. Since editquote.asp needs to utilize the exact same form elements as the insert.asp page you created earlier, you’ll use that page as a starting point. Open the insert.asp file and then use Save As to save it as a new page called editquote.asp.
Figure 6-16. Selecting the Insert Record server behavior before removing it from the page
The first thing to do is to remove the Insert Record server behavior from this page. So, in the Application panel under the Server Behaviors tab, click the Insert Record entry, and then click the minus button above it to remove the entry from the page (as shown in Figure 6-16). This is the best way to remove a server behavior from the page, as it ensures that all the code relevant to that server behavior is removed. Manually deleting code may leave fragments of code on the page, which may cause problems.
In order to edit a record, you need to retrieve that record from the database. To do that, you’ll build a recordset that will automatically return the record you want to edit. Your allquotes.asp page, which lists all the quotes in the database and links each one to this page, uses the ID of each quote as a parameter for you to uniquely identify it. You’ll use this parameter when you build your recordset to retrieve that single record from the database. You can launch the Recordset dialog box from the Server Behaviors panel (as well as the Bindings panel). To launch it from the Server Behaviors panel, choose Server Behaviors ➤ Recordset (Query).
1. 2. 3. 4. 5. 6. 7. 8. 9.
186
In the Recordset dialog box, enter the name of your recordset as rsQuotes. Select your database connection from the Connection drop-down list. Select tblQuotes from the Table drop-down list. Check the Selected radio button and highlight the ID and Quote columns in the Columns list. Select ID in the Filter drop-down list, and leave = selected in the list next to it. Select URL Parameter in the next list (it’s selected by default). Enter ID in the field next to that (it’s entered by default). Leave Sort as None—you’re only retrieving a single record, so you don’t need to sort anything! Click OK to create the recordset.
BUILDING A RANDOM QUOTE GENERATOR Your completed Recordset dialog box should look like Figure 6-17.
Figure 6-17. The completed Recordset dialog box
Click the Quote text field in Design view to select it, and then switch to the Bindings panel and expand the recordset so you can see the columns that have been retrieved in this recordset. Click to select the Quote column, and bind it to the Quote form element by clicking the Bind button at the bottom of the Bindings panel. Now you need to add the Update Record server behavior to the page. Click Server Behaviors ➤ Update Record. The Update Record dialog box will appear.
1. 2. 3. 4. 5. 6.
Select your connection from the Connection drop-down list. Select tblQuotes from the Table drop-down list. Select rsQuotes from the Select record from drop-down list. Select ID from the Unique key column drop-down list. Enter editquote.asp?edited=yes in the After updating, go to field. Make sure that form1 is selected in the Get values from field, and that the Quote form element is submitting to the Quote column as a Text data type.
7. When your dialog box is complete, click OK to apply the server behavior to the page.
187
CHAPTER 6 Your completed Update Record dialog box should look like Figure 6-18.
Figure 6-18. The completed Update Record server behavior dialog box
There are only a couple of small changes left to make, and this page will be complete. You need to change the conditional text to something more appropriate, and you also need to change the condition that it relies upon. In Design view, change the text that reads Your quote has been added to the database to Your quote has been updated. If you noticed in step 5 when filling out the Update Record server behavior, you entered the name of this page followed by the parameter name/value pair of edited=yes. Switch to Code view and locate the following conditional statement: If Request.QueryString("added") = "yes" Then Change it to the following: If Request.QueryString("edited") = "yes" Then The final thing you need to do is add a link on this page that links back to the allquotes.asp page. In Design view, place the cursor after the Submit button and press Enter to start a new paragraph. Type Back to the quotes list as the link text. Then select the entire paragraph and make it a link in the Property inspector by clicking the Point to File icon (Figure 6-19) and dragging it to the allquotes.asp page in the Files panel. A line will stretch from the icon to the mouse while you click and drag; when you let go, the file you’re pointing at will be the file you’ll have created a link to. Check that Figure 6-19. The Point to File icon, which looks like a allquotes.asp is entered in the Link field. bullseye
188
BUILDING A RANDOM QUOTE GENERATOR Save your page and test it now. If you preview the editquote.asp page directly, it will always load and make the first quote from your database available for editing—this is a feature of the Simple Recordset builder. It has automatically added a default value for the ID parameter to the code for this page; if an ID value is not provided, it will use the default value of 1. If you start your testing by previewing the allquotes.asp page, you can click a quote to edit it. You can then edit the selected quote and click Submit to save the changes. The edit page will refresh to tell you that the quote has been updated (see Figure 6-20). You can then click the link to go back to the allquotes.asp page and start again on another quote.
Figure 6-20. The updated Insert Quote page
Now you have a system that allows you to easily add and edit quotes in the database. What you need to complete this simple admin system is a facility to delete records that you no longer want in the database.
The Delete Record server behavior For now, the last page you’ll create in this simple admin system will be the delete.asp page. You’ll also need to make another simple addition to the allquotes.asp page that will create a link to the delete.asp page and delete a selected record. The Delete Record server behavior needs a recordset and a form on the page in order for it to be used. The easiest way to build the delete.asp page is to make a copy of the editquote.asp page and use that as a starting point, and then remove the bits on that page that you don’t need.
1. Open editquote.asp and save it to your site as delete.asp. 2. Remove the Update Record server behavior by selecting it in the Server Behaviors panel and clicking the minus (-) button.
3. Highlight the conditional text in Design view, including the two ASP shields above and below the text, and press the Delete key to delete it.
189
CHAPTER 6 With that done, you can start to add in the code you need to make this page delete quotes. The page you’re using as the starting point for this delete page, editquote.asp, already contains the recordset that will allow you to successfully run the delete command. It will automatically filter the database to a specific record based on the ID that will be passed from the allquotes.asp page, and display it to you in the form field. Click Server Behaviors ➤ Delete Record to launch the Delete Record dialog box.
1. Select your connection from the Connection drop-down list. 2. Select tblQuotes from the Delete from table drop-down list. 3. Select the ID column in the Unique key column drop-down list, and ensure that Numeric is checked.
4. Select form1 (it’s selected by default) in the Delete by submitting drop-down list. 5. Enter allquotes.asp in the After deleting, go to field. 6. Click OK to apply the server behavior to the page. Your completed Delete Record dialog box should look like Figure 6-21.
Figure 6-21. The completed Delete Record server behavior dialog box
Change the Submit button label—the text next to the button on the page in Design view—from Submit to Delete, and also change the value of the button itself. To do this, click the button to select it, and then go to the Property inspector and replace the value Submit with Delete. Your delete.asp page is now completed, so save it to your site and close it for now. When this page is accessed, the selected quote will be displayed in the Quote form element, and it will be deleted from the database if the Delete button is clicked. You left the link back to the allquotes.asp page there in case you get to the delete.asp page and decide not to delete the quote after all. You now need to add another link to the allquotes.asp page that will link to the delete.asp page, and pass it the ID parameter so it knows which quote to delete.
190
BUILDING A RANDOM QUOTE GENERATOR Open the allquotes.asp page and place the cursor after the end of the databound value— {rsQuotes.Quote}—inside the repeat region in Design view. Enter a space and then type the word Delete. You’ll now use the Property inspector to make this link to the delete.asp page and pass it the ID parameter with the correct value.
1. 2. 3. 4.
Highlight the word Delete, and in the Property inspector click the Browse for file icon. In the Select File dialog box, click delete.asp in the list of files. Click the Parameters button to launch the Parameters dialog box. Click the plus (+) button to add a row to the list in the Parameters dialog box, and then enter ID in the Name column.
5. Click in the Value column, and then click the lightning bolt icon to bring up the Dynamic Data dialog box.
6. Click the ID field under the rsQuotes recordset to select it, and click OK. 7. Click OK to close the Parameters dialog box. 8. Click OK again to close the Select File dialog box. Your newly created dynamic link will now populate the Link field in the Property inspector (see Figure 6-22).
Figure 6-22. The completed Link field in the Property inspector
You can now save and preview this completed page (see Figure 6-23).
Figure 6-23. The updated Quotes page, complete with Delete links
191
CHAPTER 6 When you browse the allquotes.asp page, you’ll see that each quote has a Delete link at the end of it, which, when clicked, will take you to the delete.asp page and offer you the chance to delete the selected quote (see Figure 6-24).
Figure 6-24. The Delete page
Conclusion In this chapter, you‘ve learned how to use Dreamweaver’s Insert Record, Update Record, and Delete Record server behaviors by building a simple administration system that adds, edits, and deletes quotes from a single-table database. You’ve built a page to list all the quotes in the database, utilizing the Repeat Region server behavior, and you’ve created dynamic links to move from this page to edit and delete pages on which those relevant actions could take place. In the next chapter, you’ll extend this simple system to include multiple tables. This will allow you to utilize categories and authors for the database of quotes. You’ll then move on to building a page that randomly retrieves and displays a quote from the database.
192
Chapter 7
COMPLETING THE QUOTES ADMINISTRATION SYSTEM
In the last chapter, you built a simple quotes administration system that used a single database table to store quotes and a set of ASP pages to administer that data through Add, Edit, and Delete actions, through the use of Insert Record, Update Record, and Delete Record server behaviors. In this chapter you’ll pick up where you left off in the previous chapter and add two more tables to the database to allow you to categorize the quotes and to see who actually said (or authored) them. You’ll make use of foreign keys in the database, and you’ll create a query that uses the JOIN keyword to gather together data from multiple tables into a single query. From that query, you’ll retrieve a random quote and display it on a web page. You’ll also update the administration pages we built in the previous chapter to incorporate categories and authors. All files can be downloaded from www.friendsofed.com.
195
CHAPTER 7
Updating the quotes database table First, to recap what you’ve done so far, open the existing Access database created in Chapter 6, and then open tblQuotes. The structure of tblQuotes is as follows: Field name
Data type
Settings
ID
Autonumber
Primary Key
CategoryID
Number
Default value = 0
AuthorID
Number
Default value = 0
Quote
Text
Size = 255
This simple structure allows you to add quotes to the database, and it also has room to enable you to include categories and authors. These two columns, CategoryID and AuthorID, are foreign keys. They will reference the primary keys of two new tables that you’re about to create. The structure of the tblQuotes table in SQL Server is as follows: Field name
Data type
Settings
ID
Int
Primary Key Identity = Yes Seed = 1 Increment = 1
CategoryID
Int
Allow Nulls = Checked Default value = 0
AuthorID
Int
Allow Nulls = Checked Default value = 0
Quote
Text
Allow Nulls = Unchecked Size = 255
Now you need to create two new tables: one to store the quote categories and another to store the quote authors. These are both very simple two-column tables. Create each table as described here and save it with the name shown (tblCategories and tblAuthors, respectively).
196
COMPLETING THE QUOTES ADMINISTRATION SYSTEM The tblCategories table structure is as follows: Field name
Data type
Settings
CategoryID
Autonumber
Primary Key
Category
Text
Size = 255
The tblAuthors table structure is as follows: Field name
Data type
Settings
AuthorID
Autonumber
Primary Key
Author
Text
Size = 255
Very simple! Next, we need to create the relationship between these two tables and the main quotes table. In Access, you’ll use the relationship management tool. You can launch this tool by clicking the Relationships icon, as shown in Figure 7-1.
For a thorough grounding in how to create relationships in Access, please refer to the section “Creating a relationship in Access” in Chapter 4.
Figure 7-1. The Relationships icon in Access 2003
This immediately displays the Show Table dialog box, from which you can choose the tables you want to create a relationship between. You’re going to create a relationship between the main table, tblQuotes, and your other two tables, tblCategories and tblAuthors (Figure 7-2).
Figure 7-2. The Show Table dialog box
197
CHAPTER 7 Select tblQuotes, tblCategories, and tblAuthors in the list by clicking each one while holding down the Ctrl key. Alternatively, with the top option selected, hold down the Shift key and select the bottom option in the list to select all items in between. Then click Add. You can also simply double-click each item in turn to add them to the relationships canvas. Once all three tables have been added to the canvas, click the Close button on the Show Table dialog to continue. With the tables added to the canvas, click and drag the AuthorID column in tblAuthors to the AuthorID column in tblQuotes. When you release the mouse button, the Edit Relationships dialog appears (Figure 7-3). It shows the columns you want to relate to each other, and you can specify the relationship type that should be used.
Figure 7-3. The Edit Relationships dialog box
By default, the Relationship Type in this dialog is One-To-Many, which is great, because that’s the type of relationship you want to create. A many-to-many relationship type would require multiple related records in both tables, whereas one record in the tblAuthors table can be referenced by many individual records in the tblQuotes table using this one-to-many relationship type. You also have the option of enforcing referential integrity on these database objects. To briefly recap the concept, if you tell the database that you want to use referential integrity, and you select the option to Cascade Delete Related Records, for example, then if you delete an author from the tblAuthors table, all of that author’s quotes in the tblQuotes table will be deleted, too.
Referential integrity is covered in depth in Chapter 4 in the section “Relational databases and referential integrity.”
For this little project, you won’t be using this feature, so simply click Create to create the one-to-many relationship and close the dialog. Next, you’ll create the same relationship between tblCategories and tblQuotes. Drag CategoryID from tblCategories and drop it over CategoryID in tblQuotes. Then click Create in the Edit Relationships dialog. Your completed Relationships canvas should look like Figure 7-4.
198
COMPLETING THE QUOTES ADMINISTRATION SYSTEM
Figure 7-4. The completed Relationships dialog
We moved tblCategories to the right of tblQuotes to make it easier to see the relationship lines between all tables. This does not affect the relationships we created.
You can now save and close the relationships editor window. Click File ➤ Save or click the Save icon (floppy disk) on the toolbar to save the relationships. Alternatively, you’ll be prompted to save the relationships if you simply close the Relationships window. With the database structure in place, it’s time to dive into Dreamweaver and begin updating the administration system.
Author administration To specify the author of each quote in the database, you need to have a list of authors. One way to achieve this is to create a system similar to the quotes administration system so that you could add, edit, and delete the author names in the database. However, to keep this system simple and get to the end result faster, you’ll just build a single page that will allow you to add an author name to the database.
Building the Insert Author page Open the insert.asp page created in the previous chapter and save it as insertauthor.asp by right-clicking the page tab and selecting Save As from the context menu that appears (Figure 7-5). Now you simply need to change anything that references “quote” to reference “author” instead. First, change the text you can see in Design view from Your quote has been added to the database to Your author has been added to the database
Figure 7-5. Using the Save As context menu option after right-clicking the page tab
199
CHAPTER 7 Also, change the label for the text field from Quote to Author. Click the text field to select it and then, in the Property inspector, change the name of the text field from Quote to Author. With the text field still selected, switch to Code view and change the for attribute of the label tag from Quote to Author. Dreamweaver should do this for us, but it doesn’t! The last change you need to make is to the Insert Record server behavior. Select Application ➤ Server Behaviors and you’ll see that the Insert Record server behavior has a red exclamation point next to it (Figure 7-6). This is because it’s looking for a element on the web page called Quote, but we’ve changed the element’s name to Author, so it can’t find the element anymore!
Figure 7-6. The exclamation point tells you that Dreamweaver has a problem with the code at the moment.
To remedy this situation, double-click the Insert Record server behavior to edit its properties. Click OK to get past the alert telling you that the server behavior can’t find the form field called Quote. Select tblAuthors from the Insert into table drop-down menu, and the dialog automatically updates itself to show that the Authors field will insert into the Author column as a data type of Text. Finally, change the After inserting, go to field so that it returns you to this insertauthor.asp page. Change insert.asp to insertauthor.asp and leave the parameters in place (Figure 7-7).
Figure 7-7. The updated Insert Record dialog
Click OK to apply the changes and then save the page. If you now test the page in your web browser and submit a new author name to the database, the page will refresh to tell you that the new author was successfully added to the database (Figure 7-8).
200
COMPLETING THE QUOTES ADMINISTRATION SYSTEM
Figure 7-8. The working page after an author has been added to the database
For the sake of brevity, you won’t produce a complete system to add, edit, and delete authors in this book. However, using the lessons from earlier in this chapter, you could quite easily do this yourself to better manage the data in the authors database table. Alternatively, you could download these edit and delete files from www.friendsofed.com.
Next, you’ll create the same page to allow you to add categories to the database.
Category administration To specify the category of each quote in the database, you need to have a list of categories. As with the authors administration page, you’ll just build a single page to allow you to add a category to the database.
Building the Insert Category page Open the insertauthor.asp page just created and save it as insertcategory.asp. You’ll need to make the same changes to this page that you just made to the Authors page. First, change the text on the page in Design view from Your author has been added to the database to Your category has been added to the database Change the label for the text field from Author to Category. Click the text field to select it and then, in the Property inspector, change the name of the text field from Author to Category. Don’t forget to switch to Code view and change the for attribute of the label tag from Author to Category, too.
201
CHAPTER 7 Finally, you need to update the Insert Record server behavior. Click Application ➤ Server Behaviors and double-click the Insert Record entry in the list. Click OK to get past the alert telling you that the server behavior can’t find the form field called Author. Select tblCategories from the Insert into table drop-down menu. The dialog automatically updates itself to show that the Category field will insert into the Category column as a data type of Text. Finally, change the After inserting, go to field so that it returns you to this insertcategory.asp page. Change insertauthor.asp to insertcategory.asp and leave the parameters in place (Figure 7-9).
Figure 7-9. Updating the Insert Record dialog to insert a category
Click OK to apply the changes and then save the page. If you now test the page in your web browser and submit a new category to the database, the page will refresh to tell you that the new category was successfully added to the database (Figure 7-10).
Figure 7-10. The Insert Category page after a category has been added to the database
Now you need to add these extra database fields, Author and Category, to the main quote administration page to make full use of them.
202
COMPLETING THE QUOTES ADMINISTRATION SYSTEM
Updating the Insert Quote page To specify each quote’s author and category when you add quotes to the database, you need to amend the insert.asp page. You’ll add two drop-down menus to the page, one for authors and one for categories, which will be populated by recordsets that pull data from the database. Once the recordsets are created, you can bind them to select lists on the page and, finally, update the Insert server behavior to make use of the new elements.
Creating the recordsets Open the insert.asp page created previously. First, you’ll create the two recordsets, Authors and Categories, that you need.
Building the Authors recordset The Authors recordset will draw its data from the tblAuthors table and won’t use any filters, as you want to include all the authors from the database. Here’s how to create it:
1. In the Application panel, click Bindings ➤ Recordset (Query) to launch the Recordset builder dialog.
2. In the Recordset dialog, enter rsAuthors in the Name field, select your connection to the database in the Connection drop-down menu, and then make sure tblAuthors is selected in the Table drop-down menu (Figure 7-11). Make sure the All radio button next to Columns is selected—this is the default, so it should be selected already. Leave Filter set to None, as you don’t want to filter out any records. You’ll apply a Sort to the recordset to make it easy to locate an author when using the page later, so select Author from the Sort drop-down menu and leave Ascending selected as the sort order. This will retrieve all the authors in alphabetical order.
Figure 7-11. The recordset to retrieve all authors in alphabetical order
3. That’s all you need to do for this recordset, so click OK to create it and close the Recordset dialog.
203
CHAPTER 7
Building the Categories recordset Your insert.asp page should now have the rsAuthors recordset listed in the Bindings panel. You just need to add the Categories recordset now, as follows:
1. Launch the Recordset dialog again by selecting Bindings ➤ Recordset (Query). 2. Enter rsCategories in the Name field, select your connection to the database in the Connection drop-down menu, and make sure tblCategories is selected in the Table drop-down menu (Figure 7-12). Again, you want to retrieve all columns, so leave the All radio button selected. Also, you want to retrieve the categories in alphabetical order for ease of use when using the page later, so select Category in the Sort drop-down menu and leave Ascending selected as the sort order.
Figure 7-12. The rsCategories recordset being built
3. Click OK to create the recordset and close the Recordset dialog.
Building dynamic select lists Click in Design view to place the cursor after the closing ASP shield of the conditional code, just before the label for the quote element, and press Enter to insert a new paragraph above that quote element. In this new paragraph, insert a new list/menu element either by clicking the List/Menu icon in the Insert bar (Figure 7-13) or by selecting Insert ➤ Form ➤ List/Menu. This will add a blank drop-down menu to your Design view page. In Code view, this is defined as a select list. Figure 7-13. The List/Menu button on the Insert bar in the Forms category
The Input Tag Accessibility Attributes dialog will open, unless you have turned it off in your preferences—but you didn’t do that, did you?
Enter Author as the Label for this list/menu item and choose to Attach label tag using ‘for’ attribute. Enter a in the Access key field and 1 in the Tab Index field, and then click OK to add this element to
204
COMPLETING THE QUOTES ADMINISTRATION SYSTEM the page (Figure 7-14). You will need to go through the elements in Code view to change each of the element’s respective Tab Index values so that they are sequential. This will allow you to use the Tab key to navigate this form; each press of the Tab key will move you to the next numbered form element in ascending order.
Figure 7-14. Specifying how this list/menu item should be added to the page in the Input Tag Accessibility Attributes dialog
Although Dreamweaver’s simplistic naming conventions will make this code work, we suggest giving elements names and ids that make sense to you, so that when you return to the code later on (perhaps to debug a problem), you can immediately make sense of all the elements. When you insert the list/menu item, Dreamweaver gives it an id that starts with select and, if it’s not the first of its kind on the page, appends a sequential number to it.
The new list/menu item was just given a name and id attribute of select; the for attribute of the tag was given the same value. Switch into Code view and change these three items to Author. Your updated code should look like this: Author
Now switch back to Design view, click the canvas after the Author drop-down menu, and press Enter to insert another new paragraph between the Author drop-down menu and the quote text field. In this new paragraph, insert another new list/menu element by selecting Insert ➤ Forms ➤ List/Menu. In the Input Tag Accessibility Attributes dialog, enter Category as the Label and choose to Attach label tag using ‘for’ attribute. Enter c in the Access key field and a 2 in the Tab Index field, and then click OK to add this element to the page.
205
CHAPTER 7 The new list/menu item was given a name and id of select; the for attribute of the label tag was given the same value. Switch into Code view and change these three items to Category. Your code should look like this: Category
With the select lists added to the page, you can now bind the recordset data to them, as follows:
1. In Design view, click the Author select list to select it. 2. In the Property inspector, click the Dynamic button (see Figure 7-15).
3. In the Dynamic List/Menu dialog that appears, the author element will already be selected in the Menu dropdown. If it is not for some reason, make sure you select it before continuing.
4. The next section of the dialog allows you to specify Static
Figure 7-15. The Dynamic button in the Property inspector when a list/menu is selected
options, or items that will appear in the Author drop-down menu that do not come from the database. You’ll add a Please select static option, as it is often seen in drop-down menus like this. Click the + button to add a row to the grid of Static options. You don’t need a value associated with this static option, so click in the Value column to highlight the word “value” and then delete it. Click in the Label column and type Please select. Clicking anywhere in the dialog (that isn’t a button) or pressing Enter will apply your changes to the Static options list without closing the dialog. The Static options row you just entered will turn blue to show that it is saved in the list.
5. Select the rsAuthors recordset from the Options from recordset drop-down menu, choose AuthorID from the Values drop-down menu, and choose Author from the Labels drop-down menu (Figure 7-16).
Figure 7-16. Building a data-driven Author drop-down menu
206
COMPLETING THE QUOTES ADMINISTRATION SYSTEM
6. You don’t need to specify a value to select in the list on this page—you’ll do that later on the editquote.asp page, so click OK to apply the code to the page. You need to follow the same steps for the Category drop-down menu, except that you’ll use information relevant to categories instead of authors:
1. 2. 3. 4.
In Design view, click the Category drop-down menu to select it. In the Property inspector, click the Dynamic button. The category element should be selected in the Menu field. If it isn’t, select it now. Add a Please select static option to the dialog as outlined in step 4 of the preceding instructions for creating the Authors drop-down menu.
5. From the Options from recordset drop-down, select rsCategories, and then select CategoryID from the Values list and Category from the Labels list (Figure 7-17).
Figure 7-17. Building a data-driven Category drop-down menu
6. Again, you don’t need to specify a value to select in the list, so click OK to close the Dynamic List/Menu dialog and add the dynamic drop-down code to your page.
Updating the Insert server behavior Now that your dynamic drop-down menus are in place, all you need to do to complete this page is update the Insert server behavior to include these two new items: Author and Category.
1. In the Application panel, click Server Behaviors and then double-click the Insert Record server behavior to begin editing it.
2. In the Form elements section of the dialog, click Author to select it if it is not already selected by default. Then choose AuthorID from the Column drop-down menu. Leave Numeric selected in the Submit as drop-down menu.
207
CHAPTER 7
3. In the Form elements section again, click Category to select it if it is not already selected by default. Then choose CategoryID from the Column drop-down menu and leave Numeric selected in the Submit as drop-down menu (Figure 7-18).
Figure 7-18. The updated Insert Record dialog to add an author and a category, along with the quote itself
4. Click OK to apply the changes to the page. This page is now complete, so save your page but leave it open in Dreamweaver for the moment. Next, you need to make similar changes to the editquote.asp page that you just made to this insert.asp page.
Updating the edit page So far, the editquote.asp page allows you to only edit the actual quote text and nothing else. Now that you have a system to add authors and categories into the database, and to assign an author and a category to each quote that you add, and the database has been set up to relate those records from the authors table and from the categories table to the quotes table, you can make full use of the extra data in the database and complete the administration system. In this section, you’ll add two dynamic drop-down menus to the editquote.asp page in the same way you did for the insert.asp page, but on the editquote.asp page you’ll make them automatically select the correct current author and category assigned to the quote, if any.
Copying recordsets You can save yourself some time by copying work you’ve already done instead of repeating the same steps each time:
208
COMPLETING THE QUOTES ADMINISTRATION SYSTEM
1. Open the editquote.asp page so that it’s ready to accept the recordsets you’re about to copy from the insert.asp page.
2. If you closed the insert.asp page previously, open it now; otherwise, click the insert.asp page tab in Design view (Figure 7-19).
3. Select Application ➤ Bindings to show the recordsets, and then
Figure 7-19. The page links, with the editquote.asp tab currently in focus
click rsAuthors to select it. You can either right-click the recordset and then choose Copy from the context menu (Figure 7-20), or you can use the standard Windows keyboard shortcut of Ctrl+C to copy it.
Figure 7-20. The context menu after a recordset is right-clicked in the Bindings panel
4. You have a few ways to paste this recordset into the Bindings panel of the editquote.asp page, including the keyboard shortcut method of pressing Ctrl+V, or by right-clicking in the white area of the Bindings panel and selecting the Paste option. A third option is clicking the menu icon in the blue Application panel bar and choosing Paste from that menu (Figure 7-21).
Figure 7-21. Pasting the recordset using the panel group menu option (instead of the right-click context menu)
5. Click the editquote.asp page tab to focus that page, and then paste the rsAuthors recordset using your preferred method.
6. Switch back to insert.asp, copy the rsCategories recordset, and then paste that recordset into editquote.asp.
209
CHAPTER 7
Adding authors and categories to the edit page Adding dynamic drop-down menus to a page in Dreamweaver is quite easy. Now that you’ve copied the recordsets from insert.asp to retrieve the list data from the database, all you need to do is use one of Dreamweaver’s built-in wizards to set the list to behave the way you want. You’ll add dynamic drop-downs in much the same way you added the list/menu items for Author and Category to the insert.asp page:
1. Place the cursor after the closing ASP shield of the conditional code, just before the label for the quote element, and press Enter to insert a new paragraph above it.
2. In this new paragraph, insert a new list/menu element. When the Input Tag Accessibility Attributes dialog opens, enter Author as the Label and choose to Attach label tag using ‘for’ attribute. Enter a in the Access key field and a 1 in the Tab Index field, and then click OK to add this element to the page.
3. Once again, your new list/menu item is given a name and an id attribute of select; the for attribute of the tag was given the same value. Switch into Code view and change these three items to Author. Your updated code should look like this: Author
4. Switch back to Design view and click the canvas after the Author drop-down menu. Press Enter to insert another new paragraph between the Author drop-down menu and the quote text field.
5. Insert another new list/menu element, and in the Input Tag Accessibility Attributes dialog, enter Category as the Label and choose to Attach label tag using ‘for’ attribute. Enter c in the Access key field and 2 in the Tab Index field, and then click OK to add this element to the page.
6. Again, your new list/menu was given a name and an id attribute of select; the for attribute of the tag was given the same value. Switch to Code view and change these three items to Category. Your code should look like this: Category
Don’t forget to update the other form elements’ tabindex values so that they are all sequential and none are repeated. Otherwise they won’t work as you expect!
Next, you’ll move on to the dynamic data side of things on this page.
210
COMPLETING THE QUOTES ADMINISTRATION SYSTEM
Updating the Quotes recordset You need to make one small but significant change to the rsQuotes recordset. You now need to retrieve the extra columns for AuthorID and CategoryID to be able to modify that data on your form.
1. Double-click the rsQuotes recordset in the Bindings panel, and it will open up in the Recordset dialog.
2. You need to choose to retrieve All columns instead of Selected as you had previously (Figure 7-22). Everything else on this dialog can stay unchanged.
Figure 7-22. Updating the rsQuotes recordset to retrieve only a specific quote based on the URL parameter
3. Click OK to save those changes to the recordset, and then save your page.
Binding dynamic select lists with a selected item You now have all the elements in place on this page. All that’s left to do is to bind the data to the drop-down menus and make them work.
1. In Design view, click the Author drop-down menu to select it. 2. In the Property inspector, click the Dynamic button. 3. In the Dynamic List/Menu dialog that appears, the author element will already be selected in the Menu drop-down menu. If it isn’t selected for some reason, make sure you select it before continuing.
4. You’ll add a Please select static option to the list as per the insert.asp page. Click the + button to add a row to the grid of Static options. Click in the Value column to highlight the word “value” and delete it. Then click in the Label column and type Please select. Next, select the rsAuthors recordset in the Options from recordset drop-down menu, choose AuthorID in the Values drop-down menu, and choose Author in the Labels drop-down menu.
211
CHAPTER 7 You want this list to automatically select the value stored in the database for the quote being edited, if such a value exists. To do this, you need to tell the list to look out for a specific value when it populates the Author drop-down menu values from the rsAuthors recordset and, if it finds the value you specify, mark it as selected in the list. Of course, you need to tell it to look out for a dynamic value—one that will change each time—so you can’t simply type a static value into the field. Instead, you’ll specify a value from the rsQuotes recordset.
5. To do this, click the lightning bolt icon at the end of the Select value equal to field to launch the Dynamic Data dialog.
6. Expand the rsQuotes recordset and click AuthorID to select that column (Figure 7-23).
7. You will see the relevant code written automatically in the Code field at the bottom of the dialog.
8. Click OK to close this dialog and apply this dynamic code to the previous dialog. The code that was generated for you will now appear in the Select value equal to field.
Figure 7-23. Selecting which column holds the AuthorID value that will be marked as selected in the drop-down menu
This Dynamic List/Menu dialog is now complete and should look like Figure 7-24.
Figure 7-24. Adding the code required to mark the correct author as selected in the Author drop-down menu
Click OK to apply the code to the page, then save the page. You need to follow the same steps for the Category drop-down menu, except that you will use information relevant to categories instead of authors:
212
COMPLETING THE QUOTES ADMINISTRATION SYSTEM
1. 2. 3. 4.
In Design view, click the Category drop-down menu to select it. In the Property inspector, click the Dynamic button. The category form element should be selected in the Menu field. If it isn’t, select it now. Add a Please select static option to the dialog as outlined in step 4 of the previous set of instructions. From the Options from recordset drop-down, select rsCategories, and then select CategoryID from the Values list and Category from the Labels list.
5. Click the lightning bolt icon next to the Select value equal to field and choose the CategoryID column from the rsQuotes recordset in the Dynamic Data dialog that appears.
6. Click OK to close the Dynamic Data dialog, and then click OK to close the Dynamic List/Menu dialog and add the dynamic list code to your page.
Updating the Update server behavior With your dynamic drop-down menus in place, all you need to do to complete this page is update the Update server behavior to include these two new items, Author and Category:
1. In the Application panel, click Server Behaviors and then double-click the Update Record server behavior to begin editing it.
2. In the Form elements section of the dialog, click Author to select it if it isn’t already selected by default. Then choose AuthorID from the Column drop-down menu and leave Numeric selected in the Submit as drop-down menu.
3. In the Form elements section again, click Category to select it if it isn’t already selected by default. Then choose CategoryID from the Column drop-down menu and leave Numeric selected in the Submit as drop-down menu (Figure 7-25).
Figure 7-25. The updated Update Record dialog. Now authors and categories can be updated!
4. Click OK to apply the changes to the page, and then save your page.
213
CHAPTER 7 With the editquote.asp page now completed, you can move on to build the page that will retrieve a random quote from the database to round off this little application. If you haven’t added any quotes to your database yet, now would be a great time to do so before moving on to the next step of retrieving a random quote. You can download data from www.friendsofed.com if you need to.
The random quote generator With the administration system complete, you can now build a simple page to randomly select a quote from the database and display it, along with the author of the quote and the category it has been classified under. To help you achieve that goal, you’ll build a query in the database to gather the data from the three tables into one place from which you can select your data.
Creating a join in the database Creating the join in Access can be done using a wizard or manually in a visual designer. We suggest using the visual designer method over the wizard, as follows:
1. Open your Access database and click Queries in the left menu to display any queries you may already have in there.
2. Double-click the Create query in design view list entry and the query designer window will open. The first thing you need to do is to add the tables that will be needed to the design of this query. You can always add more later, but you’re adding only three here, so you may as well add them all up front.
3. Select tblAuthors, tblCategories, and tblQuotes in the Show Tables dialog (Figure 7-26) and click Add to add them to the query designer window.
Figure 7-26. Adding tables to the design of the query
4. Click Close to close the Show Tables dialog.
214
COMPLETING THE QUOTES ADMINISTRATION SYSTEM The query designer window displays the three tables with a black line joining tblAuthors and tblCategories to tblQuotes (Figure 7-27). This window shows you the relationships among the three objects you created earlier in this chapter.
Figure 7-27. Query designer window showing the tables and their relationships
Now you can begin adding the columns to this query that you want to select from all three tables. To add a column to the query SELECT statement, you just need to double-click it.
5. In the tblQuotes table, double-click the Quote column. It will appear in the rows in lower window of the query designer. Next, double-click the Author field in tblAuthors to add that to the selected items. Finally, double-click the Category field in tblCategories. The query designer should now look like Figure 7-28.
Figure 7-28. The completed query designer window
We’ve moved the tables around in the query designer view to make it easier to see the join lines between the three tables.
215
CHAPTER 7 The SQL code that these actions produce uses the JOIN keyword to join the three tables together for you. It makes sure that each quote this query returns from the tblQuotes table will have the appropriate author and category retrieved from the tblAuthors and tblCategories tables. To take a look at the SQL code that Access has produced for you, select the View menu while the query designer window is active and then select SQL View (Figure 7-29).
Figure 7-29. Checking out the SQL code Access has produced in SQL view
Your SQL code should look something like this: SELECT tblQuotes.Quote, tblAuthors.Author, tblCategories.Category FROM tblCategories INNER JOIN (tblAuthors INNER JOIN tblQuotes ON tblAuthors.AuthorID = tblQuotes.AuthorID) ON tblCategories.CategoryID = tblQuotes.CategoryID; Save this query in your database now by clicking the Save icon on the Access toolbar and giving it the name viewQuotes when prompted. Then close Access and return to Dreamweaver.
I have a habit of calling queries Views owing to me working primarily with SQL Server and that being the name for queries in that database. Therefore, I save all queries with a view prefix. —Rob Turnbull
You now have everything in place to build the page that will retrieve a random quote—let’s get right to it!
Displaying a random quote In Dreamweaver, create a new ASP VBScript file and save it as randomquote.asp. The first thing you need to do on this page is retrieve the quotes from the database—all of them. Once you have them all in a recordset on the page, you’ll then write some simple ASP VBScript code to pick one from the recordset at random and then display it.
216
COMPLETING THE QUOTES ADMINISTRATION SYSTEM
Building the Quotes recordset To build the Quotes recordset, follow these steps:
1. In the Application panel, select Bindings ➤ Recordset (Query) to begin creating the recordset. 2. When the Recordset dialog appears, enter rsQuotes in the Name field, select your database connection from the Connection drop-down menu, and then select viewQuotes from the Table drop-down menu (Figure 7-30). You want to select all the fields from the view so you can leave the rest of the dialog at the default settings (i.e., All selected in the Columns area, with Filter and Sort set to None).
Figure 7-30. Building the Quotes recordset
3. Click OK to create the recordset and close the Recordset dialog. An important change you need to make is to the recordset cursor type. Cursor types are what ADO, or ActiveX Data Objects, use to specify how the data you’re retrieving from the database should be viewed by the connection retrieving it. Two of ADO’s four cursor types won’t work for the code you’re about to create, and one of those is the default cursor type that Dreamweaver chooses for you when you create a recordset, Forward-only, so you need to change it to one that will work.
A good reference for ADO recordset information is the ADO section of the W3Schools website: www.w3schools.com/ado/ado_ref_recordset.asp.
You can bring up the recordset properties in the Property inspector by clicking the recordset name in the Server Behaviors panel. Alternatively, you can make the same details visible in Code view.
1. Switch to Code view and then click the cursor anywhere within the recordset code near the top of the page. The Property inspector will change to display the settings of the recordset. Magic!
2. In the Property Inspector, change the Forward-only cursor type to Static. This changes the 0 to 3 in the code of the recordset.
217
CHAPTER 7
3. Switch back to Design view and type Category:. 4. Press Enter to create a second paragraph, as this one just became the first paragraph by default.
5. Type Author: and press Enter again. 6. Finally, type Quote: into the third paragraph. Next, you need to bind the values you retrieve from the database to the page in the appropriate places. Dreamweaver keeps these data bindings in the Bindings panel of the Application panel group.
7. Click at the end of the Category: text and add a space. 8. In the Application panel, click Bindings, expand the rsQuotes recordset, select the Category field, and click Insert at the bottom of the Bindings panel to add that database field to the page.
9. Repeat step 8 to add the Author field to the page, and then repeat the step once more for the Quote field (Figure 7-31). Now you need to write the code to grab a quote at random from the recordset and display that quote’s details in these three elements on the page.
Figure 7-31. The three bindings on the page in Design view
10. Switch to Code view and locate the opening
tag of the first paragraph. It should be immediately below the opening tag. Press Enter twice to create a space between the tag and the
tag, and then click on the first blank line below the tag.
11. The first line of code you’ll add is to avoid the page throwing an error if the recordset is empty (i.e., the database doesn’t have any quotes in it). Enter the following code now:
This simple code is the main engine for our random quote generator, so we’ll explore it in detail.
218
COMPLETING THE QUOTES ADMINISTRATION SYSTEM You assign the total record count minus 1 to the variable varTotalQuotes. You subtract 1 from the total to ensure that the code later on doesn’t accidentally go past the end of the recordset, which would result in the page spitting out an error. Next, you instruct the VBScript engine to make your random number really random by calling the built-in Randomize function. Without this call to Randomize, a call to the built-in Rnd function will return the same random number quite a lot. Not very random!
Then you assign an Int value (a whole number) to the variable varRandomNumber. This integer is generated by taking the value held in the varTotalQuotes variable—your total record count minus 1—and multiplying it by the number that the Rnd built in function gives you. The builtin Rnd function will always return a real number (decimal) greater than or equal to 0.0 and less than 1.0. You add 1 to that equation to ensure that you will always have at least 1 as a result of this sum. Finally, you instruct the rsQuotes recordset to Move to the position in the recordset specified in the varRandomNumber variable. This value will never be zero, nor will it ever be one more than the total number of records available, either of which would result in an error. That’s the end of the code that you need to add to before the output paragraphs.
13. Move down to just after the end of the last of the three paragraphs you added to the page earlier, just above the closing tag, and add this VB Script code:
You must End the If you started earlier on or you’ll get an error for that too! The completed code for this section of the page should look like something like this:
Category:
Author:
Quote:
Login failed, please retry
Login failed, please retry
Username
226
RESTRICTING ACCESS Password
Username
Password
Access Level
Submit
Username () already in use, choose another