First, to run PHP files, you need to run them through a server. It is best to work with a development server while you are still working on your site so that you do not need to worry about what the public can see during that time.
All PHP statements must end with a semicolon, or it will give an error. If you forget one, it treats multiple statements like one statement, which then throws a Parse error.
In PHP the $ symbol must be placed in front of all variables (no spaces).
Examples
To execute a line break in PHP, you will use "\n"
To concatenate (join) multiple strings together you use a period in between them
Example:
To interpolate (join) a string with a variable together you can include them inside double quotes
Example:
Strings must be enclosed with quotation marks or single quotes. There is a slight difference between the two.
Single Quotes - Example of Literal String:
Double Quotes - Example of Variable Interpolation:
Variables can contain integers (positive or negative whole numbers) or floating-point numbers (positive or negative numbers containing a decimal point).
You can set a boolean value to true or false.
Null values are null if no value has been added to a variable, or if it has been assigned null.
A constant is a variable that cannot change
It is case sensitive and written in ALL CAPS by convention
Arrays store one or multiple values within one variable.
There are two ways to create an array in PHP:
Call them using their index/key [0, 1, 2, etc] in square brackets following the variable name:
To add an item to the end of an array, list the name of the array with empty square brackets = the item you want to add in quotes.
Example:
Use the unset command, name of the array, and position.
Example:
Example:
These allow you to give a custom name using a string to the index/key, rather than just using a number.
Example:
Display specific info from array:
W3Schools: PHP Multidimensional Arrays
An array containing one or more arrays
To access $alice_email from the array:
If / Else statements syntax:
Else if statements syntax:
If / Else Example:
Elseif Example:
While loops are the simplest type of loop in PHP. A while loop tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to true.
Syntax:
Example:
Use a for loop to run code a specific number of times
Syntax:
Example:
Easier than the For Loop!
Use a foreach loop to loop through a key/value pair in an array
Syntax:
Example:
W3School: PHP Switch Statement
The switch statement is similar to a series of if statements on the same expression.
In many different situations you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals. This is exactly what a switch statement is for.
You can list two cases in a row if they have the same output
default statement is in case there is no match to switch statement
break is used to stop the statement from continuing to run
If you intentially do not want a break, comment out no break where the break would have been
The Do While loop is kind of like the While loop, but there's one major difference: The While loop will only start if the condition is true; whereas the Do While loop will always execute the first time, and then evaluate whether the condition is true afterwards.
Syntax:
Example:
PHP has hundreds of built in functions. You can find a list of all of them on php.net.
Print results of an array on the screen
echo $my_array does not work in PHP. Instead, you need to use print_r (human readable)
Example:
Both functions return the number of elements in an array.
This function can be used to see what a variable contains by having it print it on the screen
You can pass multiple variables at once by separating them with a comma
sort() - Alphabetical sort of an array
rsort() - Reverse alphabetical sort of an array
First, create an array
Then add the array as a parameter to sort() function
Echo the array with a foreach loop
Change all text to lowercase
No separate line to call here
Echo the array with a foreach loop
Shortcut echo tag
This way you can have HTML inside a PHP control structure
Replace opening brace with colon, replace closing brace with endif (endfor, etc)
Example:
(First three lines of code would be placed above the < !DOCTYPE html>)
Rest of the code is set within the body of the HTML
To add a form to a webpage, we use <form> element. Inside the <form> we place controls such as <button> , text boxes, etc.
Add action attribute to tell server where to send the information submitted through the form
Example:
We can access the query string by using a GET array (in file: process_form.php)
If no action attribute was added, then form will be submitted to itself. This could be useful if you want your user to review the information on the screen before submitting.
W3Schools: PHP Superglobal = $_GET
W3Schools: PHP Superglobal = $_POST
GET vs. POST | GET | POST |
---|---|---|
bookmarkable? | yes | no |
sensitive data? | no | yes |
size limit? | yes, 3000 char. | no |
$_GET is a PHP super global variable which is used to collect data after submitting an HTML form with method="get". This is the default and sends data in the query string making it less secure.
→ Tip: Use $_GET for search results
PHP options:
Or send message to someone with their name from form:
If you have a hyperlink with parameters, i.e.:
When a user clicks on the link "Test $GET", the parameters "subject" and "web" are sent to "test_get.php", and you can then access their values in "test_get.php" with $_GET.
$_POST is also a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". This sends data separately from the query string. This would be used for sensitive data such as username, password, etc.
→ Tip: Use $_POST for changing data on server - inserting, updating, or deleting
Example:
→ Tip: Add var_dump($_POST); to top of page (inside php brackets) with form. This will display data submitted in form at top of screen on page reload after clicking submit.
Example:
You can check to see which method a form used when it was submitted by checking the REQUEST_METHOD (which request method was used to access the page, ie. 'GET', 'HEAD', 'POST', 'PUT'.)
You can use this following code to only print out the array if the form was submitted
Three types of input where no value can be entered:
Example:
Code:
mysqli_insert_id returns the auto-generated id used in the last query
Example:
Here is the SQL statement in our code:
This is the value typed into title column of form...
This is the resulting SQL string...
What does it mean?
The mysqli_real_escape_string - escapes special characters in a string for user in an SQL statement, taking into acount the current charset to the connection
Can also use mysqli_escape_string
(This code would be used in the new-article.php file)
(This code would be used in the new-article.php file)
This is used to execute the same statement repeatedly with high efficiency.
It consists of two stages:
Repeated Execution:
Then, instead of this...
Use...
Next...
PHP.net - mysqli_stmt_bind_param
Then...
Inside file new-article.php, move require 'includes/database.php'; it above the if statement.
In the database.php file, wrap all of the code inside of a function.
In the new-article.php file, call the function just below the first if statement.
We still have a problem because the $conn variable was declared inside a function, and its use is limited to inside of that function. We can fix this by returning the value of the variable on the database.php file inside of the function:
Now that we've changed the database.php include, we've broken our existing pages.
To return a value, it sends a value back from a function or included file. Sof if you have a function like this:
When you call this function, there's no way to get the value of $message from outside the function:
To do this, you need to use return inside the function:
Then when you call the function, you can use its return value:
→ Return value will equal "Hello"
As for included files, if you just include or require a file (ie - file called example.php)
And then you included it in another file:
Then this file is included into the script as though you'd copied and pasted its contents into the calling script.
If you want, you can return a value from the included file by putting a return at the end, just like in a function:
Then you can get that value in the same way when you include it:
Basically, return is used to pass a value back to calling code.
Before we enter a new entry in the database, you should validate the data in the form. It should be done once the form has been submitted, but before we build the $sql statement.
It is possible that the user will have more than one error. Create a variable to hold the error messages. Set its initial value to an empty array.
Start by checking that the title is not blank. It is best to redisplay the form along with the error message so that the user can correct the errors.
Also check to see if the content is blank.
Then to test it, you need to print out the array to see the error messages, and then exit the script.
Once you know it is working, change the var_dump to check to see if the $errors array is empty. If it is empty the script should continue. Need to wrap the entire rest of the code in that block with the following if statement. The closing bracket should be second level from the bottom.
Next, in the HTML you will add to display the errors. Just to test that our code is working - under the h2 heading, add:
This will cause an error because the $errors variable was initialized inside the if block at the top. To correct this error, move the $errors = []; just above the if statement, but below the require statement.
We don't just want the var_dump at the top of the form, so now change it to the following. This will check to see if there are any errors. If there are, it will loop around and display any error messages as an unordered list.
We could have added the required attributes inside the form in the HTML, but these can be bypassed.
You should always validate data on both the server-side and client-side every time new data is being submitted from a website.
For this section we are accessing the new-article.php
Set the value attribute of the title input to the variable $title
Then, if the form is submitted, assign the value of the title field to the variable $title. Add this just under the if statement at the top, but above the if statement that checks to see if the title field is empty.
Also need to initialize the $title variable outside of the if block, so add the following above the if statement:
Now the same needs to be done for the other two controls:
Add the value to each appropriate input:
Initiate the variables at the top:
Add the post statements to fill in the blanks with what was there before if there are errors:
Now to clean up the code, replace the global variables ($_POST['title'], etc. with the new variables just created.
htmlspecialchars() - converts special characters to HTML entities
Following changes should be applied to new-article.php
In HTML where we just added new PHP code, we need to add this new htmlspecialchars
Following changes should be applied to index.php
Following changes should be applied to article.php
Following changes should be applied to new-article.php
Inside the else statement, right before mysqli_stmt_bind_param, add:
W3Schools: PHP date() Function
header - send a raw HTTP header
Following changes apply to new-article.php
Inside if statement of mysqli_stmt_bind_param:
→ This is redirecting to a relative url and will work in modern browers, but not old ones. Instead, use an absolute url.
$_SERVER - server and execution environment information
Instead of hardcoding your server information, you can get it using the superglobal $_SERVER
Insert the following code just below $id = mysqli_insert_id($conn);
Next, you can get the server name using the $_SERVER['HTTP_HOST']
Following change on index.php
Add a link on index page to add a new article. Place it underneath: require 'includes/header...';
Create a Function to Get a Single Article
Create new file: edit-article.php
Create new file in includes folder: article-functions.php
Following code in article-functions.php
mysqli_fetch_array - fetch a result row as an associative aaray, a numeric array, or both.
Add a PHP doc comment block at top of article-functions.php
Following code in article.php
Add require statement at top:
Delete code:
Replace with a call to the new function:
Since we are now using a prepared statement in our new article-functions.php, we can delete our check to see if the id is numberic. This prepared statement will protect us from SQL injection. Delete:
Now copy code from article.php and paste into edit-article.php
Create new file in includes folder: article-form.php
Copy code from new-article.php and paste into article-form.php
Once pasted into new file, delete form in new-article.php, and replace with:
Copy lines of code from new-article.php and paste at end of edit-article.php
Once pasted at end of edit-article.php, Change <h2 to:
Add to edit-article.php under $article = getArticle:
Edit-article.php - add checks to see if id that is passed is valid, and if not show error message and stop script.
Continue on edit-article.php. Above $title = $article... add:
Under $published_at = $article ['published_at']; add:
Create a function to validate an article so that it can be used in both new-article.php and the edit-article.php forms.
Start by creating new function in article-functions.php
Then go to new-article.php and copy validation code:
Paste it in new function.
After pasting:
Add php doc comment above function:
Following code in new-article.php
Add require statement at top (under other require statement)
Replace validation code in new-article.php with call to new function:
Now we can use some of that code from new-article.php in edit-article.php. Paste under die ("id not supplied... }
Delete following code in new-article.php
Example:
Example: (update title for article with id=6)
This code would be used in the Query tab of Sequel Pro
IMPORTANT: If you don't include a WHERE clause, every single row in the table will be updated
Note: Any columns used in the WHERE clause should be indexed, or they could take a long time to execute
Copy from new-article.php:
Paste into edit-article.php:
Delete from edit-article.php. It is in the pasted section already at the top of the file right about the $sql = statement.
Change INSERT statement to UPDATE in edit-article.php
Add: (edit-article.php at top)
Add $id to bind_param function call, and add i for integer:
Since we're updating and not inserting, delete:
Following change to article.php:
Add a link back to edit-article.php page after data has been displayed.
Create a new file in includes folder: url-redirect.php
Create new function in url-redirect
Copy from new-article.php:
Paste inside new function in url-redirect.php
Delete following code:
And replace with:
Add a php doc comment block above new function:
In both edit-article.php and new-article.php, add require statement:
Replace code from both edit-article.php and new-article.php (The same code that was copied to the new function) with a call to the new function:
Using an input box allow a user to enter any whole number, and use PHP to determine if it is prime. Display answer on page.
$colors = array("red", "green", "blue", "yellow");
This will sort it, but will not output it. To see that it has been sorted, you can use print_r.
$age = ["Peter" => "35", "Ben" => "37", "Lucy" => "25"];
This will sort it, but will not output it. To see that it has been sorted, you can use print_r.
Create a variable called array that contains an array with three simple values. These values can be whatever you like.
Explicitly assign the string index of "third" to the third element.
Write a foreach loop that contains the following statement to print out each element of the array, along with its index:
echo "$indexPosition = $value.";