PHP, MySQL, & JavaScript All-in-One For Dummies book cover

PHP, MySQL, & JavaScript All-in-One For Dummies

By: Richard Blum Published: 04-10-2018

Explore the engine that drives the internet

It takes a powerful suite of technologies to drive the most-visited websites in the world. PHP, mySQL, JavaScript, and other web-building languages serve as the foundation for application development and programming projects at all levels of the web. 

Dig into this all-in-one book to get a grasp on these in-demand skills, and figure out how to apply them to become a professional web builder. You’ll get valuable information from seven handy books covering the pieces of web programming, HTML5 & CSS3, JavaScript, PHP, MySQL, creating object-oriented programs, and using PHP frameworks.

  • Helps you grasp the technologies that power web applications      
  • Covers PHP version 7.2
  • Includes coverage of the latest updates in web development
  • Perfect for developers to use to solve problems
This book is ideal for the inexperienced programmer interested in adding these skills to their toolbox. New coders who've made it through an online course or boot camp will also find great value in how this book builds on what you already know.

Articles From PHP, MySQL, & JavaScript All-in-One For Dummies

page 1
page 2
page 3
26 results
26 results
PHP, MySQL & JavaScript All-in-One For Dummies Cheat Sheet

Cheat Sheet / Updated 04-20-2022

Working with PHP, MySQL, and JavaScript to create dynamic web applications can be difficult, but if you know a few programming tricks, you can make that job a lot easier. This Cheat Sheet shows you how to extract data from different databases in your PHP programs, filter out unwanted or potentially dangerous data from web forms, quickly find data stored in your MySQL database, and trigger timed events in your JavaScript programs.

View Cheat Sheet
Filtering Data in PHP

Article / Updated 06-18-2019

Validating input data is crucial to any PHP application. You don't want an attacker trying to attack your system by submitting improper form data. Fortunately, the PHP developers have provided some help with that process. PHP provides several filter functions that allow you to easily check for valid data or sanitize the data if any unwanted data is present. The following table lists the different functions available in the filter family. The PHP Filter Functions Function Description filter_has_var() Checks if a variable of the specified type exists filter_id() Returns the filter ID of the specified filter filter_input() Retrieves a value passed by GET, POST, sessions, or cookies and filters it filter_input_array() Retrieves multiple values passed to the PHP program and filters them filter_list() Returns a list of supported filters filter_var() Filters a variable filter_var_array() Filters a list of variables These functions allow you to specify a variable to check and the type of check to perform. There are two main groups of filter: Validation: Checks if the specified data is present Sanitation: Checks if the specified data is present and removes it The following table shows the different validation filters available. PHP Validation Filters Filter Description FILTER_VALIDATE_BOOLEAN Checks for a valid Boolean value FILTER_VALIDATE_EMAIL Checks for a valid email address FILTER_VALIDATE_FLOAT Checks for a valid float value FILTER_VALIDATE_INT Checks for a valid integer value FILTER_VALIDATE_IP Checks for a valid IP address value FILTER_VALIDATE_REGEXP Checks for a valid regular expression value FILTER_VALIDATE_URL Checks for a valid URL string The validation checks return a TRUE value if the data contains the data type being checked, or a FALSE value if not. The following table shows the different sanitation filters available. PHP Sanitation Filters Filter Description FILTER_SANITIZE_EMAIL Removes illegal characters from an email address FILTER_SANITIZE_ENCODED Encodes special characters in the string FILTER_SANITIZE_MAGIC_QUOTES Apply the addslashes() function FILTER_SANITIZE_NUMBER_FLOAT Remove all characters, except digits, +, –, and E FILTER_SANITIZE_NUMBER_INT Removes all characters except digits and + or – FILTER_SANITIZE_SPECIAL_CHARS Removes any special characters in the string FILTER_SANITIZE_FULL_SPECIAL_CHARS Same as htmlspecialchars() FILTER_SANITIZE_STRING Removes HTML tags and special characters from a string FILTER_SANITIZE_STRIPPED Same as FILTER_SANITIZE_STRING FILTER_SANITIZE_URL Removes all illegal characters from a URL string You can combine both the sanitizing and validating features in your code to ensure the data you receive from an HTML form is valid: $address = $_POST['email']; $address = filter_var($address, FILTER_SANITIZE_EMAIL); if (!filter_var($address, FILTER_VALIDATE_EMAIL)) { echo "Sorry, you have entered an incorrect address } else { echo "Thank you for submitting your data"; } Using the PHP filter functions will help you safely process any type of input data received in your application HTML forms.

View Article
How to Set Cookies with PHP

Article / Updated 06-18-2018

PHP uses the setcookie() function to set new cookies and update existing cookies. Here’s the basic format of the setcookie() function: >setcookie(name [, value] [, expire] [, path] [, domain] [, secure] [, httponly]) The only required parameter is the name of the cookie, although you'll almost always want to include a cookie value, too. Leaving off the value sets the cookie value to NULL. The optional expire parameter allows you to specify the expiration date and time as a Unix timestamp value, making it a persistent cookie. The Unix timestamp format is an integer value of the number of seconds since midnight on January 1, 1970. The last four parameters allow you to specify the URL paths and domains allowed to access the cookie, and whether the cookie should be set as Secure or HttpOnly. Be careful with the expire parameter. Even though the HTTP message sends the expire attribute as a full date and time, with the setcookie() function you set it using a timestamp value, not a standard date and time. The way most PHP developers do that is by adding the number of seconds to the current date and time retrieved from the time() function: setcookie("test", "Testing", time() + (60*60*24*10)); This sets the cookie named test to expire ten days from the time the web page is accessed by the site visitor. Because the cookie is part of the HTTP message and not part of the HTML data, you must set the cookie before you send any HTML content, including the opening tag. There is an exception to this, though. If the PHP output_buffer setting is enabled, the PHP server sends all output from the program to a buffer first. Then, either when the buffer is full or the program ends, it rearranges the data in the buffer to place the HTTP messages first and then sends the data to the client browser. Follow these steps to test setting a persistent cookie from a PHP application: Open your favorite text editor, program editor, or integrated development environment (IDE) package. Type the following code into the editor window: PHP Cookie Test Trying to set a cookie Save the file as cookietest1.php in the DocumentRoot folder for the web server.For XAMPP in Windows, that's c:\xampp\htdocs; for XAMPP in macOS, that’s /Applications/XAMPP/htdocs. Start the XAMPP Control Panel and then start the Apache web server. Test your code here.You may need to change the TCP port number to match your web server. Using your browser's Developer Tools, check the cookies that are set from the web page and their expiration date and time. You should see the test1 cookie created.It should be set to expire in ten minutes. Close the browser window when you’re done. The Developer Tools allow you to see the test1 cookie that was set by the program. For the Microsoft Edge browser, look in the Debugger section for the cookies. The cookie is set, along with the value, and the expiration time is set to ten minutes (600 seconds) in the future. You have to place the setcookie() function lines before the html section of the web page. Otherwise, you'll get an error message. The web server must send any cookie data in the HTTP session before any HTML content.

View Article
What are Accessor Magic Methods in PHP?

Article / Updated 06-18-2018

Accessor magic methods are PHP methods you use to access the private property values you define in the class. Creating special methods to retrieve the current property values helps create a standard for how other programs use your class objects. These methods are often called getters because they retrieve (get) the value of the property. You define the accessor using the special __get() method: public function __get($name) { return $this->$name; } That's all there is to it! Accessor methods aren’t overly complicated; they just return the current value of the property. To use them you just reference the property name as normal: echo "<p>Product: $prod1->description</p>\n"; PHP automatically looks for the accessor method to retrieve the property value. Follow these steps to try creating and using a class definition with mutators and accessors: Open your editor and type the following code: PHP OOP Test Testing PHP OOP setters and getters Invalid price set\n"; $this->price = 0; } elseif ($name == "inventory" && $value < 0) { echo "Invalid inventory set: $value\n"; } else { $this->$name = $value; } } public function __get($name) { return $this->$name; } public function buyProduct($amount) { if ($this->inventory >= $amount) { $this->inventory -= $amount; } else { echo "Sorry, invalid inventory requested: $amount\n"; echo "There are only $this->inventory left\n"; } } } $prod1 = new Product(); $prod1->description = "Carrots"; $prod1->price = 1.50; $prod1->inventory = 5; $prod1->onsale = false; echo "Just added $prod1->inventory $prod1->description\n"; echo "Now buying 4 carrots...\n"; $prod1->buyProduct(4); echo "Inventory of $prod1->description is now $prod1->inventory\n"; echo "Trying to set carrot inventory to -1:\n"; $prod1->inventory = -1; echo "Now trying to buy 10 carrots...\n"; $prod1->buyProduct(10); echo "Inventory of $prod1->description is now $prod1->inventory\n"; ?> Save the file as ooptest2.php in the DocumentRoot folder for your web server. Ensure that the web server is running, and then go here to test your code. Close the browser window when you're done. The image below shows the output that you should see when you run the program in your browser. There’s a lot going on in this example, so hang in there with me! First, the PHP code defines the Product class, using the four properties, but this time it defines them with private visibility. Following that, the mutator and accessor magic methods are defined. The mutator checks to ensure the price and inventory properties can't be set to a negative value. After the class definition, the code creates an instance of the Product class, and experiments with the inventory values. First, it uses the buyProduct() method to purchase four carrots. That works just fine. Next, it uses the mutator to set the inventory property for the carrot object to a negative value. The mutator code intercepts that request and prevents the inventory from being set, instead producing an error message. Finally, the code tries to use the buyProduct() method to purchase more carrots than what's set in inventory. The added code in the buyProduct() method prevents that from happening. Now the class definition is starting to do some useful functions for the application. But wait, there are more magic methods available for you to use!

View Article
How to Build Your Own PHP Functions

Article / Updated 06-18-2018

While you're coding in PHP, you’ll often find yourself using the built-in functions available (such as the rand() function you used earlier in the example programs). Functions are nothing more than PHP code someone else wrote to accomplish a useful feature that you can use in any program. Instead of having to copy all the code into your application, you just use the function name. PHP allows you to create your own functions to use in your programs and share with others. After you define a function, you can use it throughout your program. This saves typing if you use a common routine or block of code in lots of places in your application. All you need to do is write the code once in the function definition and then call the function everywhere else you need it. The basic format for a function definition looks like this: function name(parameters) { function code return value; } The name must uniquely identify the function. It can't be one of the existing PHP function names, and it can’t start with a number (although numbers can appear anywhere else in the function name). The parameters identify one or more variables that the calling program can pass to the function (or you can have a function that requires o parameters). If there is more than one variable in the parameter list, you must separate them with commas. You can then use the variables anywhere within the function code, but they only apply to inside the function code block. You can’t access the passed parameter variables anywhere else in the program code. Any variables you define inside the function code apply only to the function code. You can’t use function variables in the PHP code outside the function definition. The return statement allows you to pass a single value back to the calling program. It's the last statement in the function definition code, and it returns control of the program back to the main code section in your program. Try out the following steps to experiment with creating a function and using it in your PHP program: Open your editor and type the following code: PHP Function Test Save the file as factest.php in the DocumentRoot folder for your web server. Test your code here. Close your browser when you're done. When you run the factest.php program, the output should look like what you see below. All the code required to calculate the function is contained within the factorial() function definition code block. When PHP uses the factorial() function, it passes a single value that the function assigns to the $value1 variable. When the calculation is complete, the function code returns the results back to the main program. The main program uses the factorial() function twice in the code, both embedded in echo statements: echo "The factorial of 10 is " . factorial(10) . "\n"; echo "The factorial of 5 is " . factorial(5) . "\n"; You can embed variables inside the string values in echo statements, but you can't embed functions. To insert the output from the function into the echo statement output, the code uses the string concatenation operator (the period) to “glue” the output from the strings and the factorial() functions into a single string to display. If you have lots of functions that you use in many of your programs, you can define them in a separate file. Then to use the functions in your programs just use the include() function to include the function file, and you can then use the functions inside your programs without having to retype them!

View Article
Using XMLHttpRequest Class Properties

Article / Updated 06-14-2018

The XMLHttpRequest object contains several class properties that you’ll need to know about to handle the HTTP response from the web server. The XMLHttpRequest Class Properties Property Description onreadystatechange/td> Defines a callback function that the browser triggers when the HTTP connection changes state readyState Contains the connection status of the HTTP connection responseText Contains the response sent by the web server in text format responseXML Contains the response sent by the web server in XML format status Contains the numeric HTTP response code from the web server statusText Contains the text HTTP response string from the web server After you use the send() method to send a connection request to a web server, the HTTP connection process works through five connection states, as tracked by the readyState property: State 0: The connection has not been initialized. State 1: The connection to the server has been established. State 2: The server received the HTTP request message. State 3: The server is processing the HTTP request. State 4: The server sent the response. As the HTTP connection works through these five connection states, the value contained in the readyState property changes. This causes the function you define in the onreadystatechange property to trigger for each state change. When the readyState property contains a value of 4, the final result from the request is available for processing. When the readyState property value is 4, you know the communication is complete, but you don’t know how it turned out. To determine that, you check the HTTP response returned by the web server using the status property. If the status property contains the 200 numeric HTTP result code, that indicates the connection was successful, and any data returned by the web server is available in the responseText and responseXML properties. If the status property contains some other HTTP result code (such as 403 or 404), that indicates there was an error communicating with the web server. Because these values are standard, it has become somewhat common practice to start out the onreadystatechange callback function code checking for them: con.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var result = this.responseText; } }; The function only retrieves the data when the connection is complete and has returned valid data. This method of defining the callback function inline is referred to as creating an anonymous callback function, because you don’t define a name for the function. It only exists inside the onreadystatechange property, so you can’t reference it anywhere else in your JavaScript code. Although using an anonymous function is a popular way of defining the callback function, you can define the function as a standard named JavaScript function and then reference that function name in the onreadystatechange property.

View Article
Making Sure Your MySQL Database is ACID Compliant

Article / Updated 06-14-2018

Over the years, MySQL database experts have devised rules for how databases should handle transactions. The benchmark for all professional database systems is the ACID test. No, we’re not throwing the server into an acid bath; the ACID test is actually an acronym for a set of database features defining how the database server should support transactions: Atomicity Consistency Isolation Durability Atomicity The atomicity feature states that for a transaction to be considered successful, all steps within the transaction must complete successfully. Either all the steps should be applied to the database, or none of them should. A transaction should not be allowed to complete partway. To support atomicity, MySQL uses a system called commit and rollback. Database actions are only temporarily performed during a transaction. When it appears that all the actions in a transaction would complete successfully, the transaction is committed (the server applies all the actions to the database). If it appears that any one of the actions would fail, the entire transaction is rolled back (any previous steps that were successful are reversed). This ensures that the transaction is completed as a whole. MySQL uses the two-phase commit approach to committing transactions. The two-phase commit performs the transaction using two steps (or phases): Prepare phase: A transaction is analyzed to determine if the database is able to commit the entire transaction. Commit phase: The transaction is physically committed to the database. The two-phase commit approach allows MySQL to test all transaction commands during the prepare phase without having to modify any data in the actual tables. Table data is not changed until the commit phase is complete. Consistency The concept of consistency is a little more difficult than atomicity. The consistency feature states that every transaction should leave the database in a valid state. The tricky part here is what is considered a “valid state.” Often, this feature is applied to how a database server handles unexpected crashes. If the database takes a power hit in the middle of the commit phase of a multi-action transaction, can it leave the tables in a state where the data makes sense? MySQL utilizes two features to accomplish consistency: Double-write buffering: With double-write buffering, before MySQL writes data to the actual tables, it stores the data in a buffer area. Only after all the transaction data is written to the buffer area will MySQL write the buffer area data to the actual table data files. Crash recovery: If there is a system crash before the buffer area is completely written to the table files, MySQL can recover the buffer area using the crash recovery feature, which recovers submitted transactions from a transaction log file. Isolation The isolation feature is required for multiuser databases. When there is more than one person modifying data in a database, odd things can happen. If two people try to modify the same data value at the same time, who’s to say which value is the final value? When more than one person tries to access the same data, the DBMS must act as the traffic cop, directing who gets access to the data first. Isolation ensures that each transaction in progress is invisible to any other transaction in progress. The DBMS must allow each transaction to complete and then decide which transaction value is the final value for the data. It accomplishes this task using a feature called locking. Locking does what it says: It locks data while a transaction is being committed to the database. While the data is locked, other users can’t access the data, not even for queries. This prevents multiple users from querying or modifying the data while it’s in a locked mode. There are two basic levels of locking that MySQL uses to support isolation: Table-level locking: With table-level locking, any time a user requires a modification to a data record in a table, the DBMS locks the entire table, preventing other users from even viewing data in the table. As you can guess, this has an adverse effect on database performance, especially in environments where there is a lot of change to the data in the database. Early DBMS implementations used table-level locking exclusively. Row-level locking: To solve the problems of table-level locking, many DBMS implementations (including the MySQL InnoDB storage engine) now incorporate row-level locking. With row-level locking, the DBMS locks only the data record that’s being modified. The rest of the table is available for other users to access. Durability The durability feature states that when a transaction is committed to the database, it must not be lost. This sounds like a simple concept, but in reality durability is often harder to ensure than it sounds. Durability means being able to withstand both hardware and software failures. A database is useless if a power outage or server crash compromises the data stored in the database. MySQL supports durability by incorporating multiple layers of protection. The same double-write buffer and crash recovery features mentioned for the consistency feature also apply to the durability feature. MySQL writes all transactions to a log file, writes the changes to the double-write buffer area, and then writes them to the actual database files. If the system crashes during this process, most of the time MySQL can recover the transaction within the process. The onus of durability also rests on the database administrator. Having a good uninterruptable power supply (UPS) for your database server, as well as performing regular database backups, is crucial to ensuring your database tables are safe.

View Article
MySQL Features

Article / Updated 06-14-2018

The MySQL database server was created by David Axmark, Allan Larsson, and Michael Widenius as an upgrade to the mSQL database server and was first released for general use in 1996. It’s now owned and supported by Oracle but released as open-source software. MySQL was originally created to incorporate indexing data to speed up data queries in the mSQL database server, by using the indexed sequential access method (ISAM). It did this by incorporating a special data management algorithm called the MyISAM storage engine. This proved to be a huge success. MySQL was initially recognized for its speed of accessing data. The MyISAM data storage and indexing method proved to be a game changer in speeding up data access from other types of DBMS packages. It wasn’t long before the Internet world took notice, and MySQL became the DBMS package of choice for high-volume web applications. These days, MySQL has evolved to do more than just fast data queries. Development is continually ongoing to add new features to MySQL. A short list of features includes the following: It was written in C and C++ and has been compiled to run on many different platforms. It incorporates a modular design approach to create a multi-layer server design. It supports multi-threading, making it easily scalable to incorporate multiple CPUs if available. It uses a thread-based memory allocation system. It implements hash tables in memory to increase performance. It supports client/server and embedded server environments. It supports multiple data storage engines. It implements all SQL functions using a class library. It includes support for all standard SQL data types. It offers a security system that supports both user-based and host-based verification. It includes support for large databases using more than 5 billion rows of data. It provides application programming interfaces (APIs) for many common programming languages (including PHP). It incorporates many different character sets, allowing it to support many different languages. It provides both command line and graphical tools for common database management.

View Article
What are Mutator Magic Methods in PHP?

Article / Updated 06-13-2018

Mutator magic methods are PHP methods that change the value of a property that you set with the private visibility. These are also commonly called setters. The preferred way to handle class properties is to make them private so external programs can’t change them directly. Instead, to manipulate the data, external programs are forced to use mutator magic class methods that interface with the properties. The mutator magic method in PHP is __set() (note the leading double underscores). You use the mutator magic method to set all the values of the properties in the class with a single method definition: public function __set($name, $value) { $this->$name = $value; } The mutator uses two parameters: the name of the property to set and the value to assign to the property. Where the magic comes into play is with how PHP uses the mutator. In your PHP application code, you don’t actually have to call the __set() mutator method. You can define the $description property just by using a simple assignment statement: PHP automatically knows to look for the __set() mutator method defined for the class and runs it, passing the appropriate property name and value. Even though the $description property is set to the private visibility, by defining the mutator magic method you can allow external programs to assign a value to the property. The benefit of using mutators, though, is that you can control how external programs use the properties you define for the class. With the mutator definition, you can place any code you need to control property features, such as ranges of values allowed or the allowed settings applied to the property. For example, you could so something like this: public function __set($name,$value) { if ($name == "price" && $value < 0) { $this->price = 0; } else { $this->$name = $value; } } This example checks if the property being set is the $price property. If it is, it checks if the value is less than 0. If the value is less than 0, the price is set to 0 instead of the supplied price value. This gives you a way to control the value that is set for the price from external programs that use the class object.

View Article
Preventing Cross-Site Scripting in Your Web Application

Article / Updated 06-13-2018

Cross-site scripting (known as XSS) is quite possibly the most dangerous type of attack made on dynamic web applications. The main idea of an XSS attack is to embed malicious JavaScript code in data that the attacker submits to the web application as part of the normal data input process. When the web application tries to display the data in a client browser, the JavaScript is pushed to the client browser that’s viewing the website and runs. Follow these steps to watch an XSS exploit in action: Open your favorite text editor, program editor, or integrated development environment (IDE) package. Type the following code into the editor window: XSS Test input { margin: 5px; } Please enter your first name: Save the file as xssform.html in the DocumentRoot folder for your web server.For XAMPP on Windows, that's c:\xampp\htdocs; for XAMPP on macOS, that’s /Applications/XAMPP/htdocs. Open a new tab or window in your browser, and type the following code: XSS Test XSS Test Welcome, $fname\n"; ?> This is the end of the test Save the file as xsstest.php in the DocumentRoot folder for your web server. Open the XAMPP Control Panel, and then start the Apache web server. Navigate here. You may need to change the TCP port used to match your web server. In the form, type the following code in the Name text box: <script>alert("Hello!");</script> Click the Submit button to continue. Close the browser window when you're done with the test. When you submit the form with the embedded JavaScript code, you should get the output shown here. The PHP code sent the JavaScript to the browser as part of the echo statement output, and the browser dutifully ran the JavaScript code. This example is harmless, because it just displays a simple alert message, but a real attacker would embed much more malicious code. Some browsers, such as Safari and Chrome, have built-in XSS attack detection, which may trigger on this test and block the JavaScript code from running. If you don’t see the alert() pop-up box, open the developer tools for your browser and see if there's a notice that the browser blocked a potential XSS attempt. The “cross-site” part of the XSS name comes from where the </code> tag sends the browser to retrieve the JavaScript code file. In the previous example, the JavaScript code was embedded directly within the script element. <strong><em>Remember:</em></strong> The <code><script></code> HTML5 tag can also reference an external JavaScript file, which the browser will load and run. An attacker can specify the <code>src</code> attribute in the <code><script></code> tag to redirect the browser to run JavaScript located on a rogue server anywhere in the world. There are two different methods of carrying out an XSS attack: <ul> <li><strong>Reflected attack:</strong> The attacker places the rogue script as a link in the submitted data. Victims must actively click the link to launch the XSS attack.</li> <li><strong>Persistent attack:</strong> The attacker places the rogue script as data that the browser displays when the web page loads (as in the previous example).</li> </ul> Persistent attacks are very dangerous. The malicious script runs as soon as an unsuspecting website visitor opens the web page that contains the script as part of the content, without any actions required by the victim. For example, if an attacker posts a blog comment that contains malicious JavaScript code, every time the web application displays that blog comment on a client browser, the malicious script is run.

View Article
page 1
page 2
page 3