<?php echo "An Intro";    ?>

PHP is rendered before being sent to a browser.

<h1>Hello World</h1>

<h1><?php echo "Hello World"; ?></h1>

//save as index.php

To  browser, these are the same

Challenge:

Create a page with bootstrap. In the body, use php to echo out your first name in an h1 tag.

Then, use php to echo out "Hello World" into a p tag below the h1 tag.

Variables

We can save data in variables. Often, we will define our variables above our html.

<?php 

$weather = "rainy";
$temperature = "cold";

?>

<html>
<head>
    <title>My Page</title>
</head>
<body>
    <h1>The weather is <?php echo $weather ?></h1>
    <p>And the Temperature is <?php echo $temperature ?></p>
</body>
</html>

Challenge

Change your name and your comment to variables and print them in your DOM.

Comments

Comments help you remember your own code, and help other developers read your code.

<?php 

    echo "Hello World";
    
    //remember, because he drank a lot of coffee
    $name = "Joe";

 ?>

Whitespace

PHP don't care about your whitespace

<?php 

    $day = "Monday";    

    echo "Hello World";

 ?>
<?php 

    $day = "Monday";    




          echo "Hello World";

 ?>
<?php 

    $day   =    "Monday";    

    echo"Hello World";

 ?>

=

=

Data Types

Booleans are True (1) or False (0)

$bool = true;

Integers are numbers

$num = 4;

Strings are characters (words)

$name = "Liz";

Data Types

To Combine data types in php we use a period.

<?php

$name = "Ryan";

$age = 30;

echo "Hello " . $name . " how does it feel to be " . $age . " ?";
?>

Challenge:

Make 2 variables: 

Name

Status

 

Then make make a div, give it a box shadow, towards the top show the name of the author, then show the status.

Horray for the Array

Define an array

$array_example = array();

//same thing as 

$array_example = [];

Populate

$eye_color = array('blue', 'green', 'brown');

print_r($eye_color);

All arrays have key and value

Array(
[0]=>blue
[1]=>green
[2]=>brown
)

Get an Item

$eye_color = array('blue', 'green', 'brown');

echo $eye_color[0];

Custom Keys

This is called an associative array

$eye_color = array('Tom' => 'blue', 'Julia' => 'green', 'Mark' => 'brown');

echo $eye_color['Tom'];

Challenge

Make an array called post

make the first item the name and the second item the comment.

Then add the name and comment to your html.

Operators

<

>

<=

>=

= =

!=

= = =

 

 

Arithmetic

+

-

*

/

++

- -

Quiz

 

$a = 5;
$b = 3;
$c = true;
$d = false;
$e = 0;
var_dump ($a > $b);
var_dump ($a < $e);
var_dump ($a != $b);
var_dump ($e == $d);
var_dump ($e === $d);

Logical Operators

Liz and Will, send me your answers in your php file

$a = true;
$b = true;
var_dump($a && $b);
var_dump($a || $b);

$a = true;
$b = false;
var_dump($a && $b);
var_dump($a || $b);

$a = false;
$b = false;
var_dump($a && $b);
var_dump($a || $b);

Logical Operators

Liz and Will, send me your answers in your php file

$a = true;
$b = true;
var_dump(!$a && $b);
var_dump($a || $b);

$a = true;
$b = false;
var_dump($a && !$b);
var_dump($a || $b);

$a = false;
$b = false;
var_dump(!$a && !$b);
var_dump($a || $b);

Random Numbers

$num1 = rand(1,10);
echo $num1;

New Operation  Modulus

echo 5 % 3;
echo 4 % 2;
echo 4 % 7;
echo 9 % 2;
echo 21 % 6;

Conditional Statements

if(condition){
    //code to run
}elseif(condition){
    //code to run
}else{
    //code to run
}

Challenges

  • Generate 2 random numbers between 1 and 20
     
  • Echo Number 1 is ______
    Number 2 is _______  (hint, echo out html for a line break)
     
  • Echo out which number is bigger, or if they are the same.
     
  • Echo out if the first number is a factor of the second, if the second is a factor of the first, or if neither case is true.
     
  • Echo out if both numbers are even, if only one is even (and which one is) or if neither are even.

Loops

A couple of types

foreach - loop through each item in an array

while / do while loop - keep going until something is no longer true

for - repeat a fixed number of times

For Loop

for($counter = 0; $counter < 10; $counter++){
    echo $counter . "<br>";
}

Foreach

$colors = array('red', 'blue', 'green');
foreach($colors as $color){
    echo $color . "<br>";
}

More Realistic

$people = array(
		array(
                    'name' => 'Tom', 
                    'age' => 25, 
                    'profile_pic' => 'http://i686.photobucket.com/albums/vv224/ku1ture/Names/walken_zps81c6fc71.jpg'
                ),
		array(
                    'name' => 'Joe', 
                    'age' => 31, 
                    'profile_pic' => 'http://i751.photobucket.com/albums/xx160/emadhatter/Gifs/freakouteyes.gif'
                ),
		array(
                    'name' => 'Mary', 
                    'age' => 22, 
                    'profile_pic' => 'http://i972.photobucket.com/albums/ae208/CarterPaul/A%20March%20Assortment_%202010/walken_christopher.jpg'
                ),
		array(
                    'name' => 'Jessica', 
                    'age' => 45, 
                    'profile_pic' => 'http://images.fineartamerica.com/images-medium-large-5/christopher-walken-rick-fortson.jpg'
                ),
	);

Copy the following data, which looks almost exactly like what you would pull from a database.

In your body, run a foreach loop that prints an h1 tag with the person's name, a p tag with the person's age, and an image with the link as the src attribute.

Should look like this

Challenges

Fizz Buzz

  • Print out the integers 1 - 100, each on a different line
     
  • Now, if the number is a multiple of  3, it should say "Fizz". If the number is a multiple of 5, it should say "Buzz". If the number is a multiple of 3 and 5, it should say "Fizz Buzz". 

 

Challenges

Each new term in the Fibonacci sequence is generated by adding the previous two terms.

By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89

 

Print out the first 500 values of the Fibonacci Sequence

 

Challenges

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 601475143 ?

 

Functions

 

Usually, not always, but usually, you want to make a certain chunk of logic reusable.

 

This is what functions allow you to do. Instead of writing one big block of code, you make different parts reusable.

 

Starter Code

 

Make a for loop that cycles from 1 - 10. If the number is even, echo "I'm and even number!"

 

Functions

 
<?php 
    for($i = 1; $i <=10; $i++){

        if($i % 2 == 0){
            echo "I'm Even!";
        }
    }
?>

Functions

 

BOOOOOO!!!!!

 
<table id='table1'>
    <?php
        for($i = 1; $i <=10; $i++){
    
            if($i % 2 == 0){
                echo "I'm Even!";
            }
        }
    ?>
    </table>
    <table id='table2'>
    <?php
        for($i = 1; $i <=10; $i++){
    
            if($i % 2 == 0){
                echo "I'm Even!";
            }
        }
    ?>
    </table>
    <table id='table3'>
    <?php
        for($i = 1; $i <=10; $i++){
    
            if($i % 2 == 0){
                echo "I'm Even!";
            }
        }
    ?>
    </table>
?>

Functions

 

Hooray!!!

 
<?php 
    <table id='table1'>
        <?php alternate(); ?>
    </table>
    <table id='table2'>
        <?php alternate(); ?>
    </table>
    <table id='table3'>
        <?php alternate(); ?>
    </table>

<?php
    function alternate(){
        for($i = 1; $i <=10; $i++){
    
            if($i % 2 == 0){
                echo "I'm Even!";
            }
        }
    }
?>

Challenge

 

Create a custom function that does something, and then call that function in an application. 

 

Challenge

 

It is very rare that you build a function that doesn't accept an input. This is called an argument.

 

Arguments

 
<?php 
    sayAge(22);
    

    function sayAge($age){
        echo "Your age is " . $age;
    }
?>

Challenges

 

Create a function that can echo out the area of a square when given the side length of the square. 

 

Call that function for at least 3 different squares.

 

Returns

 

So to be honest, you don't actually just echo out info that often, you usually want it returned so it can be further worked with or manipulated.

 
<?php 
    $statement = sayAge(15);
    

    function sayAge($age){
        if(age > 30){
            return "You are already over 30";
        }else if($age < 30){
            return "You have " . 30 - $age . "years until you are 30";
        }else{
            return "You are 30!";
        }
    }
?>

Challenges

 

Create a function that can return the area of a square, and then echo that out.

Create a function that can figure out the perimeter of a rectangle given its width and height.

Create a function that can determine the cost to fence a rectangle given its perimeter, the cost per foot, and the sales tax.

Determine the largest area that can be fenced in for under $1000 if the cost per square foot for fencing is $8 and sales tax is 9.75%

 

 

Internal Functions

 

PHP has many functions built-in. 

 

For example, you can call strlen on any string and it will output the length of the string.

 
	$name = "Will";
	echo strlen($name);

List 2 examples where this function would be useful.

php.net

 

Don't take my word, ask php

 

 

php.net

 

Figure out what substr and strpos do. Then, write some code that uses each of these functions. 

 

Challenges

 
  1. Create a loop that echo's each name.
  2. Instead of echo, find the first 'a' in each school and save it to a new array. Then, print_r where that variable occurs. (you will need array_push)
  3. Using substr, make the first letter of the first word in each school capitalized (you will need strtoupper)
  4. Now make the first letter of every word capitalized. (You will need substr, strtoupper, and strpos).
 
$schools = array('nashville prep', 'liberty collegiate academy', 'nashville academy of computer science', 'reimagine prep', 'republic high school');

Data doesn't come from Storks

 

MySQL

Databases hold information in tables

 

Let's make one!

 

Now Make a Table

 

Name Columns

 

Name is what it will be called

Type is data type

length is # of bits used

A_I is auto increment and only for a primary key.

Name Columns

 

Now we need to learn some MySQL

The 4 Main Verbs:

 

SELECT

INSERT

UPDATE

DELETE

 

This is commonly referred to as CRUD for create, read ,update, delete. (Because SIUD isn't cool)

Name Columns

 

INSERT INTO `word`(`word_name`, `word_definition`, `difficulty`) VALUES ('veridical', 'truthful or veracious', 2)

Name Columns

 

Now go to browse

Name Columns

 

Insert 3 more words with either a difficulty of 1, 2, or 3

Now to get that info

 

SELECT * FROM `word` WHERE 1 = 1

SELECT * FROM `word` WHERE `word_id` = 4

SELECT * FROM `word` WHERE `difficulty` = 2

 

SELECT * FROM `word` WHERE `difficulty` = 2 AND word_name = 'oeuvre'

To Update

 

UPDATE `word` SET `word_definition` 'the art or science of telling time' WHERE word_id = 4

The most important concept in database design is uniqueness, or the guarantee that the data you are getting, deleting, or updating is doing what you expect. 

Bring it all together

 

PHP can execute MySQL code and talk to databases.

 

First, we have to connect to our database:

<?php

        $DB = connect('localhost', 'flashcards', 'root', '');
	
	function connect($host, $dbname, $user, $pass){
		try{
			$db = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $pass);
		}catch(PDOException $error){
			echo $error->getMessage();
			break;
		}
		return $db;
	}
?>

Now, the connection (user/pass) is saved in a variable called $DB.

Bring it all together

 

Next, what does it look like for php to write MySQL?

function getWords(){
	global $DB;
	$queryHandle = $DB->prepare("SELECT * FROM word WHERE 1=1");
	$queryHandle->execute();
	return $queryHandle;
}

Bring it all together

 

Let's call that function

$words = getWords()->fetchAll();
print_r($words);

Bring it all together

 

Let's call that function

foreach($words as $word){
    echo $word['word_name'];
    echo ", the definition is: ";
    echo $word['word_definition'];
}

Bring it all together

 

More control with HTML

foreach($words as $word){	?>

    <div class='word'><?php echo $word['word_name']; ?></div>
    <div class='word_def'><?php echo $word['word_definition'] ?></div>


<?php	}	?>

Bring it all together

 

Now create some CSS to make your word and word_def look good.

foreach($words as $word){	?>

    <div class='word'><?php echo $word['word_name']; ?></div>
    <div class='word_def'><?php echo $word['word_definition'] ?></div>


<?php	}	?>

Bring it all together

 

We can be more specific with our SQL

function getWordsByDifficulty($difficulty){
	global $DB;
	$queryHandle = $DB->prepare("SELECT * FROM word WHERE difficulty = :difficulty");
	$queryHandle->bindparam(":difficulty", $difficulty);
        $queryHandle->execute();
	return $queryHandle;
}


$words = getWordsByDifficulty(1)->fetchAll();

PUTTING

 

Create a Function that puts a word in the database (you'll need to pass the parameters and write the SQL code to Insert)

PUTTING

 

Create a Function that puts a word in the database (you'll need to pass the parameters and write the SQL code to Insert)

function putWord($word, $def, $dif){
	global $DB;
	$queryHandle = $DB->prepare("INSERT INTO word (word_name, word_definition, difficulty) VALUES (:word, :def, :dif)");
	$queryHandle->bindParam(":word", $word);
	$queryHandle->bindParam(":def", $def);
	$queryHandle->bindParam(":dif", $dif);
	$queryHandle->execute();
	return $queryHandle;
}

PUTTING

 

Now Test it Out

putWord('test', 'to try something out', 1);

PUTTING

 

Make a Form Out of It

<form method = "post" action=''>
    <h2>Word</h2>
    <input type='text' name='word'/>
    <h2>Definition</h2>
    <input type='text' name='definition'/>
    <h2>Difficulty</h2>
    <input type='text' name='difficulty'/>
    </br>
    <input type='submit' value='Enter the Word'/>
</form>

PUTTING

 

Now, when submit is hit, your browser will actually save the results in an array in a PHP variable called $_POST. Those results will be passed to the page you put in action (in this case, it just refreshes the page and passes the results to itself.

When this page loads, we want to check and see if $_POST as info in it.

 

 

if(isset($_POST['word'])){
    echo "A form submission was just made";
}

PUTTING

 

Now, if a form has been submitted, put the word in the database.

if(isset($_POST['word'])){
    putWord($_POST['word'], $_POST['definition'], $_POST['difficulty']);
}

ReFresh ReSubmits

 

Post Redirect Get

 

Create a new file called submit and move your (putWord call there).

We won't have access to our functions since they are in the index, so create another new file called functions and include it right after the connect.php

Make sure to include your functions.php in your index too.

now call your submit.php file in the action attribute of your form.

Lastly, use header('location index.php') at the last line of submit.php.

Make our flashcard system look good.

 
Made with Slides.com