Notes: Learn PHP, MySQL & Javascript 5th with jQuery, CSS & HTML5 by Robin Nixon-未读完

狄飞鹏
2023-12-01

Internet Protocol (IP) address

MySQL accepts commands in Structured Query Language (SQL). SQL is the way that every user (including a PHP program) communicates with MySQL.

You may notice that the default version of PHP in AMPPS is 5.6. In other sections of this book I detail some of the more important changes in PHP 7. If you wish to try them out for yourself, click the Options button (nine white boxes in a square) within the AMPPS control window, and then select Change PHP Version, whereupon a new menu will appear from which you can choose a version between 5.6 and 7.1.

Ampps is a stack of Apache, PHP, MySQL, Perl & Python.

http://localhost/ampps/index.php?act=secure From here you can configure and control all aspects of the AMPPS stack.

The document root is the directory that contains the main web documents for a domain. This directory is the one that the server uses when a basic URL without a path is typed into a browser, such as http://yahoo.com or, for your local server, http://localhost.

By default AMPPS will use the following location as the document root:

C:\Program Files (x86)\Ampps\www

Both 127.0.0.1 and http://localhost are ways of referring to the local computer. When a WAMP or MAMP is properly configured, you can type either into a browser’s address bar to call up the default page on the local server.

By default, PHP documents end with the extension .php. When a web server encounters this extension in a requested file, it automatically passes it to the PHP processor. Of course, web servers are highly configurable, and some web developers choose to force files ending with .htm or .html to also get parsed by the PHP processor, usually because they want to hide their use of PHP.

----------------------

If you have only PHP code in a file, you may omit the closing ?>. This can be a good practice, as it will ensure that you have no excess whitespace leaking from your PHP files.

A common error is to use /* and */ to comment out a large section of code that already contains a commented-out section that uses those characters. You can’t nest comments this way; the PHP interpreter won’t know where a comment ends and will display an error message.

In PHP, you must place a $ in front of all variables. This is required to make the PHP parser faster, as it instantly knows whenever it comes across a variable.

---------------------

<!DOCTYPE html>

<html>

  <head>

    <title>Playing with Inline Styles</title>

  </head>

  <body>

  <!--inline css style-->

    <p style="color:blue;font-size:46px;">

      I'm a big, blue, <strong>strong</strong> paragraph

    </p>

  </body>

</html>

-----------------------

  $team = array('Bill', 'Mary', 'Mike', 'Chris', 'Anne');

  echo $team[0];//Bill

 --------------------

Use Ctrl+Q to toggle comments on and off in notepad++

----------------------

<?php

//multidimensional array

  $oxo = array(array('x', ' ', 'o'),

               array('o', 'o', 'x'),

               array('x', 'o', ' '));

 

  echo $oxo[2][1];//o

?>

------------------

  $a_number = 8;

  echo ++$a_number;//9

  echo '<br>';

  echo $a_number ** 2;//81

  echo '<br>';

  echo $a_number += 1;//10

  echo '<br>';

  echo $a_number < 11;//1

  echo '<br>';

----------

|| cannot be used to force a second statement to execute if the first fails, or operater must be used in this situation.

xor, which stands for exclusive or, returns a TRUE value if either value is TRUE, but a FALSE value if both inputs are TRUE or both inputs are FALSE. To understand this, imagine that you want to concoct your own cleaner for household items. Ammonia makes a good cleaner, and so does bleach, so you want your cleaner to have one of these. But the cleaner must not have both, because the combination is hazardous. In PHP, you could represent this as follows:

$ingredient = $ammonia xor $bleach;

-----------

$x = 9;

if (++$x == 10) echo $x;//first increse x by 1, then compare it with 10; return 10

if ($x-- == 10) echo $x;//first compare x with 10 decrease x by 1; return 9

/*In short, a variable is incremented or decremented before the test if the operator is placed before the variable, whereas the variable is incremented or decremented after the test if the operator is placed after the variable.*/

-----------------

//using the period (.) to append one string of characters to another

$msgs = "fifty";

$msgs .= "-one";

echo "You have " . $msgs . " messages.";//You have fifty-one messages.

---------------

/*If you wish to assign a literal string, preserving the exact contents, you should use single quotation marks (apostrophes)*/

$variable = "i am a string value.";

$info_single_quote = 'Preface variables with a $ like this: $variable';

$info_double_quote = "Preface variables with a $ like this: $variable";

echo $info_single_quote;//variable's value is not shown.

echo '<br>';

echo $info_double_quote;//variable substitution; variable's value is shown

----------------

using phpstorm:

 

To quickly see the documentation for the class or method used at the editor's caret, press Ctrl+Q (View | Quick Documentation).

 

You can easily rename your classes, methods and variables with automatic correction of all places where they are used.

Place the caret at the symbol you want to rename, and press Shift+F6 (Refactor | Rename). Type the new name and press Enter.

You can comment and uncomment lines and blocks of code using Ctrl+/ and Ctrl+Shift+/:

Ctrl+/ comments or uncomments the current line or the selected block with single line comments (//...).

Ctrl+Shift+/ encloses the selected block in a block comment (/*...*/).

To uncomment a commented block, position the caret anywhere inside it and press Ctrl+Shift+/ .

通过File-Setting-Font 可以设置字体大小。

-------------------

<?php

  $author = "Brian W. Kernighan";

 

  echo <<<_END

  Debugging is twice as hard as writing the code in the first place.

  Therefore, if you write the code as cleverly as possible, you are,

  by definition, not smart enough to debug it.

 

  - $author.

_END;

/*This code tells PHP to output everything between the two _END tags as if it were a double-quoted string (except that quotes in a heredoc do not need to be escaped). This means it’s possible, for example, for a developer to write entire sections of HTML directly into PHP code and then just replace specific dynamic parts with PHP variables.*/

/*

Remember: using the <<<_END..._END; heredoc construct, you don’t have to add \n linefeed characters to send a linefeed—just press Return and start a new line. Also, unlike in either a double-quote- or single-quote-delimited string, you are free to use all the single and double quotes you like within a heredoc, without escaping them by preceding them with a backslash (\).*/

/*

_END tag is simply one I chose for these examples because it is unlikely to be used anywhere else in PHP code and is therefore unique. You can use any tag you like, such as _SECTION1 or _OUTPUT and so on. Also, to help differentiate tags such as this from variables or functions, the general practice is to preface them with an underscore, but you don’t have to use one if you choose not to.

*/

?>

-------------------------

$heading = "Date\tName\tPayment";

echo $heading;

These special backslash-preceded characters work only in double-quoted strings. In single-quoted strings, the preceding string would be displayed with the ugly \t sequences instead of tabs. Within single-quoted strings, only the escaped apostrophe (\') and escaped backslash itself (\\) are recognized as escaped characters.

-------------------

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. - Brian W. Kernighan.

PHP is a very loosely typed language. This means that variables do not have to be declared before they are used, and that PHP always converts variables to the type required by their context when they are accessed.

 

Constants must not be prefaced with a $ (unlike regular variables), and you can define them only using the define function.

 

It is generally considered a good practice to use only uppercase letters for constant variable names.

------------------

echo "This is line " . __LINE__ . " of file " . __FILE__;// return the line number and the file path.

-----------------

print is a function-like construct that takes a single parameter and has a return value (which is always 1).

 

echo isn’t implemented like a function, echo cannot be used as part of a more complex expression, whereas print can.

 

-------------------

//define and call a function.

  function longdate($timestamp)

  {

    return date("D F jS Y", $timestamp);

  }

echo longdate(time());

----------------

By default, variables created within a function are local to that function, and variables created outside of any functions can be accessed only by nonfunction code.

 

Suffice it to say that unless you have declared a variable otherwise, its scope is limited to being local: either to the current function, or to the code outside of any functions, depending on whether it was first created or accessed inside or outside a function.

 

To access variables from global scope, add the keyword global.

 

--------------------

<?php

  echo test();//0

  echo "<br><br>";

  echo test();//1

   

  function test()

  {

    //declare a static variable

    static $count = 0;

    echo $count;

    $count++;

  }

?>

-----------------------

expressions is not allowed as static initializer.

 

PHP htmlentities function converts all characters into HTML entities.

 

There is no difference between ++$j and $j++ unless the value of $j is being tested, assigned to another variable, or passed as a parameter to a function. In such cases, ++$j increments $j before the test or other operation is performed, whereas $j++ performs the operation and then increments $j.

 

The echo and print commands are similar in that they are both constructs, except that print behaves like a PHP function and takes a single argument, while echo can take multiple arguments.

 

If you generate data within a function, you can convey the data to the rest of the program by returning a value or modifying a global variable.

 

 

The purpose of functions is to separate discrete sections of code into their own self-contained sections that can be referenced by a single function name.

--------------------

<?php

// declare a global variable;

  global $inti;

  $inti = 1;

  echo $inti;

  echo "<br>";

function increase_int(){

  //accessing and changing global variable from within function

  global $inti;

  $inti++;

  echo "function accessed<br>";

}

increase_int();

echo $inti;//output 2

?>

----------------------

In PHP the constant FALSE is defined as NULL, another predefined constant that denotes nothing.

 

A literal simply means something that evaluates to itself, such as the number 73 or the string "Hello". A variable, which we’ve already seen has a name beginning with a dollar sign, evaluates to the value that has been assigned to it. The simplest expression is just a single literal or variable, because both return a value.

 

NULL—or nothing—represents a value of FALSE.

 

In PHP, TRUE represents the value 1, and FALSE represents NULL, which can be thought of as “nothing” and is output as the empty string.

 

Function names are case-insensitive.

-------------------

<?php

//Returning multiple values in an array

  $names = fix_names("WILLIAM", "henry", "gatES");

  echo $names[0] . " " . $names[1] . " " . $names[2];

 

  function fix_names($n1, $n2, $n3)

  {

    $n1 = ucfirst(strtolower($n1));//将字符串改为首字母大写

    $n2 = ucfirst(strtolower($n2));

    $n3 = ucfirst(strtolower($n3));

 

    return array($n1, $n2, $n3);

  }

?>

------------

<?php

  $a1 = "WILLIAM";

  $a2 = "henry";

  $a3 = "gatES";

 

  echo $a1 . " " . $a2 . " " . $a3 . "<br>";

  fix_names($a1, $a2, $a3);

  echo $a1 . " " . $a2 . " " . $a3;

//passing parameters by reference.

  function fix_names(&$n1, &$n2, &$n3)

  {

    $n1 = ucfirst(strtolower($n1));

    $n2 = ucfirst(strtolower($n2));

    $n3 = ucfirst(strtolower($n3));

  }

?>

-----------------

Local variables are accessible just from the part of your code where you define them. If they’re outside of a function, they can be accessed by all code outside of functions, classes, and so on. If a variable is inside a function, only that function can access the variable, and its value is lost when the function returns.

Global variables are accessible from all parts of your code.

Static variables are accessible only within the function that declared them but retain their value over multiple calls.

------------------

If you keep putting bricks on top of each other, it might take a long time but eventually you’ll have a wall. This is where that faith I mentioned earlier comes in handy. If you believe that with time and patience you can figure the whole coding thing out, in time you almost certainly will. -- Cecily Carver

 

Static functions are useful for performing actions relating to the class itself, but not to specific instances of the class.

 

---------------------

By default, the initial MySQL user is root, and it will have a default password of mysql. So, to enter MySQL’s command-line interface, select Start→Run, enter CMD into the Run box, and press Return. This will call up a Windows command prompt. From there, enter the following (making any appropriate changes as just discussed):

cd C:\"Program Files (x86)\Ampps\mysql\bin"

mysql -u root -pmysql

注意:上面的命令结尾没有分号

The first command changes to the MySQL directory, and the second tells MySQL to log you in as user root, with the password mysql.

 

Table 8-2. MySQL’s six command prompts

MySQL prompt        Meaning

mysql>        Ready and waiting for a command

->        Waiting for the next line of a command

'>        Waiting for the next line of a string started with a single quote

">        Waiting for the next line of a string started with a double quote

`>        Waiting for the next line of a string started with a backtick

/*>        Waiting for the next line of a comment started with /*

 

If you are partway through entering a command and decide you don’t wish to execute it after all, whatever you do, don’t press Ctrl-C! That will close the program. Instead, you can enter \c and press Return.

 

SQL commands and keywords are case-insensitive. CREATE, create, and CrEaTe all mean the same thing. However, for the sake of clarity, you may prefer to use uppercase.

Table names are case-sensitive on Linux and macOS, but case-insensitive on Windows. So, for the sake of portability, you should always choose a case and stick to it. The recommended style is to use lowercase for table names.

----------------------

Example 8-1. Canceling a line of input

meaningless gibberish to mysql \c

--------------------

Table 8-3. Common MySQL commands

Command        Action

ALTER        Alter a database or table

BACKUP        Back up a table

\c        Cancel input

CREATE        Create a database

DELETE        Delete a row from a table

DESCRIBE        Describe a table’s columns

DROP        Delete a database or table

EXIT (Ctrl-C)        Exit

GRANT        Change user privileges

HELP (\h, \?)        Display help

INSERT        Insert data

LOCK        Lock table(s)

QUIT (\q)        Same as EXIT

RENAME        Rename a table

SHOW        List details about an object

SOURCE        Execute a file

STATUS (\s)        Display the current status

TRUNCATE        Empty a table

UNLOCK        Unlock table(s)

UPDATE        Update an existing record

USE        Use a database

---------------------

CREATE DATABASE publications;//creating a database named "publications"

USE publications;//working on the newly created database

 

---------------------

 

 -------------

Table 8-4. Example parameters for the GRANT command

Arguments        Meaning

*.*        All databases and all their objects

database.*        Only the database called database and all its objects

database.object        Only the database called database and its object called object

 

GRANT ALL ON publications.* TO 'jim'@'localhost'

  IDENTIFIED BY 'mypasswd';

What this does is allow the user jim@localhost full access to the publications database using the password mypasswd. You can test whether this step has worked by entering quit to exit and then rerunning MySQL the way you did before, but instead of entering -u root -p, type -u jim -p, or whatever username you created. See Table 8-5 for the correct command for your operating system. Modify it as necessary if the mysql client program is installed in a different directory on your system.

 

Be aware that if you create a new user but do not specify an IDENTIFIED BY clause, the user will have no password, a situation that is very insecure and should be avoided.

------------------

entering quit to exit

------------------

 

 

Example 8-3. Creating a table called classics

CREATE TABLE classics (

 author VARCHAR(128),

 title VARCHAR(128),

 type VARCHAR(16),

 year CHAR(4)) ENGINE InnoDB;

 

To check whether your new table has been created, type the following:

DESCRIBE classics;

 

The term VARCHAR stands for VARiable length CHARacter string, and the command takes a numeric value that tells MySQL the maximum length allowed for a string stored in this field.

 

Another feature of character and text columns, important for today’s global web reach, is character sets. These assign particular binary values to particular characters. The character set you use for English is obviously different from the one you’d use for Russian. You can assign the character set to a character or text column when you create it.

 

Be aware that if you ever attempt to assign a string value longer than the length allowed, it will be truncated to the maximum length declared in the table definition.

 

The YEAR data type supports only the years 0000 and 1901 through 2155. This is because MySQL stores the year in a single byte for reasons of efficiency, but it means that only 256 years are available.

 

The BINARY data types (see Table 8-7) store strings of bytes that do not have an associated character set. For example, you might use the BINARY data type to store a GIF image.

 

MySQL indexes only the first n characters of a TEXT column (you specify n when you create the index). What this means is that VARCHAR is the better and faster data type to use if you need to search the entire contents of a field.

 

The term BLOB stands for Binar Large OBject, and therefore, as you would think, the BLOB data type is most useful for binary data in excess of 65,536 bytes in size. The main other difference between the BLOB and BINARY data types is that BLOBs cannot have default values.

 

Floating-point values (of any precision) may only be signed.

 

The DATETIME and TIMESTAMP data types display the same way. The main difference is that TIMESTAMP has a very narrow range (from the years 1970 through 2037), whereas DATETIME will hold just about any date you’re likely to specify, unless you’re interested in ancient history or science fiction.

 

Example 8-5. Adding the auto-incrementing column id

ALTER TABLE classics ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT KEY;

 

Example 8-7. Removing the id column

ALTER TABLE classics DROP id;

------------------

Example 8-8. Populating the classics table

 

INSERT INTO classics(author, title, type, year)

 VALUES('Mark Twain','The Adventures of Tom Sawyer','Fiction','1876');

INSERT INTO classics(author, title, type, year)

 VALUES('Jane Austen','Pride and Prejudice','Fiction','1811');

INSERT INTO classics(author, title, type, year)

 VALUES('Charles Darwin','The Origin of Species','Non-Fiction','1856');

INSERT INTO classics(author, title, type, year)

 VALUES('Charles Dickens','The Old Curiosity Shop','Fiction','1841');

INSERT INTO classics(author, title, type, year)

 VALUES('William Shakespeare','Romeo and Juliet','Play','1594');

 ----------------

 

 displaying the table's contents:

 

 SELECT * FROM classics;

 

 --------------------

 

 Renaming a table;to change the name of the table classics to pre1900, you would use the following command:

 

 ALTER TABLE classics RENAME pre1900;

 

 -----------------

 Changing the data type of a column:

 

 ALTER TABLE classics MODIFY year SMALLINT;

 ------------------

 Adding a new column:

 

 ALTER TABLE classics ADD pages SMALLINT UNSIGNED;

 -----------------

 Renaming a column:

 

 ALTER TABLE classics CHANGE type category VARCHAR(16);

 --------------

 Removing a column:

 

 ALTER TABLE classics DROP pages;

 --------------------

 Example 8-9. Creating, viewing, and deleting a table

CREATE TABLE disposable(trash INT);

DESCRIBE disposable;

DROP TABLE disposable;

SHOW tables;

-----------------

Example 8-10. Adding indexes to the classics table

ALTER TABLE classics ADD INDEX(author(20));

ALTER TABLE classics ADD INDEX(title(20));

ALTER TABLE classics ADD INDEX(category(4));

ALTER TABLE classics ADD INDEX(year);

DESCRIBE classics;

---------------

An alternative to using ALTER TABLE to add an index is to use the CREATE INDEX command. They are equivalent, except that CREATE INDEX cannot be used for creating a PRIMARY KEY.

 

Example 8-11. These two commands are equivalent

ALTER TABLE classics ADD INDEX(author(20));

CREATE INDEX author ON classics (author(20));

--------------

Example 8-12. Creating the table classics with indexes

CREATE TABLE classics (

 author VARCHAR(128),

 title VARCHAR(128),

 category VARCHAR(16),

 year SMALLINT,

 INDEX(author(20)),

 INDEX(title(20)),

 INDEX(category(4)),

 INDEX(year)) ENGINE InnoDB;

 ---------------

 Deleting a table:

 DROP TABLE classics1;

 ------------------

 All values must be unique in any column having a primary key index.

 

 Example 8-13. Populating the isbn column with data and using a primary key

ALTER TABLE classics ADD isbn CHAR(13);

UPDATE classics SET isbn='9781598184891' WHERE year='1876';

UPDATE classics SET isbn='9780582506206' WHERE year='1811';

UPDATE classics SET isbn='9780517123201' WHERE year='1856';

UPDATE classics SET isbn='9780099533474' WHERE year='1841';

UPDATE classics SET isbn='9780192814968' WHERE year='1594';

ALTER TABLE classics ADD PRIMARY KEY(isbn);

DESCRIBE classics;

------------------

 

Example 8-14. Creating the table classics with a primary key

CREATE TABLE classics (

 author VARCHAR(128),

 title VARCHAR(128),

 category VARCHAR(16),

 year SMALLINT,

 isbn CHAR(13),

 INDEX(author(20)),

 INDEX(title(20)),

 INDEX(category(4)),

 INDEX(year),

 PRIMARY KEY (isbn)) ENGINE InnoDB;

 --------------------

 Example 8-15. Adding a FULLTEXT index to the table classics

ALTER TABLE classics ADD FULLTEXT(author,title);

------------

Example 8-16. Two different SELECT statements

SELECT author,title FROM classics;

SELECT title,isbn FROM classics;

------------

Example 8-17. Counting rows

SELECT COUNT(*) FROM classics;

-------------

Example 8-19. With and without the DISTINCT qualifier

SELECT author FROM classics;

SELECT DISTINCT author FROM classics;

------------

Example 8-20. Removing the new entry

DELETE FROM classics WHERE title='Little Dorrit';

-------------

Example 8-21. Using the WHERE keyword

SELECT author,title FROM classics WHERE author="Mark Twain";

SELECT author,title FROM classics WHERE isbn="9781598184891";

-----------

Example 8-22. Using the LIKE qualifier

SELECT author,title FROM classics WHERE author LIKE "Charles%";

SELECT author,title FROM classics WHERE title LIKE "%Species";

SELECT author,title FROM classics WHERE title LIKE "%and%";

-------------

Example 8-23. Limiting the number of results returned

SELECT author,title FROM classics LIMIT 3;

SELECT author,title FROM classics LIMIT 1,2;

SELECT author,title FROM classics LIMIT 3,1;

---------------

Example 8-24. Using MATCH...AGAINST on FULLTEXT indexes

SELECT author,title FROM classics

 WHERE MATCH(author,title) AGAINST('and');

SELECT author,title FROM classics

 WHERE MATCH(author,title) AGAINST('curiosity shop');

SELECT author,title FROM classics

 WHERE MATCH(author,title) AGAINST('tom sawyer');

 ---------------

 Example 8-25. Using MATCH...AGAINST in Boolean mode

SELECT author,title FROM classics

 WHERE MATCH(author,title)

 AGAINST('+charles -species' IN BOOLEAN MODE);

SELECT author,title FROM classics

 WHERE MATCH(author,title)

 AGAINST('"origin of"' IN BOOLEAN MODE);

 ---------

 Example 8-26. Using UPDATE...SET

UPDATE classics SET author='Mark Twain (Samuel Langhorne Clemens)'

 WHERE author='Mark Twain';

UPDATE classics SET category='Classic Fiction'

 WHERE category='Fiction';

 -----------

 Example 8-27. Using ORDER BY

SELECT author,title FROM classics ORDER BY author;

SELECT author,title FROM classics ORDER BY title DESC;

SELECT author,title,year FROM classics ORDER BY author,year DESC;

------------

SELECT category,COUNT(author) FROM classics GROUP BY category;

-----------

Example 8-28. Creating and populating the customers table

CREATE TABLE customers (

 name VARCHAR(128),

 isbn VARCHAR(13),

 PRIMARY KEY (isbn)) ENGINE InnoDB;

INSERT INTO customers(name,isbn)

 VALUES('Joe Bloggs','9780099533474');

INSERT INTO customers(name,isbn)

 VALUES('Mary Smith','9780582506206');

INSERT INTO customers(name,isbn)

 VALUES('Jack Wilson','9780517123201');

SELECT * FROM customers;

----------

Example 8-29. Joining two tables into a single SELECT

SELECT name,author,title FROM customers,classics

 WHERE customers.isbn=classics.isbn;

 ------------

 NATURAL JOIN takes two tables and automatically joins columns that have the same name.

 

 SELECT name,author,title FROM customers NATURAL JOIN classics;

 -------------

 SELECT name,author,title FROM customers

 JOIN classics ON customers.isbn=classics.isbn;

 ----------

 You can also save yourself some typing and improve query readability by creating aliases using the AS keyword. Simply follow a table name with AS and the alias to use.

 

 SELECT name,author,title from

 customers AS cust, classics AS class WHERE cust.isbn=class.isbn;

 -----------

 You can also use AS to rename a column (whether or not joining tables), like this:

SELECT name AS customer FROM customers ORDER BY customer;

-------------

Example 8-30. Using logical operators

SELECT author,title FROM classics WHERE

 author LIKE "Charles%" AND author LIKE "%Darwin";

SELECT author,title FROM classics WHERE

 author LIKE "%Mark Twain%" OR author LIKE "%Samuel Langhorne Clemens%";

SELECT author,title FROM classics WHERE

 author LIKE "Charles%" AND author NOT LIKE "%Darwin";

 --------------

Example 9-1. Creating a transaction-ready table

CREATE TABLE accounts (

 number INT, balance FLOAT, PRIMARY KEY(number)

 ) ENGINE InnoDB;

DESCRIBE accounts;

-----------

Example 9-2. Populating the accounts table

INSERT INTO accounts(number, balance) VALUES(12345, 1025.50);

INSERT INTO accounts(number, balance) VALUES(67890, 140.00);

SELECT * FROM accounts;

------------

Example 9-3. A MySQL transaction

BEGIN;

UPDATE accounts SET balance=balance+25.11 WHERE number=12345;

COMMIT;

SELECT * FROM accounts;

-----------

When you are satisfied that a series of queries in a transaction has successfully completed, issue a COMMIT command to commit all the changes to the database. Until it receives a COMMIT, MySQL considers all the changes you make to be merely temporary. This feature gives you the opportunity to cancel a transaction by not sending a COMMIT but issuing a ROLLBACK command instead.

-------------

Example 9-4. A funds transfer transaction

BEGIN;

UPDATE accounts SET balance=balance-250 WHERE number=12345;

UPDATE accounts SET balance=balance+250 WHERE number=67890;

SELECT * FROM accounts;

------------

Example 9-5. Canceling a transaction using ROLLBACK

ROLLBACK;

SELECT * FROM accounts;

-----------

Example 9-6. Using the EXPLAIN command

EXPLAIN SELECT * FROM accounts WHERE number='12345';

------------

Alternatively, you can lock the tables you are backing up before running mysqldump. To lock tables for reading (as we want to read the data), from the MySQL command line issue this command:

LOCK TABLES tablename1 READ, tablename2 READ ...

Then, to release the lock(s), enter the following:

UNLOCK TABLES;

-----------

exit MySQL by using:

exit;

-------------

The basic format of the mysqldump command is shown here:

mysqldump -u user -ppassword database

注意:结尾没有分号

-----------

Example 9-8. Dumping the publications database to a file

mysqldump -u user –p password publications > publications.sql

-----------

Backing up a single table

To back up only a single table from a database (such as the classics table from the publications database), you should first lock the table from within the MySQL command line, by issuing a command such as the following:

LOCK TABLES publications.classics READ;

This ensures that MySQL remains running for read purposes, but writes cannot be made. Then, while keeping the MySQL command line open, use another terminal window to issue the following command from the operating system command line:

mysqldump -u user -ppassword publications classics > classics.sql

You must now release the table lock by entering the following command from the MySQL command line in the first terminal window, which unlocks all tables that have been locked during the current session:

UNLOCK TABLES;

---------------

 

Example 9-7. Dumping the publications database to screen

mysqldump -u user -ppassword publications

 

-------------------------

 

Backing up a single table

To back up only a single table from a database (such as theclassics table from the publications database), you should first lock the table from within the MySQL command line, by issuing a command such as the following:

LOCK TABLES publications.classics READ;

This ensures that MySQL remains running for read purposes, 

but writes cannot be made. Then, while keeping the MySQL command line open, use another terminal window to issue the following command from the operating system command line:

mysqldump -u user -ppassword publications classics > classics.sql

You must now release the table lock by entering the following command from the MySQL command line in the first terminal window, which unlocks all tables that have been locked during the current session:

UNLOCK TABLES;

 

 

------------------------

Example 9-9. Dumping all the MySQL databases to file

mysqldump -u user -ppassword --all-databases > all_databases.sql

----------------

 

Restoring from a Backup File

To perform a restore from a file, call the mysql executable, passing it the file to restore from using the < symbol. So, to recover an entire database that you dumped using the --all-databases option, use a command such as that in Example 9-10.

 

Example 9-10. Restoring an entire set of databases

mysql -u user -ppassword < all_databases.sql

 

To restore a single database, use the -D option followed by the name of the database, as in Example 9-11, where the publications database is being restored from the backup made in Example 9-8.

 

Example 9-11. Restoring the publications database

mysql -u user -ppassword -D publications < publications.sql

To restore a single table to a database, use a command such as that in

 

Example 9-12, where just the classics table is being restored to the publications database.

Example 9-12. Restoring the classics table to the publications database

mysql -u user -ppassword -D publications < classics.sql

-----------------

Example 9-13. Dumping data to CSV-format files

mysqldump -u user -ppassword --no-create-info --tab=c:/temp

  --fields-terminated-by=',' publications

---------------

<?php // login.php

  $hn = 'localhost';

  $db = 'publications';

  $un = 'username'; // Change this

  $pw = 'password'; // Change this

?>

------------

Example 10-2. Connecting to a MySQL server with mysqli

<?php

  require_once 'login.php';

  $conn = new mysqli($hn, $un, $pw, $db);

  if ($conn->connect_error) die("Fatal Error");

?>

 

The -> operator indicates that the item on the right is a property or method of the object on the left.

------------

each row can be fetched in its entirety via the fetch_array method

-------------------------

heredoc (or here-document) is a way of quoting large amounts of texts in shells and programming languages. It preserves the line breaks and other formatting of the literal text; some implementations allow variables to be interpolated, the quoted text to be executed as commands, or leading tabs to be stripped. The general syntax is << followed by an identifier, followed, starting on the next line, by the text to be quoted, and then closed by the same identifier on it's own line. Both bourne shell and bash have heredocs as a way of providing input to commands. PHP and Perl also have implementations of heredocs.

----------

Example 10-7. Creating a table called cats

<?php

  require_once 'login.php';

  $conn = new mysqli($hn, $un, $pw, $db);

  if ($conn->connect_error) die("Fatal Error");

 

  $query = "CREATE TABLE cats (

    id SMALLINT NOT NULL AUTO_INCREMENT,

    family VARCHAR(32) NOT NULL,

    name VARCHAR(32) NOT NULL,

    age TINYINT NOT NULL,

    PRIMARY KEY (id)

  )";

 

  $result = $conn->query($query);

  if (!$result) die ("Database access failed");

?>

------------

Example 10-17. How to safely access MySQL with user input

<?php

  require_once 'login.php';

  $conn = new mysqli($hn, $un, $pw, $db);

  if ($conn->connect_error) die("Fatal Error");

 

  $user  = mysql_fix_string($conn, $_POST['user']);

  $pass  = mysql_fix_string($conn, $_POST['pass']);

  $query = "SELECT * FROM users WHERE user='$user' AND pass='$pass'";

 

  // Etc.

 

  function mysql_fix_string($conn, $string)

  {

    if (get_magic_quotes_gpc()) $string = stripslashes($string);

    return $conn->real_escape_string($string);

  }

?>

-----------------

A Binary Large Object (or BLOB) is a collection of binary data stored as a single entity in a database management system. BLOBs are typically images, audio or other multimedia objects, though sometimes binary code is stored as a BLOB.

-----------

Example 10-19. Issuing prepared statements

<?php

  require_once 'login.php';

  $conn = new mysqli($hn, $un, $pw, $db);

  if ($conn->connect_error) die("Fatal Error");

 

  $stmt = $conn->prepare('INSERT INTO classics VALUES(?,?,?,?,?)');

  $stmt->bind_param('sssss', $author, $title, $category, $year, $isbn);

 

  $author   = 'Emily Brontë';

  $title    = 'Wuthering Heights';

  $category = 'Classic Fiction';

  $year     = '1847';

  $isbn     = '9780553212587';

 

  $stmt->execute();

  printf("%d Row inserted.\n", $stmt->affected_rows);

  $stmt->close();

  $conn->close();

?>

------------------

Example 10-20. Functions for preventing both SQL and XSS injection attacks

<?php

  function mysql_entities_fix_string($conn, $string)

  {

    return htmlentities(mysql_fix_string($conn, $string));

  }

 

  function mysql_fix_string($conn, $string)

  {

    if (get_magic_quotes_gpc()) $string = stripslashes($string);

    return $conn->real_escape_string($string);

  }

?>

-----------------

Example 11-5. Submitting multiple values with an array

   Vanilla <input type="checkbox" name="ice[]" value="Vanilla">

 Chocolate <input type="checkbox" name="ice[]" value="Chocolate">

Strawberry <input type="checkbox" name="ice[]" value="Strawberry">

----------------

session variables are stored on the server (unlike cookies, which are stored in the web browser) and can therefore be trusted.

 

Instead of the $_POST array, forms can easily be changed to use the GET method. Reasons to do this might include making the result of a search bookmarkable or directly linkable from another page.

 

Alt-Left arrow and Alt-Right arrow move backward and forward within the browsing history.

 类似资料: