noteforW3schoolsPHP

for writing php code in local, i install wampServer, which combines Apache, PHP, MySQL on windows. wampServer is also developers’ toy only on windows, open source but unfriendly for beginers. i try to learn this software by reading document, but that’s little hard.
install VC11 before installing wampServer
LAMP => Apache MySQL and PHP on Linus
WAMP => Apache MySQL and PHP on Windows
OK, leave environment alone, let start learning.

PHP varible

Creating PHP varibles

* Note: Unlike other programming languages, PHP has no command for declaring a variable. It is created the moment you first assign a value to it. *

<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;  // does $ like var in javascript
?>

Global and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.

PHP The global Keyword

PHP The global Keyword
The global keyword is used to access a global variable from within a function.

To do this, use the global keyword before the variables (inside the function):

<?php
$x = 5; 
$y = 10;

function myTest() {
    global $x, $y;  //pay attention that $x and $y is declared outside of function
    $y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable:

<?php
function myTest() {
    static $x = 0;
    echo $x;
    $x++;
}

myTest();
myTest();
myTest();
?>

Then, each time the function is called, that variable will still have the information it contained from the last time the function was called.

* Note: The variable is still local to the function. *
* myfeeling: static varible is only static in its own function scope. *

PHP Data Type

<?php 
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
<?php
class Car {
    function Car() {
        $this->model = "VW";
    }
}

// create an object
$herbie = new Car();

// show object properties
echo $herbie->model;
?>

PHP Constants

Constants are Global

Constants are automatically global and can be used across the entire script.

The example below uses a constant inside a function, even if it is defined outside the function:

<?php
define("GREETING", "Welcome to W3Schools.com!");

function myTest() {
    echo GREETING;
}

myTest();
?>

PHP Operators

=== Identical x=== y Returns true if xisequalto y, and they are of the same type

PHP String Operators

PHP has two operators that are specially designed for strings.

Operator Name Example Result Show it
. Concatenation txt1. txt2 Concatenation of txt1and txt2 Show it »
.= Concatenation assignment txt1.= txt2 Appends txt2to txt1

$x = array("a" => "red", "b" => "green");  
$y = array("c" => "blue", "d" => "yellow");  

var_dump($x === $y);

PHP For Loops

The PHP foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Syntax
foreach ( arrayas value) {
code to be executed;
}

<?php 
$colors = array("red", "green", "blue", "yellow"); 

foreach ($colors as $value) {
    echo "$value <br>";
}
?>

PHP Functions

PHP Default Argument Value

The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:

<?php
function setHeight($minheight = 50) {
    echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions - Returning values

To let a function return a value, use the return statement:

<?php
function 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);
?>

PHP Arrays

Loop Through an Indexed Array

To loop through and print all the values of an indexed array, you could use a for loop, like this:

<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);

for($x = 0; $x < $arrlength; $x++) {
    echo $cars[$x];
    echo "<br>";
}
?>

Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like this:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $x_value) {
    echo "Key=" . $x . ", Value=" . $x_value;
    echo "<br>";
}
?>

PHP Superglobals

PHP Global Variables - Superglobals

Several predefined variables in PHP are “superglobals”, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

PHP $_REQUEST

PHP $_REQUEST is used to collect data after submitting an HTML form.

The example below shows a form with an input field and a submit button. When a user submits the data by clicking on “Submit”, the form data is sent to the file specified in the action attribute of the tag. In this example, we point to this file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_REQUEST to collect the value of the input field:

<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_REQUEST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>

</body>
</html>

* thanks god, this is wery convenient to use. *

PHP $_GET

PHP $_POST

* also could use GET["name"]and _POST[“name”], which is so simple to get form data. *

PHP Form Handing

GET vs. POST

Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, …)). This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

Both GET and POST are treated as GETand _POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

$_GET is an array of variables passed to the current script via the URL parameters.

$_POST is an array of variables passed to the current script via the HTTP POST method.

When to use POST?

Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
* soga *

PHP Form Validation

<?php // define variables and set to empty values $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>

* if you want to know how to prevent hackers, learn to be a hacker first. *

PHP Form Complete

* after test, only html code will be sent to browser, but php code will not send, which excute in sever side. *

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php // define variables and set to empty values $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); // check if name only contains letters and whitespace if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // check if URL address syntax is valid (this regular expression also allows dashes in the URL) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  Name: <input type="text" name="name" value="<?php echo $name;?>">
  <span class="error">* <?php echo $nameErr;?></span>
  <br><br>
  E-mail: <input type="text" name="email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
  Website: <input type="text" name="website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
  Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
  <br><br>
  <input type="submit" name="submit" value="Submit">  
</form>

<?php echo "<h2>Your Input:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?>

</body>
</html>

* but write php with html code seems odd. and I am curious about how JS test form value. *

PHP Date and Time

Use the date() function to automatically update the copyright year on your website:

&copy; 2010-<?php echo date("Y");?>

* scan this chapter rouphly, come back when you need it to show date. *

PHP 5 Include Files

* this can reduce code lines. *
Syntax

include 'filename';
//or
require 'filename';

PHP include vs. require

The require statement is also used to include a file into the PHP code.

However, there is one big difference between include and require; when a file is included with the include statement and PHP cannot find it, the script will continue to execute

<html>
<body>

<h1>Welcome to my home page!</h1>
<?php include 'noFileExists.php'; echo "I have a $color $car."; ?>

</body>
</html>

If we do the same example using the require statement, the echo statement will not be executed because the script execution dies after the require statement returned a fatal error.
**
Use require when the file is required by the application.

Use include when the file is not required and application should continue when file is not found.
**

PHP 5 Fle Handing

* another useful tools. *
** myfeeling:
1. test write a block of PHP code in html file but it will not be excute. server may only sent it to broswer.
2. and it seems possible to get data from form texture and input into a txt file. we can read a txt file into php code and echo it.
**

<?php
echo readfile("webdictionary.txt");
?>

PHP File Open/Read

<?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("webdictionary.txt")); fclose($myfile); ?>

* in this case, return and line break will not function. *

PHP check End of File

<?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); // Output one line until end-of-file while(!feof($myfile)) { echo fgets($myfile) . "<br>"; } fclose($myfile); ?>

* in this case, performance will be better cause return and line break function. *
* myfeeling: *
for case1:

$myfile = fopen("filename", "w") or die("unable to open file");
fwrite($myfile, $txt);

Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file

for case2:

$myfile = fopen("filename", "a") or die("unable to open file");
fwrite($myfile, $txt);

The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist
* and it seems that few wamps tutorials are online, unknow how to degue php code. *
* myfeeling end *

PHP 5 File Upload

With PHP, it is easy to upload files to the server.
However, with ease comes danger, so always be careful when allowing file uploads!
* who care? HAHHAHAHA *
* php.ini initialize file *

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

* it seems that i can not find uploads/ fold in my site3, but when i create uploads/ fold, sys tell me there all ready a fold named uploads/. strange! a invisiable fold. *
* and I find w3schools.com teach a little. *

Others in PHP 5

** i jumped some shapters like

PHP 5 Cookies

PHP 5 Sessions

PHP 5 Filters

PHP 5 Error Handling

PHP 5 Exception

cause right now, i do not need to care about this. **

PHP Connect to MySQL

in WAMP environment, connect to DB with root@localhost using empty password;

<?php
$servername = "localhost";
$username = "root";
$password = "";

try {
    $conn = new PDO("mysql:host=$servername;dbname=", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>

myfeeling: HAHA, get it, before it, I tried many password and username;

PHP MySQL Create

    $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "CREATE DATABASE myDBPDO";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "Database created successfully<br>";

* does it need to close or delete or something. *
* yes, it need, $conn = null; *

PHP MySQL Create Table

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 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
    )";

    // use exec() because no results are returned
    $conn->exec($sql);
    echo "Table MyGuests created successfully";
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>

PHP MySQL Insert

INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com');

PHP MySQL Insert Multiple

$conn->beginTransaction();
//code to change DB
$conn->commit();

//in catch block
$conn->rollback();

* I am so good that DW have local document about PDO (PHP Data object) *

MySQL prepared

//pre code
    // prepare sql and bind parameters
    $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) 
    VALUES (:firstname, :lastname, :email)");
    $stmt->bindParam(':firstname', $firstname);
    $stmt->bindParam(':lastname', $lastname);
    $stmt->bindParam(':email', $email);

    // insert a row
    $firstname = "John";
    $lastname = "Doe";
    $email = "john@example.com";
    $stmt->execute();

    // insert another row
    $firstname = "Mary";
    $lastname = "Moe";
    $email = "mary@example.com";
    $stmt->execute();
//following code

PHP MySQL Select

beg your pardon? I can not accept this. too far to go.

<?php
echo "<table style='border: solid 1px black;'>";
echo "<tr><th>Id</th><th>Firstname</th><th>Lastname</th></tr>";

class TableRows extends RecursiveIteratorIterator { 
    function __construct($it) { 
        parent::__construct($it, self::LEAVES_ONLY); 
    }

    function current() {
        return "<td style='width:150px;border:1px solid black;'>" . parent::current(). "</td>";
    }

    function beginChildren() { 
        echo "<tr>"; 
    } 

    function endChildren() { 
        echo "</tr>" . "\n";
    } 
} 

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT id, firstname, lastname FROM MyGuests"); 
    $stmt->execute();

    // set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); 
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { 
        echo $v;
    }
}
catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>

**
benefits of using PDO:
1. can access to more than one datebase;
2. can use try catch;
but php and mysql web develop book use sqli, cry.
**

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值