PHP With MYSQL Essential Training Notes
After completing the Lynda.com recent PHP and MySQL training series, these are the notes that I’ve taken. Hopefully they can serve as a useful reference for you like they have me!
The difference between single and double quotes
Its better to use double quotes.
- You can add variables into double quotes and it will output the variable value.
- You can surround a variable in curly braces and it will still output the variable value
Single quotes will output the variable name.
String Functions
|
$string = “The quick brown fox jumped over the lazy dog†|
|
|
.= |
Concatenates a string |
|
str_repeat($string,2); |
Repeats a string twice |
|
strpos($string,â€brownâ€); |
Finds the position of the string |
There is two types of numbers:
- Integers (whole numbers)
- Floating point numbers (decimals)
Manipulating Numbers
Increment: $var++
Decrement: $var–
Random number: rand()
Random number with min/max: rand(1,10)
Float point Numbers
Floating point numbers are Decimal numbers! Ie. 3.14
$myfloat = 3.143864
Round($myfloat,2); would produce 3.14
Arrays
print_r($array) will display all variables in an array
if you surround it with <pre> </pre> tags it will display them nicely formatted.
in_array(needle,haystack) checks for an item in an array
Boolean & NULL
Boolean means true or false, 1 or 0 (respectively).
Isset($variable) tests the Boolean state of a variable and returns true or false
empty($variable) is similar to the opposite of isset($var).However it will return TRUE for the value 0 in both integer and string format (also NULL).
Constants
Similar to variables however they do not change!
define(“MAX_WIDTHâ€, 980);
echo MAX_WIDTH;
If & Else statements
When using if, and elseif statements, the final else will be the default if none of the if and elseif statements are true.
Switch Statements
Use when you need to test one variable, instead of writing many if / else statements.
Make sure you use break in the code or it will continue to search through the conditions
Switch ($a) {
case 0:
echo “hiâ€;
break;
}
3 Different types of loops: While, For & Foreach
While Loops
$count = 0
while ($count <= 10) {
echo $count;
$count++;
}
For Loops
Same as while loops.
Format is:
for (initial, test, each) {statement;}
example: for ($count, $count <= 10; $count++) {echo $count . “<br />â€; }
Foreach Loops (only used on arrays!!)
This is how you use each value
foreach ($array as $value) { statement; }
You can also loop through key, value pairs
foreach ($array as $key => $value) {statement;}
Pointers
To find the current position of the pointer in an array
current($array);
Move to the next position in an array
next($array);
Reset the pointer in an array
reset($array);
Using a while loop that moves the array pointer (similar to what you would do processing rows that are returned from a database)
$ages = array(4,8,15,22,29,33,52);
while ($age = current($ages)) { // this will loop while it can successfully assign an age from
statement;
next($ages);
}
User-Defined Functions
function name($arguments) { statement; }
Local Scope
Variables defined within a function, act as if they only exist within the function.
Global Scope
If you define a variable using the global $var syntax, then it will pull in variables outside of the function, and also make them available outside the function.
3 Ways to get information from a user
- GET
- POST
- COOKIE
Passing variables through GET & URLEncode
If you want to pass a character such as an ampersand (&) or space, you can include php in the link to urlencode the characters. For example:
<a href=â€test.php?name=<?php echo urlencode(“david&â€) ?>&surname=maraâ€> Link </a>
You only need to encode when using GET. Not with POST.
If you want to dynamically create an entire link, use rawurlencode($string) for everything before the ? in a link, and urlencode($string) for everything after.
Cookies
setcookie($name, $value, $expire);
Must come before ANY html, white space, tabs etc.. on a page.
Headers (and Page ReDirection),
Must come before ANY html, white space, tabs etc.. on a page.
Format:
header(header information);
How to write a page re-direct.
header(“Location: page.htmlâ€);
exit;
Output Buffering
Output buffering basically means that you can store up all the information of the page, and send it in one hit. This allows you to have headers appear in the body text of a page. This kind of ‘convenience’ comes at this cost of performance.
You can enable Output Buffering in the PHP.ini file.
You can also enable it without editing the PHP.ini file. You can do it within PHP.
ob_start(); // has to appear before any HTML is output if we’re sending headers
ob_end_flush();
CRUD – Create, Read, Update, Delete
Read
SELECT * FROM table WHERE column1 = ‘some_text’ ORDER BY column1, column2 ASC;
Create
INSERT INTO table (column1, column2, column3) VALUES (val1, val2, val3);
Note: Strings must have single quotes ‘ around them.
Update
UPDATE table SET column1 = ‘some_text’ WHERE id = 1;
mysql_affected_rows() will tell you how many rows were affected in the last update.
Delete
DELETE FROM table WHERE id = 1;
PHP Database Interaction in FIVE steps
1. Create a connection
$connection = mysql_connect(“localhost”, “root”, “password”);
2. Select a database
$db_select = mysql_select_db(“widget_corp”, $connection);
3. Perform database query
$result = mysql_query(“SELECT * FROM subjects”, $connection);
4. Use returned data (if any)
while ($row = mysql_fetch_array($result)) {
echo $row['menu_name'] . ” ” . $row['position'] . “<br />”;
}
5. Close connection
mysql_close($connection);
The 10 Essential MySQL commands
1. mysql_connect
Connects to a MySQL server
2. mysql_select_db
Selects a database
3. mysql_query
Used to query the database
4. mysql_error
You can echo mysql_error() to get the error returned by mysql
5. mysql_close
Close a MySQL connection
6. mysql_fetch_array
Retrieves the records in an array (can be accessed using associative keys)
Remember you have to loop through each record in the array.
7. mysql_num_rows
Retrieves the number of record rows retrieved from a query
8. mysql_affected_rows
Shows the affected number of rows from a query
9. mysql_real_escape_string
Escapes dangerous characters from entering your database
10. mysql_insert_id
Tells you the last inserted ID.
Text encoding and transformation
Anything you output to the browser should go through htmlentities especially if it’s coming from a database where users have entered the data.
htmlentities()
Converts any special characters to %lt; (html entities!)
strip_tags()
strips all html tags from text. You can allow specific tags as required:
strip_tags($content, “<b><br><p><a>â€);
This would allow the bold, break, paragraph and link tags to be the only html formatting on this text.
nl2br()
nl2br($content); will preserve any ‘enters’ or new lines in the text entered by the user.
Login / Authorisation
When structuring your query string to search if a username/password is correct in a database, do NOT select * information and return that. This is insecure and you do not need the password returned. Instead return perhaps the id and the username and any other information you will require.
Incorrect Auth Check:
$query = “SELECT * FROM users WHERE username = ‘{$username}’ AND hashed_password = ‘{$hashed_password}’”;
Correct Auth Check:
$query = “SELECT id, username FROM users WHERE username = ‘{$username}’ AND hashed_password = ‘{$hashed_password}’”;
Building an Application (CMS)
- Blue printing
- Build databases
- Build the folder structure
- Build layout
- Build navigation
- Setup page layout using includes/requires
- Break the pages into chunks and start building!
Things to keep in mind
- Don’t spend too much time refactoring or anything like that, find the balance between ‘perfect practice’ and ‘efficiency’. Don’t always go over-kill or you’ll never finish.
- Don’t repeat yourself coding
- Use htaccess to limit access to files which contain database logins/password details
- Refactoring – improving your code
- Use htaccess to limit access to your include files.