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

VBA Automation for Excel 2019 Cookbook by Mike Van Niekerk VBA Automation for Excel 2019 Cookbook Solutions to automate tasks and increase productivity with Excel and other MS Office applications By Mike Van Niekerk The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/VBA-Aut 阅读详情

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.

Learning Web Design by Jennifer Niederst Robbins Learning Web Design A BEGINNER’S GUIDE TO HTML, CSS,JAVASCRIPT, AND WEB GRAPHICS Jennifer Niederst Robbins My GitHub Files: https://github.com/Li-YangZhong/Learning_Web_Design_Book_by_Jennife... 阅读详情

相关推荐

You Don't Know JS Yet (book series) - 2nd Edition by Kyle Simpson

You Don’t Know JS Yet (book series) - 2nd Edition 全文阅读地址From https://github.com/getify/You-Dont-Know-JS 我的GitHub文件: https://github.com/Li-YangZhong/Kyle_Simpson_You_Don-t_Know_JS_Yet_-Get_Started.git...

CodingIsFun 2175

167条你没见过的IDEA操作技巧(英文文档加翻译)

下面有部分没有翻译,仅作参考:1.To open any class in the editor quickly, press Ctrl+N (Navigate | Class) and start typing the name of the class. Choose the class from a drop-down list that appears.要快速打开编辑器中的任何类,请按Ct...

qq_32851113的博客 2万+

《Beginning C++17》-学习笔记-Chapter 01-Basic Ideas

书名:Beginning C++17 - From Novice to Professional 作者:Ivor Horton, Peter Van Weert 笔记: Blocks can be placed inside other blocks—this concept is called nesting. Blocks can be nested, one within anothe...

CodingIsFun 674

数组的初始化 array initializer is not allowed here

此处不允许使用数组初始值设定项 array initializer is not allowed here 数组的使用分声明和初始化两部分,两者可同时进行,也可分开进行 int[] array; 声明 array = new int{element1,element2,element3..}; 初始化方式1 array = new int[length]; 初始化方式2 数组...

Mr_moving 2万+

Beginning Git and GitHub by Mariot Tsitoara

Beginning Git and GitHub A Comprehensive Guide to Version Control, Project Management, and Teamwork for the New Developer Mariot Tsitoara $ git init # Initialize a new git database $ git clone # Copy an existing database $ git status # Check the status

CodingIsFun 623

OCV/AOCV/SOCV的介绍和应用

library中的cell delay是在某个固定的PVT(operating condition)下仿真得出的。,cell的delay并不是一个固定值,而是一个随机值,遵循高斯分布或门特卡洛分布,在STA中用OCV来模拟这一『特征』。OCV全称on chip variation,用于描述不同管子间由于工艺偏差、电压降、温度变化引起的delay变化。,也用于描述工艺偏差引起的net厚度宽度的变化从而导致net的电容电阻变化。优点:设置起来比较简单粗暴,对于不那么先进的工艺可行!的影响,更贴合实际。

m0_61003348的博客 8984

IntelliJ IDEA快捷键

Search Everywhere  Double Shirt Go to File  Ctrl+Shift+N Recent Files  Ctrl+E Navigation Bar  Alt+Home The Code Completion feature lets you quickly complete different kinds of stat

xiaonaughty的博客 1万+

为什么你的SiC MOSFET仿真不准?可能是离子注入的‘沟道效应’在捣鬼(Silvaco BCA模块详解)

本文深入分析了SiC MOSFET仿真中离子注入沟道效应的关键影响,揭示了Silvaco BCA模块在模拟SiC晶向和角度参数时的核心设置要点。通过详细解析晶圆偏切与注入角度的等效关系,提供优化MOSFET沟道区注入仿真的五步实战方法,帮助工程师将阈值电压仿真误差从26%降低到5%以内。

weixin_26789847的博客 410

mysql与php6_PHP MySQL和JavaScript入门经典 第6版

第1部分:Web应用基础知识第1章 理解Web的工作方式 31.1 HTML和WWW简史 41.2 创建Web内容 41.3 理解Web内容递送 51.4 选择Web托管提供商 71.5 利用多种Web浏览器执行测试 81.6 创建一个示例文件 91.7 使用FTP传输文件 101.7.1 选择FTP客户端 101.7.2 使用FTP客户端 111.8 了解在Web服务器上放置文件的位置 131....

weixin_39977776的博客 410

osgearth2.10 demo功能介绍

osgearth-2.10 demo: 说明: 1、运行环境win7 x64 旗舰版,CPU i5-6400 8核,8G内存; 2、括号内是对应demo的测试参数(.earth); 3、配置OSG_FILE_PATH; 4、参数命令行可以查看各个demo需要的输入参数; 5、前缀说明:gui界面程序、cmd控制台程序、non功能未知; 6、程序后括号里的non表示不需要通过命令行输入参数; 示例: 1、gui:osgearth_3pv(simple.earth):相机与地球的投影关系,Range表示相机

rach09的专栏 2425

OPNET网络仿真实验

外网

嚴 帅的博客 1万+

pycharm每日一贴中英文对照(机器翻译)

1.To quickly select the currently edited element (class, file, method or field) in any view (Project view, Structure view or other), press Alt+F1. 要在任何视图(项目视图、结构视图或其他视图)中快速选择当前编辑的元素(类、文件、方法或字段),请按Alt...

grmrh的博客 5494

电磁场仿真软件:COMSOL Multiphysics_(17).时域与频域分析

时域和频域分析是电磁场仿真中非常重要的两种方法,每种方法都有其独特的应用场景和优势。时域分析适用于瞬态响应和宽带信号的分析,而频域分析则适用于稳态响应和窄带信号的分析。在COMSOL Multiphysics中,通过合理设置物理场接口、材料属性、边界条件、网格划分和求解器,可以高效地进行这两种分析,并通过傅里叶变换将时域结果转换为频域结果,进一步拓展仿真应用的范围。合理的性能优化措施,如网格划分优化和并行计算,可以显著提高仿真的效率和准确性。

kkchenjj的博客 1978

TS错误信息列表

错误信息列表code类型英文描述中文描述1002错误Unterminated string literal.未终止的字符串文本。1003错误Identifier expected.应为标识符。1005错误'{0}' expected.应为“{0}”。1006错误A file cannot have a reference to itself.文件不能引用自身。1009错误Trailing comm...

Jinmy的博客 9万+

软件崩溃时Visual Studio中看不到有效的调用堆栈,使用Windbg动态调试去分析定位

当在Visual Studio中遇到软件崩溃且无法查看详细调用堆栈时,可以使用Windbg进行动态调试去分析定位问题。

dvlinker的技术专栏 1万+

复合材料仿真PAM-COMPOSITE 全工艺案例实操参数模板

复合材料仿真PAM-COMPOSITE 全工艺案例实操参数模板

源代码杀手的博客 281

Microsoft Excel 2019 Pivot Table Data Crunching by Bill Jelen and Michael Alexander

About the companion content The download files for this book include all of the data sets used to produce the book, so you can practice the concepts in the book. You can download this book’s companion content from the following page: MicrosoftPressStore.co

CodingIsFun 989

YOLOv8【第十一章:视频追踪与流处理篇·第3节】匈牙利算法(Hungarian Algorithm)与 KM 算法匹配机制详解!

🏆 本文收录于 《YOLOv8实战:从入门到深度优化》 专栏。该专栏系统复现并梳理全网各类 YOLOv8 改进与实战案例(当前已覆盖分类 / 检测 / 分割 / 追踪 / 关键点 / OBB 检测等方向),坚持持续更新 + 深度解析,质量分长期稳定在 97 分以上,可视为当前市面上 覆盖较全、更新较快、实战导向极强 的 YOLO 改进系列内容之一。

**My Coding Family** 450

《C++ Without Fear》学习笔记

书名:C++ Without Fear A Beginner’s Guide That Makes You Feel Smart 作者:Brian Overland 阅读时间:2018/10/6-2018/10/20 书摘+书评: An important rule of good programming style is that variables should usually...

CodingIsFun 832

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Learning JavaScript - JavaScript Essentials for Modern Application Development by Ethan Brown

Learning JavaScript JAVASCRIPT ESSENTIALS FOR MODERN APPLICATION DEVELOPMENT by Ethan Brown I certainly hold no animosity toward amateurs: everyone has to start somewhere, programming is a profitabl...

CodingIsFun 700

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

Flexbox in CSS: Understanding CSS Flexible Box Layout by Estelle Weyl

”礼让三先“就是遇到通行困难的情况下要礼貌让行,要先慢、先让、先停。“宁停三分,不抢一秒”是从无数血的教训中总结出来的宝贵经验。 Live examples are available at http://standardista.com/flexbox/flexfiles. You can either click the icon while reading this book to go directly to a live version of the code example reference

CodingIsFun 449

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

Webpack for Beginners

Your Step-by-Step Guide to Learning Webpack 4 by Mohamed Bouzid 源代码: https://gitee.com/liyangzhong/webpack_beginners.git https://github.com/Li-YangZhong/webpack_beginners.git Once you are in the webpack_beginners folder, use the following command to ini

CodingIsFun 446

What Every Web Developer Should Know About HTTP By K. Scott Allen

In fact, these days many web sites try to avoid having any sort of real file name in their URL. For starters, file names are usually associated with a specific technology, like the .aspx file extension for Microsoft’s ASP.NET technology. Many URLs will out

CodingIsFun 394
上一篇: How to Manually Upgrade WordPress, Themes & Plugins 如何手动升级WordPress, 主题和插件
下一篇: 辞海拾遗
CodingIsFun
博客等级 码龄8年 37粉丝 240原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值