Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download PHP C:\windows\PHP.ini พิมพ์แทรก cgi.force_redirect = 0 เปลี่ยนจาก Off เป็ น On error_reporting=E_ALL & ~E_NOTICE Internet Programming by PHP PHP Web-Server Architecture Client Side Server Side Web Server PHP engine Client เรี ยกไฟล์ .PHP HTML Page .PHP Web Browser Database PHP Tag Styles • XML Style <?php echo ‘<P>Order porocessed.</P>’; ?> • Short Style <? echo ‘<P>Order porocessed.</P>’; ?> • SCRIPT Style <script language=‘php’> echo ‘<P>Order porocessed.</P>’; </script> • ASP Style <% echo ‘<P>Order porocessed.</P>’; %> ความสามารถของ PHP • มีความสามารถในการจัดการกับตัวแปรหลายประเภท เช่น integer, float, string, array เป็ นต้น • สามารถรับข้อมูลจากฟอร์มของ HTML ได้ • สามารถรับ-ส่ ง Cookies ได้ • สามารถใช้ตวั แปรแบบ Session ได้ ( PHP version 4.0 ขี้นไป) • มีความสามารถในการรองรับการเขียนโปรแกรมแบบ OOP (Object Oriented Programming) • สามารถเรี ยกใช้ COM component ได้ • มีความสามารถในการติต่อและจัดการฐานข้อมูล • มีความสามารถในการสร้างภาพกราฟฟิ ก ตัวอย่ างของรู ปแบบการเขียนโปรแกรมแบบ PHP <HTML> <HEAD> <TITLE> New Document </TITLE> </HEAD> <BODY BGCOLOR="#FFFFFF"> <?php echo "ทดสอบ PHP"; ?> </BODY> </HTML> Variable Type • Interger => ใช้สาหรับเก็บข้อมูลที่เป็ นตัวเลขไม่มีจุดทศนิ ยม • Double => ใช้สาหรับเก็บข้อมูลที่เป็ นตัวเลขจานวนจริ ง • String => ใช้สาหรับเก็บข้อมูลที่เป็ นตัวอักษร • Boolean => ใช้สาหรับข้อมูลในการตรวจสอบสถานะที่เป็ น True หรื อ False • Array => ใช้สาหรับเก็บข้อมูลที่เป็ น Multiple Data โดยสามารถใช้ได้กบั ข้อมูล ทุกชนิดที่กล่าวมา • Object => ใช้สาหรับเก็บข้อมูลในรู ปแบบของ Classes การประกาศตัวแปร ่ • ต้องมีเครืองหมาย $ (dollar sing) นาหน้ าเสมอ •ใน PHP การประกาศตัวแปรด้ วยตัวพิมพ์เล็ก หรื อ ตัวพิมพ์ใหญ่ จะถือว่ าเป็ นคนละตัว แปร เช่น number กับ Number ่ วแปรจะต้องขึนต้ ้ นด้วย ตัวอ ักษร หรือ • ชือตั เครื่ องหมาย _ (Underscore) เท่ านั้น • การประกาศตัวแปรใน PHP ไม่ ต้องกาหนด Type ของตัวแปร PHP จะ เป็ นตัวกาหนด ่ ให้โดยอ ัตโนมัต ิ โดยพิจารณาจากค่าทีจะน ามาเก็บใน ตัวแปรนั้น ยกเว้ นตัวแปรชนิด EX ตัวอย่ างรูปแบบการประกาศตัวแปร <?php $VariablesType = "ตัวเลข"; //ตัวแปร String output $variablestype = 10; //ตัวแปร Interger เลขฐาน 10 $number8 = 025; //ตัวแปร Interger เลขฐาน 8 $number16 = 0x25; //ตัวแปร Interger เลขฐาน 16 $NumberReal1 = 9.18; //ตัวแปร Double แสดงจุดทศนิยม $NumberReal2 = 9.18e3; //ตัวแปร Double เลขยกกาลัง 9.81คูณ10ยกกาลัง3 $NumberReal3 = 9.18e-3; //ตัวแปร Double เลขยกกาลัง 9.81คูณ10ยกกาลังลบ3 echo "$VariablesType<br>";echo "$variablestype<br>"; echo "$number8<br>";echo "$number16<br>"; echo "$NumberReal1<br>";echo "$NumberReal2<br>";echo "$NumberReal3<br>"; ?> แบบที่ 1 การเก็บค่าลงใน Array <?php $VariablesArray = array("10","20","30"); echo $VariablesArray[0]."<br>"; output echo $VariablesArray[1]."<br>"; echo $VariablesArray[2]."<br>"; ?> แบบที่ 2 <?php $VariablesArray = array('name'=>'สุระชัย', 'Lname'=>'หัวไผ่','Email'=>'[email protected]'); output echo $VariablesArray['name']." "; echo $VariablesArray['Lname']."<br>"; echo $VariablesArray['Email']."<br>"; ?> function each() การแสดงค่าจาก Array <?php $VariablesArray = array('name'=>'สุระชัย','Lname'=>'หัวไผ่','Email'=>'[email protected]'); ?> <?php //แสดงค่าโดยใช้ function each() $VariablesArray1 = each($VariablesArray); echo $VariablesArray1['0']." "; output echo $VariablesArray1['1']."<br>"; $VariablesArray1 = each($VariablesArray); echo $VariablesArray1['0']." "; echo $VariablesArray1['1']."<br>"; $VariablesArray1 = each($VariablesArray); echo $VariablesArray1['0']." "; echo $VariablesArray1['1']."<br>"; ?> function list() การแสดงค่าจาก Array <?php $VariablesArray = array('สุ ระชัย','หัวไผ่','[email protected]'); ?> <?php //แสดงค่าโดยใช้ ้้ function List() list($name,$last,$email)=$VariablesArray; echo "ชื่อ $name นามสกุล $last <BR> email $email \n"; ?> output Arithmetic Operators ตัวอย่าง + การบวก (addition) $a=$b+$c - การลบ (subtraction) Echo ($a+$b); * การคูณ (multiplication) $c=$a%$b; / การหาร (division) $a++ % โมดูลสั (modulus) เศษที่ได้จากการหาร + + เพิ่มค่าขึ้น 1 (incrementing) - - ลดค่าลง 1 (decrementing) ++$a นาค่าตัวแปรมาใช้ก่อนค่อยเพิ่มค่า เพิ่มค่าก่อนค่อยนาค่าตัวแปรมาใช้ $a + =$b เทียบเท่า $a =$a +$b Logical Operator Operator ความหมาย ตัวอย่าง && หรื อ and || หรื อ or AND $a && $b OR $a || $b ! NOT !$a ^ หรื อ xor Exclusive OR $a ^ $b Comparison Operators = = หมายความว่า เท่ากับ (equal) = = = หมายความว่า เหมือนกัน (identical) != หรื อ <> หมายความว่า ไม่เท่ากับ (not equal) !== หมายความว่า ไม่เหมือนกัน (not identical) < หมายความว่า น้อยกว่า (Less then) > หมายความว่า มากกว่า (Greater than) <= หมายความว่า น้อยกว่าเท่ากับ >= หมายความว่า มากกว่าเท่ากับ หมายเหตุ $a<$b หมายความว่า a น้อยกว่า b if <?php $a=1;$b=2; if ($a<$b) { echo "จริ ง"; } ?> Conditional Execution output If Else <?php $a=1;$b=2; if ($a>$b) {echo "จริ ง";} else {echo ”เท็จ";} ?> output If Elseif Conditional Execution <?php $a=1;$b=2; if ($a>$b) {echo "จริ ง";} elseif($a<$b) {echo "เท็จ";} ?> output Switch <?php $a=1; switch ($a){ case 1: echo “1”; break; case 2: echo ”2"; break; } ?> output For <?php For ($a=0; $a<=5; $a++){ echo “$a”; } ?> Iteration output While <?php $a=1; While ($a<=5){ echo "$a"; $a++; } ?> output Do...While <?php $a=1; do{ echo "$a"; $a++; }While ($a<=6); ?> Iteration output Break <?php $a=1; While ($a<=5){ echo "$a"; $a++; if ($a==3){break;} } ?> output การรับค่าจาก web browser แบบ Post <form method="post" action="form_process.php"> ชื่อ : <input type="text" name="txtname"><br> เพศ : <input type="radio" name="gender" value="m" checked>ชาย <input type="radio" name="gender" value="f">หญิง<br> ระดับการศึกษา : <select name="graduation" size="1"> <option value="1">ประถมศึกษา</option> <option value="2">มัธยมศึกษา</option> <option value="3">อนุปริ ญญา</option> <option value="4">ปริ ญญาตรี ข้ ึนไป</option> </select><br> <input type="hidden" name="myname" value="Member"> <br><input type="submit" value=”Submit"> <input type="reset" value="clear"> </form> การแสดงค่าที่รับจาก web browser ด้วย PHP <?php echo "ค่าของช่องรับข้อความ : <b>" . $txtname . "</b><br>"; echo "ค่าของปุ่ มตัวเลือก : <b>" . $gender . "</b><br>"; echo "ค่าของลิสต์บอ็ กซ์ : <b>" . $graduation . "</b><br>"; echo "ค่าของ hidden field : <b>" . $myname . "</b>"; ?> การรับค่าจาก web browser แบบ Get <form method="get" action="form_process2.php"> ชื่อ : <input type="text" name="txtname"><br> เพศ : <input type="radio" name="gender" value="m" checked>ชาย <input type="radio" name="gender" value="f">หญิง<br> ระดับการศึกษา : <select name="graduation" size="1"> <option value="1">ประถมศึกษา</option> <option value="2">มัธยมศึกษา</option> <option value="3">อนุปริ ญญา</option> <option value="4">ปริ ญญาตรี </option> </select><br> <input type="hidden" name="myname" value="SOMPRASONG"> <br><input type="submit" value="submit"> <input type="reset" value="clear"> </form> การแสดงค่าที่รับจาก web browser ด้วย PHP <?php echo "query string ที่พว่ งมากับ URL คือ <br><b>" . $QUERY_STRING . "</b><br>"; echo "ค่าของช่องรับข้อความ : <b>" . $txtname . "</b><br>"; echo "ค่าของปุ่ มตัวเลือก : <b>" . $gender . "</b><br>"; echo "ค่าของลิสต์บอ็ กซ์ : <b>" . $graduation . "</b><br>"; echo "ค่าของ hidden field : <b>" . $myname . "</b>"; ?> การส่ ง query string ผ่าน Hyperlink สัญลักษณ์ ? & = + % ความหมาย ใช้คนั ระหว่าง URL กับ query string ใช้คนั ระหว่างตัวแปรต่างๆ ที่อยูภ่ ายใน query string ใช้คนั ระหว่างชื่ อของตัวแปรกับค่าของตัวแปร ใช้แทนช่องว่าง ใช้นาหน้าตัวเลขในรู ปฐานสิ บหก เพื่อแทนอักขระพิเศษที่มี รหัสแอสกี้เลขฐานสิ บหกเท่านั้น เช่น @ [ และพยัณชนะ ภาษาไทย <a href=“get_qstr.php? Name=สุ ระชัย+หัวไผ่ &[email protected] &Phone=099199302”> sen <?php echo . $Name . "</b><br>"; echo . $Email . "</b><br>"; echo . $Phone. "</b>"; ?> Session • • • • • Session เป็ นตัวแปร เพื่อเก็บค่าต่างๆไว้ ที่ Client side Session จะจาค่าตัวแปรไว้จนกว่าจะปิ ดหน้าต่างของ Web browser PHP ที่สามารถใช้ตวั แปร Session ได้ ตั้งแต่ version 4.0 ขึ้นไป เราใช้ตวั แปร Session ช่วยในการเก็บค่า Password หรื อใช้ช่วยคานวณจานวนและราคาสิ นค้าที่ตอ้ งการสัง่ ซื้อ Session Function Session_registor(“ชื่อตัวแปร”); ===> ใช้กาหนดค่าให้ session Session_Start(); ===> ใช้เริ่ มต้นการทางานของ session Session_Unregister(“ชื่อตัวแปร”); ===> ยกเลิกตัวแปร session ที่กาหนด Session_destroy(); ===> ยกเลิกตัวแปร session ทั้งหมด Session Example <?php session_start(); session_unregister("username"); ?> <form action="session_file2.php"> <input type="text" name="username"> <input type="submit" value=" OK "> </form> Session Example <?php session_register("username"); echo $username; ?> <br><a href="session_file3.php">session_file3.php</a> <?php session_start(); echo $username; ?> <br><a href="session_file1.php">session_file1.php</a> Cookie • • • • • Cookie การเก็บข้อมูลฝัง Client Side Cookie จะถูกจัดเก็บในรู ปของไฟล์ Cookie ไฟล์ Cookie จะถูกจัดเก็บไว้ที่เครื่ อง Client ที่เข้าไปใช้บริ การ Cookie สามารถกาหนดอายุการทางานได้ เราใช้ Cookie ในการตรวจสอบและติดตามการใช้บริ การต่างของ ผูใ้ ช้บริ การ web server ได้ • หรื ออาจประยุกต์ใช้ในการให้บริ การกับลูกค้าประจาได้ Cookie Function Setcookie( ชื่อ,ค่า,เวลาหมดอายุ); ===> ใช้สาหรับส่ ง Cookie ไปยังเครื่ องผูใ้ ช้ Output Buffering Function Ob_start(); ===> ใช้เปิ ดการทางานของ Output buffering และจอง buffering ไว้ (ควรเรี ยกใช้ function ในบรรทัดแรกของโปรแกรม) Ob_end_flush(); ===> ใช้ส่งค่าที่เก็บใน buffer ไปยัง web browser และ ปิ ดการทางานของ Output buffering Cookie Example <?php //กาหนดให้ cookie หมดอายุหลังจากถูกสร้างแล้วเป็ นเวลา 60 วินาที (1 นาที) $c_name = "TestCookie"; $c_val = "123"; setcookie($c_name, $c_val, time() + 60); echo " c_name=$c_name<br>"; echo " c_val=$c_val <br>"; ?> <br> <a href="cookie_test.php">ตรวจสอบค่าของ cookie</a><br> Cookie Example <?php if (isset($HTTP_COOKIE_VARS['TestCookie'])) { echo $HTTP_COOKIE_VARS['TestCookie']; } else { echo "ไม่พบตัวแปร \$HTTP_COOKIE_VARS['TestCookie']"; } ?> Output ก่อน 60 วินาที Output หลัง 60 วินาที Cookie Example <?php echo "ทดสอบ"; setcookie("Test", "456", time() + 60); ?> Management File & Directory for PHP Function ==> fopen() รู ปแบบ ==> ใช้ เเปิ ด file fopen (“ filename”, “Mode”) Mode • r ==> เปิ ดอ่านอย่างเดียวโดยเริ่ มอ่านจากตาแหน่งเริ่ มต้นของไฟล์ • r+ ==> เปิ ดอ่านและเขียนไฟล์ โดยเริ่ มอ่านจากตาแหน่งเริ่ มต้นของไฟล์ •w ==> เขียนไฟล์ทบั ไฟล์เดิมข้อความเดิมจะหายหมด ถ้าไม่มีไฟล์อยูจ่ ะเขียนไฟล์ข้ ึนมาใหม่ •w+ ==> เปิ ดเพื่ออ่านไฟล์และ เขียนไฟล์ทบั ไฟล์เดิมข้อความเดิมจะหายหมด ถ้าไม่มีไฟล์อยูจ่ ะเขียนไฟล์ ขึ้นมาใหม่ •a ==> เขียนต่อท้ายไฟล์ ถ้าไม่มีไฟล์อยูจ่ ะเขียนไฟล์ข้ ึนมาใหม่ •a+ ==> เปิ ดเพื่ออ่านไฟล์และ เขียนต่อท้ายไฟล์ ถ้าไม่มีไฟล์อยูจ่ ะเขียนไฟล์ข้ ึนมาใหม่ Function ==> fclose() รู ปแบบ ==> ใช้ เปิ ด file fclose ( “file_ID”) File_ID ==> คือหมายเลขไฟล์ที่ทาการเปิ ดหลังใช้ fopen() Function ==> fpassthru() เป็ นฟังก์ชั่นที่ใช้ อ่านข้ อมูลทั้งหมดจากไฟล์และปิ ดไฟล์โดยไม่ ต้องใช้ fclose() <?PHP $file1 = fopen("filephp.txt","r"); echo $file1; fpassthru ($file1); ?> Function ==> fread() เป็ นฟังก์ชั่นที่ใช้ อ่านข้ อมูลจากไฟล์โดยกาหนดจานวนไบต์ ได้ รู ปแบบ ==> fread(“file_ID”,”จานวน Byte ที่ต้องการอ่าน”) <?PHP $file1 = fopen("filephp.txt","r"); $mydata = fread($file1,5); echo $mydata."<BR>"; fclose ($file1); ?> Function ==> file() เป็ นฟังก์ชั่นพิเศษที่ใช้ อ่านข้ อมูลจากไฟล์โดยไม่ ต้องสั่งเปิ ดไฟล์ด้วยฟังก์ชัน fopen() รู ปแบบ ==> file(“ชื่ อไฟล์ ”) <?php $data1 = file(“C:/inpub/wwwroot/test.txt”) for ($I=0; $I<Count($data); $i++){ echo $data1.”<BR>:”; } ?> aaa bbb ccc การเขียนข้ อมูลลง file fputs() การเขียนข้ อมูลลง file ใน PHP มี 2 function ใช้ งานเหมือนกัน fwrite() รู ปแบบ ==> fputs(“File_ID”,”ข้ อมูลที่ต้องการเขียนลงไฟล์ ”) <?php $file1 = fopen("filephp.txt","r"); fputs($file1,”ทดสอบ”); fclose ($file1);} ?> PHP Connection to ODBC 1. สร้ างฐานข้ อมูล 2. ทาการเชื่ อมต่ อ ODBC ของ Microsoft Windows กับ ้ ฐานข้อมู ลที่ สร ้างขึน 3. กาหนดชื่ อ ของ DSN (Data Source Name) ทีใ่ ช้ ่ สาหร ับเชือมต้ อฐานข้อมู ล 4. ใช้ Function ทีม่ อี ยู่ใน PHP Engine เรียกใช้ ฐานข้ อ มู ลผ่าน DSN ทีก่ าหนดไว้ รู ปแบบการเชื่อมต่อฐานข้อมูล 1. เปิ ดฐานข้ อมูล ==> Connection 2. จัดการฐานข้ อมูล ==> Insert,Update,Delete,Search 3. ปิ ดฐานข้ อมูล==>Close ฟังก์ชนั odbc_Connect() ใช้สาหรับการเชื่อมฐานข้อมูล รู ปแบบ $conn=odbc_Connect(“DSN”,”Usename”,”Password”); ฟังก์ชนั odbc_Close() ใช้สาหรับยกเลิกการเชื่อมต่อฐานข้อมูล รู ปแบบ odbc_Close(“Connection_ID”); Ex odbc_Close($conn); ฟังก์ชนั odbc_exec() ใช้สาหรับการสร้าง Query กับฐานข้อมูลที่เชื่อมต่อ รู ปแบบ odbc_exec(“Connection_ID”,”SOL_Statement”); Ex $sql = “SELECT * From Product Where ProdcutID=$searchID” $table_product = odbc_exec($conn,$sql); ฟังก์ชนั odbc_num_rows() ใช้สาหรับการนับจานวน Record ถ้าทางานไม่สาเร็ จจะคืนค่า -1 กลับมา รู ปแบบ odbc_num_rows(“Execute_Num”); Ex $sql = “SELECT * From Product Where ProdcutID=$searchID” $table_product = odbc_exec($conn,$sql); $record_count=odbc_num_rows($table_product ); ฟังก์ชนั odbc_num_fields() ใช้สาหรับการนับจานวน field ถ้าทางานไม่สาเร็ จจะคืนค่า -1 กลับมา รู ปแบบ odbc_num_fields(“Execute_Num”); Ex $sql = “SELECT * From Product Where ProdcutID=$searchID” $table_product = odbc_exec($conn,$sql); $field_count= odbc_num_fields($table_product ); ฟังก์ชนั odbc_fields_name() ใช้สาหรับการแสดงชื่อของ field รู ปแบบ odbc_fields_name(“Execute_Num”,” field_Id”); Ex $sql = “SELECT * From Product Where ProdcutID=$searchID” $table_product = odbc_exec($conn,$sql); echo odbc_fields_name($table_product,”1”); ฟังก์ชนั odbc_fetch_row() ใช้สาหรับการอ่านข้อมูลใน Record ปัจจุบนั และเลื่อน Index ไปยังตาแหน่งถัดไป รู ปแบบ odbc_fetch_row(“Execute_Num”); Ex $sql = “SELECT * From Product Where ProdcutID=$searchID” $table_product = odbc_exec($conn,$sql); echo odbc_fetch_row($table_product,); ฟังก์ชนั odbc_result() ใช้สาหรับการอ่านข้อมูลใน Record ปั จจุบนั โดยกาหนด field ที่ตอ้ งการได้และเลื่อน Index ไปยังตาแหน่งถัดไป รู ปแบบ odbc_result(“Execute_Num”,”field_name หรื อ field_ID”); Ex $sql = “SELECT * From Product Where ProdcutID=$searchID” $table_product = odbc_exec($conn,$sql); echo odbc_result($table_product,”ProductName”); Introduction to PHP & MySQL David Olsen WVU Web Services April 2, 2003 Overview of Presentation Introduction – My Experience – What I Won’t be Covering Why Use PHP & MySQL How It All Works Overview of PHP PHP Crash Course Overview of MySQL MySQL Crash Course Using PHP to Query a MySQL Database Example Script – Oscar Pool PHP & MySQL Resources Introduction My Experience – – – – Web Developer for 4 years Started creating DB-driven sites in 2001 (PHP & Sybase) Not formally trained in programming or database development and have picked it up as I’ve gone along. Consider myself at an Intermediate-level with PHP & MySQL What I won’t be Covering – – – Installation Product Comparisons (e.g. PHP vs. ASP, ColdFusion, Perl) Web Application Security Why Use PHP & MySQL If you want to add dynamic content to your pages If you want to make your pages easier to maintain If you’re learning your first "real" computing language If you need a solution that’s portable across multiple platforms (e.g. Red Hat Linux to Windows 2000) If you like free software or need a free solution Examples of uses of PHP & MySQL: – – – – – Sign-up Forms Surveys Polls Email a Postcard Content Management Overview of PHP Open Source server-side scripting language designed specifically for the web. Can also be used for command-line scripting and writing clientside GUI applications. Conceived in 1994, now used on +10 million web sites. Outputs not only HTML but can output XML, images (JPG & PNG), PDF files and even Flash movies (using libswf and Ming) all generated on the fly. Can write these files to the filesystem. Supports a wide-range of databases (20 + ODBC). PHP also has support for talking to other services using protocols such as LDAP, IMAP, SNMP, NNTP, POP3, HTTP. Perl- and C-like syntax. Relatively easy to learn. Website @ http://www.php.net/ PHP Crash Course Embedding PHP in HTML Adding dynamic content – – – Introduction to PHP functions How to find system information Date( ) function Variables Accessing Form Variables Operators Control Structures PHP Crash Course (cont.) Embedding PHP in HTML <html> <body> <strong>Hello World!</strong><br /> <? echo ‘My name is Dave Olsen!’; ?> </body> </html> PHP tag styles: XML: <?php ?>, Short: <? ?>, ASP: <% %> Script: <script language=‘php’></script> url: http://www.usablecode.com/wvuPresentation/embed.php PHP Crash Course (cont.) Adding dynamic content by adding the date to the page. <html> <body> <strong>Hello World!</strong><br /> <? echo ‘Today is’; echo date(‘H:i jS F’); ?> </body> </html> Date() http://www.php.net/manual/en/function.date.php PHP Function Reference http://www.php.net/manual/en/funcref.php One useful function is phpinfo(). Gives system information so you can quickly find out what’s on your machine. url: http://www.usablecode.com/wvuPresentation/date.php PHP Crash Course (cont.) Variables: Are the symbols we use to represent data. Variable names can be of any length; can include letters, numbers and underscores; cannot start with a digit; case-sensitive; and can have the same name as a function. To assign values to variables: $foo = ‘bar’; Data Type: String $foo = 1; Data Type: integer $foo = 5.34; Data Type: Double $foo = array(“bar”,”united”); Data Type: Array Data Types are automatically assigned though you can force a data type by type casting. For example: $foo = ‘Hello’; $bar = (int)$foo; $bar now equals 0 Almost all variables are local. Globals include $_POST PHP Crash Course (cont.) Accessing Form Variables Three methods – – – Short: $varfoo, Medium: $_POST[‘varfoo’], (recommended for versions of PHP +4.1) Long: $HTTP_POST_VARS[‘varfoo’] Need register_globals ON for short method to work. Not expected to be ON on the WVU server. I’m open to input on the issue. Tip: For checkbox variables your variable name should end with [ ] – – Checkbox results are automatically put into an array Example: <input type=checkbox name=foo[] value=Y> PHP Crash Course (cont.) Operators: Operators are symbols that you can use to manipulate values and variables by performing an operation on them. Web Site @ http://www.php.net/manual/en/language.operators.php Includes: – – – – Assignment (e.g. =, +=, *=) Arithmetic (e.g. +, -, *) Comparison (e.g. <, >, >=, ==) Logical (e.g. !, &&, ||) PHP Crash Course (cont.) Control Structures: Are the structures within a language that allow us to control the flow of execution through a program or script. Grouped into conditional (branching) structures (e.g. if/else) and repetition structures (e.g. while loops). Example if/elseif/else statement: if ($foo == 0) { echo ‘The variable foo is equal to 0’; } else if (($foo > 0) && ($foo <= 5)) { echo ‘The variable foo is between 1 and 5’; } else { echo ‘The variable foo is equal to ‘.$foo; } Good code will use indents and comments. Overview of MySQL Relational database management system (RDBMS) Free Website @ http://www.mysql.com/ MySQL Crash Course Database Basics Common SQL Statements – – – – INSERT SELECT UPDATE DELETE Simple Join Entity-Relationship (ER) Modeling An Easy Way to Manage Your MySQL DBs MySQL Crash Course (cont.) Database Basics A relational database manager (MySQL) manages databases which holds tables which has records (rows) with attributes (columns) Each record must have a unique ID, also known as a Primary Key. When used as an identifier in another table it’s called a Foreign Key. Used for joins. Each attribute has to have a data type. (e.g. int, text, varchar) A database language (SQL) is used to create and delete databases and manage data MySQL Crash Course (cont.) Table structure for following examples: CREATE TABLE oscarpool ( uid int(4) auto_increment, username varchar(255), email varchar(255), bestpicture int(2), PRIMARY KEY (uid) ) CREATE TABLE bestdirector ( bdid int(4) auto_increment, name varchar(255), PRIMARY KEY (bdid) ) Created two tables, ‘oscarpool’ & ‘bestdirector’ Instead of using SQL to create tables use phpMyAdmin url: http://www.phpmyadmin.net/ MySQL Crash Course (cont.) Common SQL Statement: INSERT INSERT INTO oscarpool (username,email,bestpicture) VALUES (‘dolsen',‘[email protected]',1) Creates a new record in the table ‘oscarpool’ Text fields need to have ‘s. Tip: If you have an ‘ in your data you need to escape it before inserting it. Can use the PHP function addslashes(). Example: ‘John O\’Brien’ MySQL Crash Course (cont.) Common SQL Statement: SELECT SELECT uid,username FROM oscarpool Selects the attributes ‘uid’ and ‘username’ from every record in ‘oscarpool’ SELECT is how you query the database. You can also: – – – limit the number of records returned with LIMIT, limit retrieval to those records that match a condition with WHERE, sort the data after the query has been evaluated using ORDER BY Tip: To easily select every attribute replace ‘uid’ with ‘*’ MySQL Crash Course (cont.) Common SQL Statement: UPDATE UPDATE oscarpool SET email = ‘[email protected]’ WHERE uid = 1 Updates the email address where ‘uid = 1’ in the table ‘oscarpool’ In this case I know that uid 1 is what my record was. In many cases you’d pass a uid variable from a form. MySQL Crash Course (cont.) Common SQL Statement: DELETE DELETE FROM oscarpool WHERE uid = 1 Deletes the record where ‘uid = 1’ in the table ‘oscarpool’ DELETE only removes the record from the table. To remove an entire table from the database you need to use the SQL statement DROP. Tip: To remove every record in a table but not remove the table just don’t include the WHERE clause. MySQL Crash Course (cont.) Simple Join SELECT bd.name FROM oscarpool op, bestdirector bd WHERE op.uid = 1 and op.bestdirector = bd.bdid Selects the name of the Best Director that the user with ‘uid = 1’ has chosen bestdirector is a Foreign Key of the Primary Key for the table BestDirector Tip: Try to not have fields from two different tables have the same name. Gets confusing when trying to output this data when we connect with PHP. MySQL Crash Course (cont.) Entity-Relationship (ER) Modeling ER Modeling is the simple and clear method of expressing the design (relations) of a database between tables and attributes. Rectangles – Represent entities. Diamonds – Represent relationships between entities Ellipses – Represent attributes that describe an entity Lines – Connect entities to relationships. Can have annotation. M = many, 1 = one. Lines – Connects entities to attributes. No annotation. Entity = Table, Attributes = Attributes Web Database Applications by O’Reilly Publishers gives decent overview MySQL Crash Course (cont.) An easy way to manage your DBs phpMyAdmin is a browser-based administration tool for MySQL. Needs to be installed on your server. It can: – – – – – – – create and drop databases create, copy, drop, rename and alter tables delete, edit and add fields manage keys on fields load text files into tables create (*) and read dumps of tables and more Download phpMyAdmin @ http://www.phpmyadmin.net/ Note: phpMyAdmin does not come with out-of-the-box security. You either need to edit the config files to authenticate from a table or use .htaccess. Using PHP to Query a MySQL Database <html> <body> <h1>A List of Users Who Have Signed Up For OscarPool</h1> <? $dbh = mysql_connect("localhost",“dbusername",“dbpassword") or die(“Couldn't connect to database."); $db = mysql_select_db(“dbname", $dbh) or die(“Couldn't select database."); $sql = “SELECT username, email FROM oscarpool”; $result = mysql_query($sql, $dbh) or die(“Something is wrong with your SQL statement."); while ($row = mysql_fetch_array($result)) { $username = $row[‘username’]; $email = $row[‘email’]; echo ‘<a href=“mailto:’.$email.’”>’.$username.’</a><br />\n’; } ?> </body> </html> Using PHP to Query a MySQL Database (cont.) Notes for previous slide example: – – – – – – The first option in mysql_connect can be an IP address. mysql_query returns a small table with your results in it. The while loop then goes through each record of that small table and pulls out the attributes/fields you selected in your SQL statement. die( ) will kill the script. Make sure that that text is informative. If you use a function in your SQL query then it has to be a part of the $row statement. For example, UNIX_TIMESTAMP(datefield) would be $row[‘UNIX_TIMESTAMP(datefield)’] \n stands for a new line so that your source code will look a little neater: PHP MySQL functions @ url: http://www.php.net/manual/en/ref.mysql.php Example Script – Oscar Pool Script allows a user to enter a Pool where they get to choose who they think will win in various categories from the 2003 Oscars. The script makes sure that there’s one entry per email address. Utilizes include() to separate logic from presentation. Utilizes custom functions to handle errors and database connections. Not the best in regards to security but not bad. Created in one evening. Graphic Design by Jeph Christoff. url: http://www.usablecode.com/OscarPool/index.php src url: http://www.usablecode.com/OscarPool/index.phps PHP & MySQL Resources Web Sites – – – – – – – Books – – – – PHP and MySQL Web Development 2nd Edition, Welling & Thomson Web Database Applications with PHP & MySQL, O’Reilly Publishers PHP Cookbook, O’Reilly Publishers MySQL Cookbook, O’Reilly Publishers Listservs – http://www.php.net/ http://www.phpbuilder.com/ http://www.devshed.com/ http://www.phpmyadmin.net/ http://www.hotscripts.com/PHP/ http://www.mysql.com/ http://www.owasp.org/ thelist, http://lists.evolt.org/ (Note: very general and large volume of email) People - Me, [email protected]