Learning PHP, MySQL, JavaScript, CSS & HTML5
How many properties and how many methods does an XMLHttpRequest object have?
An XMLHttpRequest object has six properties and six methods (see Tables 18-1 and18-2).
Given a pair of CSS rules with equal precedence, how can you make one have greater precedence over the other?
Given a pair of CSS declarations with equal precedence, to make one have greater precedence over the other, you append the !important declaration to it, like this: p { color:#ff0000 !important; }
6. What benefit does a FULLTEXT index provide?
A FULLTEXT index enables natural-language queries to find keywords, wherever they are in the FULLTEXT column(s), in much the same way as using a search engine.
Using regular expressions, write a JavaScript function to test whether the word fox exists in the string The quick brown fox.
A JavaScript function using regular expressions to test whether the word fox exists in the string "The quick brown fox" could be:document.write(/fox/.test("The quick brown fox"))
Using regular expressions, write a PHP function to replace all occurrences of the word the in The cow jumps over the moon with the word my.
A PHP function using a regular expression to replace all occurrences of the word the in "The cow jumps over the moon" with the word my could be: $s=preg_replace("/the/i", "my", "The cow jumps over the moon");
What is a PHP session?
A PHP session is a group of variables unique to the current user.
How can you draw a complex curve with two imaginary attractors?
A complex curve with two imaginary attractors is called a Bézier curve. To create one, call the bezierCurveTo method, supplying two pairs of x and y coordinates for the attractors, followed by another pair for the end point of the curve. A curve is then created from the current drawing location to the destination.
How is an object different from a function?
A function is a set of statements referenced by a name that can receive and return values. An object may contain zero or many functions (which are then called meth‐ods) as well as variables (which are called properties), all combined in a single unit.
Write a regular expression to match any single word followed by any nonword character.
A regular expression to match any single word followed by any nonword character could be /\w+\W/g.
Write a regular expression to match either of the words fox or fix.
A regular expression to match either of the words fox or fix could be /f[oi]x/.
Write a statement to sort an array of numbers in descending numerical order.
A statement to sort an array of numbers into descending numerical order would look like this: numbers.sort(function(a, b){ return b - a })
What is a stopword?
A stopword is a word that is so common that it is considered not worth including in a FULLTEXT index or using in searches. However, it does participate in a search when it is part of a larger string bounded by double quotes.
What four components (at the minimum) are needed to create a fully dynamic web page?
A web server (such as Apache), a server-side scripting language (PHP), a database (MySQL), and a client-side scripting language (JavaScript).
Which character must be placed at the end of every PHP statement?
All PHP statements must end with a semicolon (;).
By default, to which part of a document will JavaScript code output?
By default, JavaScript code will output to the part of the document in which it resides. If it's in the head, it will output to the head; if in the body, it outputs to the body.
Why must a cookie be transferred at the start of a program?
Cookies should be transferred before a web page's HTML, because they are sent as part of the headers.
What negative effects can happen if you do not close the objects created by mysqli methods?
If you neglect to properly close objects created with mysqli methods, your programs carry the risk of running out of memory, especially on high-traffic websites. If there's a program flow logic error in your code, it also ensures you won't accidentally access old results.
In CSS rules, what is the purpose of the semicolon?
In CSS, the semicolon is used as a separator between declarations.
Which character is used by CSS to represent any element?
In CSS, you can match any element using the * universal selector.
Which HTML5 technology supports running background JavaScript tasks?
In HTML5 you can set up web workers to carry on background tasks for you. These workers are simply sections of JavaScript code.
What feature is new in HTML5 and offers greater capability than cookies?
In HTML5, local storage offers far greater access to local user space than cookies, which are limited in the amount of data they can hold.
Which characters are used to prefix (a) IDs, and (b) class names in a CSS rule?
In a CSS declaration, ID names are prefixed with a # character (e.g., #myid), and class names with a . character (e.g., .myclass).
Why is a for loop more powerful than a while loop?
Loops using for statements are more powerful than while loops, because they support two additional parameters to control loop handling.
What HTML attribute is used to precomplete form fields with a value?
The HTML attribute used to precomplete form fields with a value is value, which is placed within an <input> tag and takes the form value="value".
What are the O, S, and C functions provided to do?
The O function returns an object by its ID, the S function returns the style property of an object, and the C function returns an array of all objects that access a given class.
Which PHP function escapes a string, making it suitable for use with MySQL?
The PHP function that escapes characters in a string, making it suitable for use with MySQL, is mysql_real_escape_string.
You can submit form data using either the POST or the GET method. Which asso‐ciative arrays are used to pass this data to PHP?
The associative arrays used to pass submitted form data to PHP are $_GET for the GET method and $_POST for the POST method.
What is the best way to force your own operator precedence?
The best way to force your own operator precedence is to surround the parts of an expression to be evaluated first with parentheses.
Which two JavaScript commands will make the browser load the previous page in its history array?
The commands to change to the previous page in the browser's history array are: history.back() history.go(-1)
What is the difference between a CSS ID and a CSS class?
The difference between a CSS ID and a CSS class is that an ID is applied to only a single element, whereas a class can be applied to many elements.
What is the difference between a text box and a text area?
The difference between a text box and a text area is that although they both accept text for form input, a text box is a single line, whereas a text area can be multiple lines and include word wrapping.
Which JavaScript function is the equivalent of echo or print in PHP?
The equivalent of the echo and print commands used in PHP is the JavaScript document.write function (or method).
Name the four functions with which you can specify CSS colors.
The four functions with which you can specify CSS colors are hsl, hsla, rgb, and rgba; for example: color:rgba(0%,60%,40%,0.4);
How many items of data per pixel are returned by the getImageData method?
The getImageData method returns an array containing the specified pixel data, with the elements consecutively containing the red, green, blue, and alpha pixel values, so four items of data are returned per pixel.
Why is the hash function a powerful security measure?
The hash function is a powerful security measure, because it is a one-way function that converts a string to a 32-character hexadecimal number that cannot be con‐verted back, and is therefore almost uncrackable.
When is the mysql_result function not optimal?
The mysql_result function is not optimal when more than one cell is being re‐quested, because it fetches only a single cell from a database and therefore has to be called multiple times, whereas mysql_fetch_row will fetch an entire row.
What is the term for the process of removing duplicate data and optimizing tables?
The process of removing duplicate data and optimizing tables is called normaliza‐tion.
What is the purpose of microdata?
The purpose of microdata is to make information more easily understandable by computer programs, such as search engine
What is the purpose of the try ... catch construct?
The purpose of the try ... catch construct is to set an error trap for the code inside the try statement. If the code causes an error, the catch section will be ex‐ecuted instead of a general error being issued.
What is register_globals, and why is it a bad idea?
The register_globals setting was the default in versions of PHP prior to 4.2.0. It was not a good idea, because it automatically assigned submitted form field data to PHP variables, thus opening up a security hole for potential hackers who could attempt to break into PHP code by initializing variables to values of their choice.
What XMLHttpRequest object's property returns an Ajax text response?
The responseText property of an XMLHttpRequest object contains the value re‐turned by a successful Ajax call.
What XMLHttpRequest object's property returns an Ajax XML response?
The responseXML property of an XMLHttpRequest object contains a DOM tree created from the XML returned by a successful Ajax call.
How can you create gradient fills of more than two colors?
To create a gradient fill (either radial or linear) with more than two colors, specify all the colors required as stop colors assigned to a gradient object you have already created, and assign them each a starting point as a percent value of the complete gradient (between 0 and 1), like this: gradient.addColorStop(0, 'green') gradient.addColorStop(0.3, 'red') gradient.addColorStop(0,79, 'orange') gradient.addColorStop(1, 'brown')
How can you create a multidimensional array?
To create a multidimensional array, place subarrays inside the main array.
Which JavaScript function creates new elements, and which appends them to the DOM?
To create a new element, use code such as: elem = document.createElement('span') To add the new element to the DOM, use code such as: document.body.appendChild(elem)
How can you destroy a cookie?
To destroy a cookie, reissue it with set_cookie, but set its expiration date in the past.
How can you ensure that an input is completed before a form gets submitted?
To ensure that a form is not submitted with missing data, you can apply the required attribute to essential inputs.
Which method would you use to specify a section of a camera such that future drawing takes place only within that area?
To ensure that future drawing takes place only within a certain area, you can create a path and then call the clip method.
What method can you call to erase all local storage data for the current domain?
To erase all local storage data for the current domain, you can call the localStor age.clear method.
How can you flow text over multiple columns?
To flow text over multiple columns, you use the column-count, column-gap, and column-rule properties or their browser-specific variants, like this: column-count:3; column-gap :1em; column-rule :1px solid black;
How do you give JavaScript access to a canvas element?
To give JavaScript access to a canvas element, ensure the element has been given an ID such as mycanvas, and then use the document.getElementdById function (or the O function from the OSC.js file supplied on the companion website) to return an object to the element. Finally, call getContext on the object to retrieve a 2D context to the canvas, like this: canvas = document.getElementById('mycanvas') context = canvas.getContext('2d')
2. Which two audio codecs should you use to guarantee maximum playability on all platforms?
To guarantee maximum audio playability on all platforms, you should use the OGG codec plus either the ACC or MP3 codec.
Which two video codecs should you use to guarantee maximum playability on all platforms?
To guarantee maximum video playability on all platforms, you should use the MP4/ H.264 codec, and the OGG/Theora or VP8 codec to support the Opera browser.
What HTML tag can you use to import a style sheet into a document?
To import a style sheet into a document, you can use the HTML <link> tag, like this:<link rel='stylesheet' type='text/css' href='styles.css'>
Which directive do you use to import one style sheet into another (or the <style> section of some HTML)?
To import one style sheet into another, you use the @import directive like this: @import url('styles.css');
Which tags would you use to incorporate audio and video in a web page?
To incorporate audio or video in a web page, you use the <audio> or <video> tags.
How can your code inform a web browser that the document can be run offline as a local web app?
To inform a web browser that the document can be run offline as a local web app, create a file to use as a manifest; in that file, list the files required by the application, then link to the file in the <html> tag, like this: <html manifest='filename.appcache'>
How do you initiate a PHP session?
To initiate a PHP session, use the session_start function.
What XMLHttpRequest method is used to initiate an Ajax request?
To initiate an Ajax request, an XMLHTTPRequest object's send method is called.
Which two HTML element tags are used to insert audio and video into an HTML5 document?
To insert audio and video into an HTML5 document, use the <audio> and <video> tags.
How can you make an element (a) invisible, and (b) collapse to zero dimensions?
To make an element invisible, set its visibility property to hidden (or visible to restore it again). To collapse an element's dimensions to zero, set its display property to none (the value block is one way to restore it).
How can you make cross-document messaging more secure?
To make cross-document messaging more secure, you should always supply a do‐ main identifier when posting messages, and check for that identifier when receiving them, like this for posting: postMessage(message, 'http://mydomain.com') And this for receiving: if (event.origin) != 'http://mydomain.com') // Disallow You can also encrypt or obscure communications to discourage injection or eaves‐ dropping.
How can you make something happen when the mouse passes both over and out of an object?
To make something happen when the mouse passes over and out of an object, attach to the onmouseover and onmouseout events.
What JavaScript method is used to match a string against a regular expression?
To match a string against a regular expression in JavaScript, use the test method.
If a form has to offer three choices to a user, each of which is mutually exclusive so that only one of the three can be selected, which input type would you use, given a choice between checkboxes and radio buttons?
To offer three mutually exclusive choices in a web form, you should use radio but‐tons, because checkboxes allow multiple selections.
Which methods can you call to play and pause HTML5 media playback?
To play and pause HTML5 media playback, you can call the play and pause meth‐ ods of an audio or video element.
How can you release an element from its location in a web page to enable it to be moved around?
To release an element from its location in a web page to enable it to be moved around, set its position property to relative, absolute, or fixed. To restore it to its original place, set the property to static.
How do you set up a transition on an object so that when any of its properties are changed, the change will transition immediately in a linear fashion over the course of half a second?
To set up a transition on an object so that when any of its properties are changed the change will transition immediately in a linear fashion over the course of half a second, you would use this declaration: transition:all .5s linear;
How can you specify a callback function to handle Ajax responses?
To specify a callback function to handle Ajax responses, assign the function name to the XMLHttpRequest object's onreadystatechange property. You can also use an unnamed, inline function.
How do you start and finish the creation of a canvas path?
To start a canvas path, issue the beginPath method on the context. After creating a path, you close it by issuing closePath on the context, like this: context.beginPath() // Path creation commands go here context.closePath()
Which PHP function stores a cookie on a web browser?
To store a cookie on a web browser, use the set_cookie function.
How can you submit a form field without displaying it in the browser?
To submit a form field without the user seeing it, place it in a hidden field using the attribute type="hidden".
How can you support media playback in a non-HTML5 browser?
To support media playback in a non-HTML5 browser, you can embed a Flash audio or video player inside any audio or video element, which will be activated if HTML5 media playing is not supported.
What is the best way for web workers to communicate with a main program?
Web workers communicate with a main program most easily using the postMes sage method to send information, and by attaching to the web worker object's onmessage event to retrieve it.
What form attribute can be used to help users complete input fields?
You can help users complete fields with data they may have submitted elsewhere using the autocomplete attribute, which prompts the user with possible values.
How can you include JavaScript code from another source in your documents?
You can include JavaScript code from other sources in your documents by either copying and pasting them or, more commonly, including them as part of a <script src='filename.js'> tag.
How can you indicate with an ellipsis that text is truncated?
You can indicate that text is truncated with an ellipsis using this declaration: text-overflow:ellipsis;
How can you make a property or method available to all objects in a class without replicating the property or method within the object?
You can make a property or method available to all objects in a class without rep‐licating the property or method within the object by using the prototype keyword to create a single instance, which is then passed by reference to all the objects in a class.
Name two ways to modify a CSS attribute of an object.
You can modify a CSS attribute of an object using the setAttribute function, like this: myobject.setAttribute('font-size', '16pt') You can also (usually) modify an attribute directly (using slightly modified property names where required), like this: myobject.fontSize = '16pt'
How can you include a Google Web Font in a web page?
You include a Google Web Font in a web page by first selecting it from http:// google.com/fonts. Then assuming, for example, you chose Lobster, include it in a <link> tag, like this: <link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'> and also refer to the font in a CSS declaration such as this: h1 { font-family:'Lobster', arial, serif; }
What programming language is required to access many of the advanced HTML5 features?
You need to use JavaScript to access many of the new HTML5 technologies such as the canvas and geolocation.
When would you use the === (identity) operator?
You use the identity operator when you wish to bypass JavaScript's automatic operand type changing.
Why is it better to use a program editor instead of a plain-text editor?
Dedicated program editors are smart and can highlight problems in your code before you even run it.
Why is it a good idea to explicitly declare properties within a class?
Explicitly declaring properties within a class is unnecessary, as they will be implicitly eclared upon first use. But it is considered good practice as it helps with code readability and debugging, and is especially useful to other people who may have to maintain your code.
Why is it necessary to write a function for creating new XMLHttpRequest objects?
It's necessary to write a function for creating new XMLHttpRequest objects, because Microsoft browsers use two different methods of creating them, while all other major browsers use a third. By writing a function to test the browser in use, you can ensure that code will work on all major browsers.
Are JavaScript functions and variable names case-sensitive or case-insensitive?
JavaScript functions and variable name are case-sensitive. The variables Count, count, and COUNT are all different.
How do if and while statements interpret conditional expressions of different data types?
Most conditional expressions in if and while statements are literal (or Boolean) and therefore trigger execution when they evaluate to TRUE. Numeric expressions trigger execution when they evaluate to a nonzero value. String expressions trigger execution when they evaluate to a nonempty string. A NULL value is evaluated as false and therefore does not trigger execution.
How do if and while statements interpret conditional expressions of different data types?
Most conditional expressions in if and while statements are literal or Boolean and therefore trigger execution when they evaluate to TRUE. Numeric expressions trigger execution when they evaluate to a nonzero value. String expressions trigger exe‐cution when they evaluate to a nonempty string. A NULL value is evaluated as false and therefore does not trigger execution.
What keyword is used to create an object?
New objects are created via the new keyword.
Name a way to return multiple values from a function.
One way to return multiple values from a function is to place them all inside an array and return the array.
What is meant by operator associativity?
Operator associativity refers to the direction of processing (left to right or right to left).
Write a regular expression to match any characters that are not in a word, as defined by regular expression syntax.
Regular expressions to match characters not in a word could be any of /[^\w]/, / [\W]/, /[^a-zA-Z0-9_]/, and so on.
Both SELECT DISTINCT and GROUP BY cause the display to show only one output row for each value in a column, even if multiple rows contain that value. What are the main differences between SELECT DISTINCT and GROUP BY?
SELECT DISTINCT essentially affects only the display, choosing a single row and eliminating all the duplicates. GROUP BY does not eliminate rows, but combines all the rows that have the same value in the column. Therefore, GROUP BY is useful for performing an operation such as COUNT on groups of rows. SELECT DISTINCT is not useful for that purpose.
What is session fixation?
Session fixation is the attempt to force your own session ID onto a server rather than letting it create its own.
What is session hijacking?
Session hijacking is where a hacker somehow discovers an existing session ID and attempts to take it over.
How can you submit a group of selections from a web form using a single field name?
Submit a group of selections from a web form using a single field name by using an array name with square brackets such as choices[], instead of a regular field name. Each value is then placed into the array, whose length will be the number of elements submitted.
What CSS declaration would you use to rotate an object by 90 degrees?
The CSS declaration you would you use to rotate an object by 90 degrees is: transform:rotate(90deg);
What do the CSS3 attribute selector operators ^=, $=, and *= do?
The CSS3 operators ^=, $=, and *= match the start, end, or any portion of a string, respectively.
What is the JavaScript string concatenation operator?
The JavaScript string concatenation operator is the + symbol.
What are the main differences between an Ajax GET and POST request?
The main differences between an Ajax GET and POST request are that GET requests append the data to the URL and not as a parameter of the send method, and POST requests pass the data as a parameter of the send method and require the correct form headers to be sent first.
Do all the methods of a class have to be defined within the class definition?
The methods of a class do not have to be defined within a class definition. If a method is defined outside the constructor, the method name must be assigned to the this object within the class definition.
How are Boolean values handled differently by PHP and JavaScript?
The most noticeable difference between Boolean values in PHP and JavaScript is that PHP recognizes the keywords TRUE, true, FALSE, and false, whereas only true and false are supported in JavaScript. Additionally, in PHP TRUE has a value of 1 and FALSE is NULL; in JavaScript they are represented by true and false, which can be returned as string values.
What new HTML5 element enables drawing of graphics in web pages?
The new HTML5 element for drawing graphics in a web browser is the canvas element, created using the <canvas> tag.
Which properties provide the width and height available in a browser window?
The properties that provide the width and height available in a browser window are window.innerHeight and window.innerWidth.
What property do you use to specify the size of a background image?
The property you use to specify the size of a background image is backgroundsize, like this: background-size:800px 600px;
What syntax is used to create an associative array?
The syntax you would use to create an associative array is key : value, within curly braces, as in the following: assocarray = {"forename" : "Paul","surname" : "McCartney","group" : "The Beatles"}
Name the three conditional statement types.
The three conditional statement types are if, switch, and the ?: operator.
1Which two parameters to the transform method apply to scaling operations?
The transform method takes six arguments (or parameters), which are in order: horizontal scale, horizontal skew, vertical skew, vertical scale, horizontal translate, and vertical translate. Therefore, the arguments that apply to scaling are numbers 1 and 4 in the list.
What is the purpose of the with statement?
The with statement takes an object as its parameter. Using it, you specify an object once; then for each statement within the with block, that object is assumed.
What delay between events should you set (in milliseconds) to achieve an animation rate of 50 frames per second?
To achieve an animation rate of 50 frames per second, you should set a delay between interrupts of 20 milliseconds. To calculate this value, divide 1,000 milliseconds by the desired frame rate.
How can you add a comment to a style sheet?
To add a comment to a style sheet, you enclose it between /* and */ opening and closing comment markers.
6. How can you adjust the width of lines when drawing?
To adjust the width of drawn lines, assign a value to the lineWidth property of the context, like this: context.lineWidth = 5
Which PHP function converts HTML into a format that can be displayed but will not be interpreted as HTML by a browser?
To convert HTML into a format that can be displayed but will not be interpreted as HTML by a browser, use the PHP htmlentities function.
How do you create a canvas element in HTML?
To create a canvas element in HTML, use a <canvas> tag and specify an ID that JavaScript can use to access it, like this: <canvas id='mycanvas'>
How can you create a comment in JavaScript?
To create a comment in JavaScript, preface it with // for a single-line comment or surround it with /* and */ for a multiline comment.
How would you create a gray text shadow under some text, offset diagonally to the bottom right by 5 pixels, with a blurring of 3 pixels?
To create a gray text shadow under some text, offset diagonally to the bottom right by 5 pixels, with a blurring of 3 pixels, you would use this declaration: text-shadow:5px 5px 3px #888;
How can you determine whether or not a browser supports local storage?
To determine whether or not a browser supports local storage, test the typeof property of the localStorage object, like this: if (typeof localStorage == 'undefined') // Local storage is not available}
Which HTML tag attribute is used to directly embed a style into an element?
To directly embed a style into an element, use the style attribute, like this: <div style='color:blue;'>
Give two cross-browser methods to display the URL assigned to the link with an id of thislink.
To display the URL assigned to the link ID thislink in all main browsers, you can use the two following commands: document.write(document.getElementById('thislink').href) document.write(thislink.href)
Which tags do you use to enclose JavaScript code?
To enclose JavaScript code, you use <script> and </script> tags.
What JavaScript command would you use to replace the current document with the main page at the oreilly.com website?
To replace the current document with the main page at the oreilly.com website, you could use the following command: document.location.href = 'http://oreilly.com'
What method do you call to request geolocation data from a web browser?
To request geolocation data from a web browser, you call the following method, passing the names of two functions you have written for handling access or denial to the data: navigator.geolocation.getCurrentPosition(granted, denied)
How can you select a group of different elements and/or element types in CSS?
To select a group of different elements and/or element types in CSS, you place a comma between each element, ID, or class.
Which function creates a single event at a future time?
To set a single event at a future time, call the setTimeout function, passing it the code or function name to execute and the time delay in milliseconds.
Which function sets up repeating events at set intervals?
To set up repeating events at regular intervals, use the setInterval function, pass‐ ing it the code or function name to execute and the time delay between repeats in milliseconds.
How can you write a function that accepts and processes an unlimited number of parameters?
To write a function that accepts and processes an unlimited number of parameters,access parameters through the arguments array, which is a member of all functions.
What characters are used to define a JavaScript variable name?
Unlike PHP, no character is used (such as $) to define a JavaScript variable name. JavaScript variable names can start with and contain any uppercase and lowercase letters as well as underscores; names can also include digits, but not as the first character.
Where are the username and password stored in a PHP program when you are using HTTP authentication?
Using HTTP authentication, the username and password are stored in $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'].
What is meant by "salting" a string?
When a string is salted, extra characters (known only by the programmer) are added to it before hash conversion. This makes it nearly impossible for a brute-force dic‐tionary attack to succeed.
How do you know whether an Ajax call completed successfully?
When an Ajax call successfully completes, the object's status will have a value of 200.
When you're defining a class, what keyword do you use to refer to the current object?
When defining a class, use the this keyword to refer to the current object.
Which keyword can you use within a JavaScript function to define a variable that has local scope?
Within a JavaScript function, you can define a variable that has local scope by pre‐ceding it with the var keyword upon first assignment.
Which HTML tag is used to encapsulate a form element and supporting text or graphics, making the entire unit selectable with a mouse-click?
You can encapsulate a form element and supporting text or graphics, making the entire unit selectable with a mouse-click, by using the <label> and </label> tags.
What method can you use to extract data from a canvas into an image?
You can extract the data from a canvas using the toDataURL method, which can then be assigned to the src property of an image object, like this: image.src = canvas.toDataURL()
To support drag-and-drop operations, how can you prevent the default action of disallowing drag and drop for these events?
You can prevent the default action of disallowing drag and drop for the events that handle these operations, by issuing a call to the event object's preventDefault method in your ondragover and ondrop event handlers.
What JavaScript method can you use to send a form for validation prior to sub‐ mitting it?
You can send a form for validation prior to submitting it by adding the JavaScript onsubmit attribute to the <form> tag. Make sure that your function returns true if the form is to be submitted and false otherwise.
With which property can you specify the radius of a border?
You can specify the radius of a border using the border-radius property, like this: border-radius:20px;
How can you tell when an Ajax call has completed?
You can tell that an Ajax call has completed when the readyState property of anobject has a value of 4.
What are the two types of comment tags?
You can use // for a single-line comment or /* ... */ to span multiple lines.
How do you escape a quotation mark?
You can use \' or \" to escape either a single or double quote.
How can you create a multiline echo or assignment?
You can use multiple lines within quotations marks or the <<<_END ... _END; construct to create a multiline echo or assignment. The closing tag must begin at the start of a line, and end with a semicolon followed by a new line.
Are the operators && and and interchangeable?
Generally, the operators && and and are interchangeable except where precedence is important, in which case && has a high precedence, while and has a low one.
What actual underlying values are represented by TRUE and 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.
PHP and JavaScript are both programming languages that generate dynamic results for web pages. What is their main difference, and why would you use both of them?
PHP runs on the server, whereas JavaScript runs on the client. PHP can commu‐nicate with the database to store and retrieve data, but it can't alter the user's web page quickly and dynamically. JavaScript has the opposite benefits and drawbacks.
How can you make a table satisfy the Second Normal Form?
To satisfy Second Normal Form, columns whose data repeats across multiple rows should be removed to their own tables.
How can you make a variable accessible to all parts of a PHP program?
You can make a variable accessible to all parts of a PHP program by declaring it as global.
What is the difference between $variable = 1 and $variable == 1?
$variable = 1 is an assignment statement, whereas $variable == 1 is a compar‐ison operator. Use $variable = 1 to set the value of $variable. Use $variable == 1 to find out later in the program whether $variable equals 1. If you mistakenly use $variable = 1 where you meant to do a comparison, it will do two things you probably don't want: set $variable to 1 and return a true value all the time, no matter what its previous value was.
What is the purpose of an FTP program?
FTP stands for File Transfer Protocol. An FTP program is used to transfer files back and forth between a client and a server.
What does HTML stand for?
HyperText Markup Language: the web page itself, including text and markup tags.
If you generate data within a function, what are a couple of ways to convey the data to the rest of the program?
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.
Which of the following tag styles is preferred in HTML5: <hr> or <hr />?
In HTML5 you can use either the XHTML style of tag (such as <hr />) or the standard HTML4 style (such as <hr>). It's entirely up to you or your company's coding style.
What do you put in a column to tie together two tables that contain items havinga one-to-many relationship?
In a one-to-many relationship, the primary key from the table on the "one" side must be added as a separate column (a foreign key) to the table on the "many" side.
Name the main disadvantage of working on a remote web server.
It is necessary to FTP files to a remote server in order to update it, which can substantially increase development time if this action is carried out many times a session. in
Why does the name MySQL contain the letters SQL?
Like nearly all database engines, MySQL accepts commands in Structured Query Language (SQL). SQL is the way that every user (including a PHP program) com‐municates with MySQL.
Why is a for loop more powerful than a while loop?
Loops using for statements are more powerful than while loops, because they support two additional parameters to control the loop handling.
What is the PHP command for deleting the file file.txt?
The PHP command for deleting the file file.txt is: unlink('file.txt');
Which PHP function enables the running of system commands?
The PHP exec function enables the running of system commands.
Which PHP function is used to read in an entire file in one go, even from across the Web?
The PHP function file_get_contents is used to read in an entire file in one go. It will also read them from across the Internet if provided with a URL.
Which PHP superglobal variable holds the details on uploaded files?
The PHP superglobal associative array $_FILES contains the details about uploaded files.
Give one reason why using the POST form method is usually better than GET.
The POST form method is generally better than GET, because the fields are posted directly, rather than being appended to the URL. This has several advantages, par‐ticularly in removing the possibility to enter spoof data at the browser's address bar.(It is not a complete defense against spoofing, however.)
What is the best way to force your own operator precedence?
The best way to force your own operator precedence is to place parentheses around subexpressions to which you wish to give high precedence.
Which printf conversion specifier would you use to display a floating-point number?
The conversion specifier you would use to display a floating-point number is %f.
What is the difference between unary, binary, and ternary operators?
The difference between unary, binary, and ternary operators is the number of operands each requires (one, two, and three, respectively).
What is the difference between the echo and print commands?
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.
Which function can be used to prevent XSS injection attacks?
The function htmlentities can be used to prevent cross-site scripting injection attacks.
What is the main benefit of the array keyword?
The main benefit of the array keyword is that it enables you to assign several values at a time to an array without repeating the array name.
What is the difference between ++$j and $j++?
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.
What command would you use to back up the database publications to a file called publications.sql?
To back up the database publications to a file called publications.sql, you would use a command such as: mysqldump -u user -ppassword publications > publications.sql
How can you call an initializing piece of code when an object is created?
To call a piece of initializing code when an object is created, create a constructor method called __construct within the class and place your code there.
How do you connect to a MySQL database using mysqli?
To connect to a MySQL database with mysqli call the mysqli method, passing the hostname, username, password, and database. A connection object will be returned on success.
How do you convert one variable type to another (say, a string to a number)?
To convert one variable type to another, reference it and PHP will automatically convert it for you.
How would you create a Unix timestamp for 7:11 a.m. on May 2, 2016?
To create a Unix timestamp for 7:11am on May 2nd 2016, you could use the command: $timestamp = mktime(7, 11, 0, 5, 2, 2016);
How can you create a database with a many-to-many relationship?
To create a database with many-to-many relationship, you create an intermediary table containing keys from two other tables. The other tables can then reference each other via the third.
How can you create a multidimensional array?
To create a multidimensional array, you need to assign additional arrays to elements of the main array.
How do you create a new object in PHP?
To create a new object in PHP, use the new keyword like this: $object = new Class;
What syntax would you use to create a subclass from an existing one?
To create a subclass, use the extends keyword with syntax such as this: class Subclass extends Parentclass ...
How would you create a new MySQL user on the local host called newuser with a password of newpass and with access to everything in the database newdatabase?
To create this new user, use the GRANT command like this: GRANT PRIVILEGES ON newdatabase.* TO 'newuser'@'localhost' IDENTIFIED BY 'newpassword';
How can you determine the most recently entered value of an AUTO_INCREMENT column?
To determine the last entered value of an AUTO_INCREMENT column, use the mysql_insert_id function.
How can you determine the number of rows returned by a mysqli query?
To determine the number of rows returned by a mysqli query, use the num_rows property of the result object.
Which mysqli method can be used to properly escape user input to prevent code injection?
To escape special characters in strings, you can call the real_escape_string meth‐od of a mysqli connection object, passing it the string to be escaped.
What feature does MySQL provide to enable you to examine how a query will work in detail?
To examine how a query will work in detail, you can use the EXPLAIN command.
How can you incorporate one PHP file within another?
To incorporate one file within another, you can use the include or require direc‐tives, or their safer variants, include_once and require_once.
What commands initiate and end a MySQL transaction?
To initiate a MySQL transaction, use either the BEGIN or the START TRANSACTION command. To terminate a transaction and cancel all actions, issue a ROLLBACK command. To terminate a transaction and commit all actions, issue a COMMIT com‐mand.
How can you set PHP's internal pointer into an array back to the first element of the array?
To reset PHP's internal pointer into an array back to the first element, call the reset function.
How can you retrieve a particular row of data from a set of mysqli results?
To retrieve a specific row from a set of mysqli results, call the data_seek method of the result object, passing it the row number (starting from 0), then call the fetch_array or other retrieval method to obtain the required data.
Using the SELECT ... WHERE construct, how would you return only rows contain‐ing the word Langhorne somewhere in the author column of the classics table used in this chapter?
To return only those rows containing the word Langhorne somewhere in the col‐umn author of the table classics, use a command such as: SELECT * FROM classics WHERE author LIKE "%Langhorne%";
Which command would you use to view the available databases or tables?
To see the available databases, type SHOW databases. To see tables within a database that you are using, type SHOW tables. (These commands are case-insensitive.)
To send the output from printf to a variable instead of to a browser, what alternative function would you use?
To send the output from printf to a variable instead of to a browser, you would
What command can you use to skip the current iteration of a loop and move on to the next one?
To skip the current iteration of a loop and move on to the next one, use a continue statement.
How do you submit a query to MySQL using mysqli?
To submit a query to MySQL using mysqli, ensure you have first created a con‐nection object to a database, and call its query method, passing the query string.
What printf statement could be used to take the input string "Happy Birthday" and output the string "**Happy"?
To take the input string "Happy Birthday" and output the string "**Happy", you could use a printf statement such as: printf("%'*7.5s", "Happy Birthday");
How can you view the structure of a table?
To view the structure of a table, type DESCRIBE tablename.
Why do you suppose an underscore is allowed in variable names (e.g.,$current_user) whereas hyphens are not (e.g., $current-user)?
A hyphen is reserved for the subtraction operators. A construct like $currentuser would be harder to interpret if hyphens were also allowed in variable names and, in any case, would lead programs to be ambiguous.
What is the difference between a numeric and an associative array?
A numeric array can be indexed numerically using numbers or numeric variables. An associative array uses alphanumeric identifiers to index elements.
What do the IP address 127.0.0.1 and the URL http://localhost have in common?
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 brows‐er's address bar to call up the default page on the local server.
What is the difference between foreach and each?
Both the each function and the foreach ... as loop construct return elements from an array; both start at the beginning and increment a pointer to make sure the next element is returned each time; and both return FALSE when the end of the array is reached. The difference is that the each function returns just a single ele‐ment, so it is usually wrapped in a loop. The foreach ... as construct is already a loop, executing repeatedly until the array is exhausted or you explicitly break out of the loop.
How many values can a function return?
By default, a function can return a single value. But by utilizing arrays, references, and global variables, any number of values can be returned.
What does CSS stand for?
Cascading Style Sheets: styling and layout rules applied to the elements in an HTML document.
List three major new elements introduced in HTML5.
Probably the most interesting new elements in HTML5 are <audio>, <video>, and <canvas>, although there are many others such as <article>, <summary>,<footer>, and more.
What is the meaning of scope in PHP?
Scope refers to which parts of a program can access a variable. For example, a variable of global scope can be accessed by all parts of a PHP program.
If you encounter a bug (which is rare) in one of the open source tools, how do you think you could get it fixed?
Some of these technologies are controlled by companies that accept bug reports and fix the errors like any software company. But open source software also depends on a community, so your bug report may be handled by any user who understands the code well enough. You may someday fix bugs in an open source tool yourself.
What is the purpose of a MySQL index?
The purpose of a MySQL index is to substantially decrease database access times by maintaining indexes of one or more key columns, which can then be quickly searched to locate rows within a table.
What is the purpose of functions?
The purpose of functions is to separate discrete sections of code into their own, selfcontained sections that can be referenced by a single function name.
What is the purpose of the explode function?
The purpose of the explode function is to extract sections from a string that are separated by an identifier, such as extracting words separated by spaces within asentence.
What is the purpose of the semicolon in MySQL queries?
The semicolon is used by MySQL to separate or end commands. If you forget to enter it, MySQL will issue a prompt and wait for you to enter it. (In the answers in this section, I've left off the semicolon, because it looks strange in the text. But it must terminate every statement.)
What are the simplest two forms of expressions?
The simplest forms of expressions are literals (such as numbers and strings) and variables, which simply evaluate to themselves.
What is the standard PHP function for connecting to a MySQL database?
The standard MySQL function used for connecting to a MySQL database is mysql_connect.
What tag is used to cause PHP to start interpreting program code? And what is the short form of the tag?
The tag used to start PHP interpreting code is <?php ... ?>, which can be short‐ened to <? ... ?> but is not recommended practice.
What does the word relationship mean in reference to a relational database?
The term relationship refers to the connection between two pieces of data that have some association, such as a book and its author, or a book and the customer who bought the book. A relational database such as MySQL specializes in storing and retrieving such relations.
What are the three rules of the First Normal Form?
The three rules of First Normal Form are: • There should be no repeating columns containing the same kind of data. • All columns should contain a single value. • There should be a primary key to uniquely identify each row.
What is the main benefit of using a function?
Using functions avoids the need to copy or rewrite similar code sections many times over by combining sets of statements together so that they can be called by a simple name.
Are variable names case-sensitive?
Variable names are case-sensitive. So, for example,$This_Variable is not the same as $this_variable.
What can a variable store?
Variables hold a value that can be a string, a number, or other data.
What is the difference between a WAMP, a MAMP, and a LAMP?
WAMP stands for "Windows, Apache, MySQL, and PHP"; M in MAMP stands for Mac instead of Windows; and the L in LAMP stands for Linux. They all refer to a complete solution for hosting dynamic web pages.
How can you retrieve a string containing an error message when a mysqli error occurs?
When a mysqli error occurs, the error property of the connection object contains the error message. If the error was in connecting to the database, then the con nect_error property will contain the error message.
What is the result of combining a string with a number?
When you combine a string with a number, the result is another string.
What is the difference between accessing a variable by name and by reference?
When you reference a variable by name, such as by assigning its value to another variable or by passing its value to a function, its value is copied. The original does not change when the copy is changed. But if you reference a variable, only a pointer (or reference) to its value is used, so that a single value is referenced by more than one name. Changing the value of the reference will change the original as well.
What needs to be defined in two tables to make it possible for you to join them together?
When you're joining two tables together, they must share at least one common column such as an ID number or, as in the case of the classics and customers tables, the isbn column.
Which symbol is used to preface all PHP variables?
With the exception of constants, all PHP variables must begin with $.
How can you determine the number of elements in an array?
You can use the count function to count the number of elements in an array.
Can you redefine a constant?
You cannot redefine constants because, by definition, once defined they retain their value until the program terminates.
Can you use spaces in variable names?
You cannot use spaces in variable names, as this would confuse the PHP parser. Instead, try using the _ (underscore).
When would you use the === (identity) operator?
You use the identity operator when you wish to bypass PHP's automatic operand type changing (also called type casting).
Which file access mode would you use with fopen to open a file in write and read mode, with the file truncated and the file pointer at the start?
You would use the "w+" file access mode with fopen to open a file in write and read mode, with the file truncated and the file pointer at the start.