380 likes | 771 Views
Ch. 3. PHP ( 이 강의 내용의 대부분 예들은 http:// www.w3schools.com/php/default.asp 에서 가져온 것이다 ). PHP?. PHP?: “PHP: Hypertext Preprocessor “ PHP First version in 1994 by Rasmus Lerdorf Server-sided scripting language
E N D
Ch. 3. PHP(이 강의 내용의 대부분 예들은 http://www.w3schools.com/php/default.asp에서 가져온 것이다)
PHP? • PHP?: “PHP: Hypertext Preprocessor “ • PHP • First version in 1994 by RasmusLerdorf • Server-sided scripting language • integrats with popular DBs & supports number of major protocols (POP3, IMAP, LDAP, etc.) • fast • forgiving • C like • free
내려받기와 설치 • 내려 받기: http://php.net • 설치: • Web server가 먼저 설치 되어야 함 • (지세한 과정은 생략)
Syntax • Basic • <?php{php coding} ?> • <?phpecho "Hello World!";?>
Comments • <?php// This is a single-line comment# This is also a single-line comment/*This is a multiple-lines comment blockthat spans over multiplelines*/// You can also use comments to leave out parts of a code line$x = 5 /* + 15 */ + 5;echo $x;?>
Variables • $로 시작:$name • 대소문자 구분 • 이름을 숫자로 시작할 수 없음 • 이름에 A-z, 0-9, _ 만 사용 • <?php$txt = "Hello world!";$x = 5;$y = 10.5;?>
<?php$txt = "W3Schools.com";echo "I love $txt!";?> • <?php$txt = "W3Schools.com";echo "I love " . $txt . "!";?> • <?php$x = 5;$y = 4;echo $x + $y;?>
<?php$x = 5; // global scopefunction myTest() {$x=8; // local scope echo "<p>Variable x inside function is: $x</p>";} myTest();echo "<p>Variable x outside function is: $x</p>";?>
<?php$x = 5;$y = 10;function myTest() { global $x, $y; $y = $x + $y;}myTest();echo $y; // outputs 15?>
<?phpfunction myTest() { static $x = 0; echo $x; $x++;}myTest();echo “<br>”;myTest();echo “<br>”;myTest();echo “<br>”;?>
Data Types • Types • String • Integer • Float (floating point numbers - also called double) • Boolean • Array • Object • NULL • Resource • 선언할 필요 없이 상황에 따라 자동으로 지정
<?php$x = 5985;$y=10.36;$z=“hello!”;var_dump($x);echo “<br>”;var_dump($y);echo “<br>”;var_dump($z);?>
Strings • <?phpecho strlen("Hello world!"); // outputs 12echo str_word_count("Hello world!"); // outputs 2echo strrev("Hello world!"); // outputs !dlrowolleHecho strpos("Hello world!", "world"); // outputs 6echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!?>
Constants • define(name, value, case-insensitive) • global • <?phpdefine("GREETING", "Welcome to W3Schools.com!", true);echo greeting;?>
Operators • Arithmatic
if • <?php$t = date("H");if ($t < "10") { echo "Have a good morning!";} elseif ($t < "20") { echo "Have a good day!";} else { echo "Have a good night!";}?>
switch • <?php$favcolor = "red";switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; case "green": echo "Your favorite color is green!"; break; default: echo "Your favorite color is neither red, blue, nor green!";}?>
while • <?php$x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++;} ?> • <?php$x = 1; do { echo "The number is: $x <br>"; $x++;} while ($x <= 5);?>
for • <?phpfor ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>";} ?> • <?php$colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>";}?>
functions • <?phpfunction sum($x, $y) { $z = $x + $y; return $z;}echo "5 + 10 = " . sum(5, 10) . "<br>";echo "7 + 13 = " . sum(7, 13) . "<br>";echo "2 + 4 = " . sum(2, 4);?> • <?phpfunction familyName($fname, $year) { echo "$fnameRefsnes. Born in $year <br>";}familyName("Hege", "1975");familyName("Stale", "1978");familyName("Kai Jim", "1983");?>
Arrays • $cars = array("Volvo", "BMW", "Toyota"); • $cars[0] = "Volvo";$cars[1] = "BMW";$cars[2] = "Toyota"; • $age['Peter'] = "35";$age['Ben'] = "37";$age['Joe'] = "43"; • <?php$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");echo "Peter is " . $age['Peter'] . " years old.";?>
Sorting arrays • sort() - sort arrays in ascending order • rsort() - sort arrays in descending order • asort() - sort associative arrays in ascending order, according to the value • ksort() - sort associative arrays in ascending order, according to the key • arsort() - sort associative arrays in descending order, according to the value • krsort() - sort associative arrays in descending order, according to the key
<?php$numbers = array(4, 6, 2, 22, 11);sort($numbers);$arrlength = count($numbers);for($x = 0; $x < $arrlength; $x++) { echo $numbers[$x]; echo "<br>";}?> • <?php$numbers = array(4, 6, 2, 22, 11);sort($numbers);$arrlength = count($numbers);for($x = 0; $x < $arrlength; $x++) { echo $numbers[$x]; echo "<br>";}?>
Superglobals • $GLOBALS • $_SERVER • $_REQUEST • $_POST • $_GET • $_FILES • $_ENV • $_COOKIE • $_SESSION
forms • <form action="welcome.php" method="post">Name: <input type="text" name="name"><br>E-mail: <input type="text" name="email"><br>< input type="submit">< /form> • <html>< body>Welcome <?php echo $_POST["name"]; ?><br>Your email address is: <?php echo $_POST["email"]; ?>< /body>< /html>
Include • menu.php • <?phpecho '<a href="/default.asp">Home</a> -<a href="/html/default.asp">HTML Tutorial</a> -<a href="/css/default.asp">CSS Tutorial</a> -<a href="/js/default.asp">JavaScript Tutorial</a> -<a href="default.asp">PHP Tutorial</a>';?> • <html>< body><div class="menu"><?php include 'menu.php';?></div><h1>Welcome to my home page!</h1><p>Some text.</p><p>Some more text.</p>< /body>< /html>
Include • menu.php • <?phpecho '<a href="/default.asp">Home</a> -<a href="/html/default.asp">HTML Tutorial</a> -<a href="/css/default.asp">CSS Tutorial</a> -<a href="/js/default.asp">JavaScript Tutorial</a> -<a href="default.asp">PHP Tutorial</a>';?> • <html>< body><div class="menu"><?php include 'menu.php';?></div><h1>Welcome to my home page!</h1><p>Some text.</p><p>Some more text.</p>< /body>< /html>
Session • <?php// Start the sessionsession_start();?><!DOCTYPE html><html><body><?php// Set session variables$_SESSION["favcolor"] = "green";$_SESSION["favanimal"] = "cat";echo "Session variables are set.";?>
PHP-MySQL • Connection • <?php$servername = "localhost";$username = "username";$password = "password";// Create connection$conn = mysqli_connect($servername, $username, $password);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}echo "Connected successfully";?>
Create DB • <?php$servername = "localhost";$username = "username";$password = "password";// Create connection$conn = mysqli_connect($servername, $username, $password);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}// Create database$sql = "CREATE DATABASE myDB";if (mysqli_query($conn, $sql)) { echo "Database created successfully";} else { echo "Error creating database: " . mysqli_error($conn);}mysqli_close($conn);?>
Create Table • <?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB";// Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}// sql to create table$sql = "CREATE TABLE MyGuests (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL,lastname VARCHAR(30) NOT NULL,email VARCHAR(50),reg_date TIMESTAMP)";if (mysqli_query($conn, $sql)) { echo "Table MyGuests created successfully";} else { echo "Error creating table: " . mysqli_error($conn);}mysqli_close($conn);?>
Insert data • <?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB";// Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}// sql to create table$sql = "CREATE TABLE MyGuests (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL,lastname VARCHAR(30) NOT NULL,email VARCHAR(50),reg_date TIMESTAMP)";if (mysqli_query($conn, $sql)) { echo "Table MyGuests created successfully";} else { echo "Error creating table: " . mysqli_error($conn);}mysqli_close($conn);?>
Select data • <?php$servername = "localhost";$username = "username";$password = "password";$dbname = "myDB";// Create connection$conn = mysqli_connect($servername, $username, $password, $dbname);// Check connectionif (!$conn) { die("Connection failed: " . mysqli_connect_error());}$sql = "SELECT id, firstname, lastname FROM MyGuests";$result = mysqli_query($conn, $sql);if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; }} else { echo "0 results";}mysqli_close($conn);?>