+ All Categories
Home > Documents > · Web viewMaking site dynamic. e.g. taken. from biofoam - index. HTML:

· Web viewMaking site dynamic. e.g. taken. from biofoam - index. HTML:

Date post: 26-Mar-2018
Category:
Upload: doanhanh
View: 224 times
Download: 4 times
Share this document with a friend
28
PHP Notes Making site dynamic e.g. taken from biofoam - index HTML: <div class="homepagefeat"> <div class="homepagefeattext"> <span> <strong class="greentext">Spray Foam</strong> <br /> <img src="<?php echo $settings['siteDir']; ?>images/sprayfoamthumb.jpg" alt="Bio Foam Spray Foam Insulation" title="Bio Foam Spray Foam Insulation"/> Spray Foam insulation is a polyurethane foam sprayed onto the home to insulate ceilings, walls and everywhere else one would expect insulation. As a result, it helps to keep the heat inside during the cold months and the hot air outside when it's warm. </span> </div> <a href="<?php echo $settings['siteDir']; ?>spray-foam.html" class="button">Find out more about Spray foam</a> </div> PHP: <?php $specials = content::find_by_parent_id(1, 1); foreach($specials as $special){ $page2.='<div class="homepagefeat">'; $page2.='<div class="homepagefeattext">'; $page2.='<span> <strong class="greentext">'.$special- >title1.'</strong><br />'; $page2.='<img src="'.$settings['siteDir'].'uploads/'.$special- >image.'" alt="Bio Foam Spray Foam Insulation" title="Bio Foam Spray Foam Insulation"/>'; $page2.='<p>'.$special->paragraph1.'</p>'; $page2.='</span>'; $page2.='</div>'; $page2.='<a href="'.$settings['siteDir'].'spray-foam.html" class="button">Find out more about Spray foam</a>'; $page2.='</div>'; } echo $page2; ?> Open php 1
Transcript

PHP Notes

Making site dynamice.g. taken from biofoam - index

HTML:<div class="homepagefeat"> <div class="homepagefeattext"> <span> <strong class="greentext">Spray Foam</strong> <br /> <img src="<?php echo $settings['siteDir']; ?>images/sprayfoamthumb.jpg" alt="Bio Foam Spray Foam Insulation" title="Bio Foam Spray Foam Insulation"/> Spray Foam insulation is a polyurethane foam sprayed onto the home to insulate ceilings, walls and everywhere else one would expect insulation. As a result, it helps to keep the heat inside during the cold months and the hot air outside when it's warm. </span> </div>

<a href="<?php echo $settings['siteDir']; ?>spray-foam.html" class="button">Find out more about Spray foam</a> </div>

PHP:<?php $specials = content::find_by_parent_id(1, 1);

foreach($specials as $special){$page2.='<div class="homepagefeat">';$page2.='<div class="homepagefeattext">';$page2.='<span> <strong class="greentext">'.$special-

>title1.'</strong><br />';$page2.='<img src="'.$settings['siteDir'].'uploads/'.$special-

>image.'" alt="Bio Foam Spray Foam Insulation" title="Bio Foam Spray Foam Insulation"/>';

$page2.='<p>'.$special->paragraph1.'</p>';$page2.='</span>';$page2.='</div>';$page2.='<a href="'.$settings['siteDir'].'spray-foam.html"

class="button">Find out more about Spray foam</a>';$page2.='</div>';

}echo $page2;?>

Open phpDeclare specials = content database looking at parent id to be 1Set specials to be specialSet page2 for all html replacing all named items to look at database e.g. $special->paragraph1 – this looks at paragraph1 in contents table for all items with parent id 1Img src- displays image, uploads is folder where image is saved then / look at database e.g. $special->image.Alt etc show what will be displayed when hover over imageNeed to close span & div in the order they are closed in HTML

1

PHP Notes

A href – adding link, don’t add links in table

$_POST['name']$_post [] is an associative array, create new variables for each post and make them equal to whatever is posted.

E.g.If you have a form where user enters products to order and quantity of order

Html:-

<html><body><h4>Tizag Art Supply Order Form</h4><form action="process.php" method="post"> <select name="item"> <option>Paint</option><option>Brushes</option><option>Erasers</option></select>Quantity: <input name="quantity" type="text" /> <input type="submit" /></form></body></html>

PHP

<html><body><?php$quantity = $_POST['quantity'];$item = $_POST['item'];

echo "You ordered ". $quantity . " " . $item . ".<br />";echo "Thank you for ordering from Tizag Art Supplies!";

?></body></html>

We create variables $quantity and $item and make them equal to whatever is posted in quantity and item on form.

Echo will output: – You ordered 6 brushes.Thank you for ordering with Tizag Art Supplies.

The full stops join all the different code together, between html and php.

Print_r($_POST);Enter this line of code where you are using post and then enter info on a form, this will then show the names on all the form and the info in them – this is used to check the data that is being sent to the server. (Make sure all info captured and being sent)

2

PHP Notes

It will look like this on top of webpageArray ( [name] => donna [tel] => 09097 [email] => jkjk [day1] => 2 [month1] => Mar [year1] => 2013 [day2] => 5 [month2] => Jun [year2] => 2014 [course] => lahinch old course [players] => 1 [time] => early [caddy] => yes [comments] => dfsfs [comments2] => )

<div class="product-left">If design been divided into left and right columns listing items, set up a count so that looks at number of items and divides number into number of columns, $featured_class = ($feat_count % 3) ? "main-product" : "main-product-end"; Above is if number of items can be divided into 3 do main-product else do main-product-end. e.g. from spiritualgiftworld.com \includes\featured

FunctionsA function is a block of code that can be executed whenever it is needed. Functions can be used if there is a block of code you are using on a number of pages, then create a function and use it e.g. header for website used on every page.

To create a functionFirst give function a name that will then be used every time you call it. You tell PHP that you are creating a function by putting the word function.e.g.<?phpfunction myCompanyMotto(){}?>

{ - tells php where function starts and ends.

<?phpfunction myCompanyMotto(){ echo "We deliver quantity, not quality!<br />";}echo "Welcome to Tizag.com <br />";myCompanyMotto();echo "Well, thanks for stopping by! <br />";echo "and remember... <br />";myCompanyMotto();?>

Above creates function myCompanyMotto()When company motto is called we echo out the slogan - "We deliver quantity, not quality!” Always start your function with the keyword function Remember that your function's code must be between the "{" and the "}" When you are using your function, be sure you spell the function name correctly

With functions you can send them information that the function can use by using parameters, these are inside the () and looks like a variable. Example below parameter is a person’s name and function concatenates name into a greeting string.

3

PHP Notes

Eg.

<?phpfunction myGreeting($firstName){ echo "Hello there ". $firstName . "!<br />";}myGreeting("Jack");myGreeting("Ahmed");myGreeting("Julie");myGreeting("Charles");?>

Output is:

Hello there Jack!Hello there Ahmed!Hello there Julie!Hello there Charles!

You can use multiple parameters

<?phpfunction myGreeting($firstName, $lastName){ echo "Hello there ". $firstName ." ". $lastName ."!<br />";}myGreeting("Jack", "Black");myGreeting("Ahmed", "Zewail");myGreeting("Julie", "Roberts");myGreeting("Charles", "Schwab");?>

e.g<?phpfunction mySum($numX, $numY){ $total = $numX + $numY; return $total; }$myNumber = 0;echo "Before the function, myNumber = ". $myNumber ."<br />";$myNumber = mySum(3, 4); // Store the result of mySum in $myNumberecho "After the function, myNumber = " . $myNumber ."<br />";?>

Output isBefore the function, myNumber = 0After the function, myNumber = 7

ArrayAn array is a data structure that stores more than one value in a single value. Arrays always start with a value of 0

4

PHP Notes

$employee_array[0] = "Bob";$employee_array[1] = "Sally";$employee_array[2] = "Charlie";$employee_array[3] = "Clare";

echo "Two of my employees are ". $employee_array[0] . " & " . $employee_array[1]; echo "<br />Two more employees of mine are " . $employee_array[2] . " & " . $employee_array[3];

$salaries["Bob"] = 2000;$salaries["Sally"] = 4000;$salaries["Charlie"] = 600;$salaries["Clare"] = 0;

echo "Bob is being paid - $" . $salaries["Bob"] . "<br />";echo "Sally is being paid - $" . $salaries["Sally"] . "<br />";echo "Charlie is being paid - $" . $salaries["Charlie"] . "<br />";echo "Clare is being paid - $" . $salaries["Clare"];

Above we are using the names of the employees to associate the array.

While loopswhile ( conditional statement is true){

//do this code;}

1. The conditional statement is checked. If it is true, then (2) occurs. If it is false, then (4) occurs.

2. The code within the while loop is executed.3. The process starts again at (1). Effectively "looping" back.4. If the conditional statement is false, then the code within is not executed and there is

no more looping. The code following the while loop is then executed like normal.

$brush_price = 5; $counter = 10;

echo "<table border=\"1\" align=\"center\">";echo "<tr><th>Quantity</th>";echo "<th>Price</th></tr>";while ( $counter <= 100 ) {

echo "<tr><td>";echo $counter;echo "</td><td>";echo $brush_price * $counter;echo "</td></tr>";$counter = $counter + 10;

}echo "</table>";

5

PHP Notes

Links When setting up links go to code for that page and set a href to look at directory, e.g. $settings[‘siteDir’], then . to add next code, then name of that page ‘news’ / . to add next code, variable that’s pointing at database - $news->url$article .= '<a href="' . $settings['siteDir'] . 'news/'.$news->url.'.html" class="news_readmore_link">Read More.. </a>' . PHP_EOL;

For each loop For each item in the specified array execute this code.

While a For Loop and While Loop will continue until some condition fails, the For Each loop will continue until it has gone through every item in the array.$employeeAges;$employeeAges["Lisa"] = "28";$employeeAges["Jack"] = "16";$employeeAges["Ryan"] = "35";$employeeAges["Rachel"] = "46";$employeeAges["Grace"] = "34";

foreach( $employeeAges as $key => $value){echo "Name: $key, Age: $value <br />";

}

Outputs:Name: Lisa, Age: 28Name: Jack, Age: 16Name: Ryan, Age: 35Name: Rachel, Age: 46Name: Grace, Age: 34For each element of the $employeeAges associative array I want to refer to the key as $key and the value as $value. You can use any variable name e.g.foreach( $employeeAges as $name => $age){

echo "Name: $name, Age: $age <br />";}The operator "=>" represents the relationship between a key and value. You can imagine that the key points => to the value.

6

PHP Notes

Google MapsTo set up google maps on a location/contact page, you need to get a unique API key for that map, e.g. of code Tintean.com location.To get key go to google API webpage, and go to API console and log in with gmail of that website – this can be found in CRM,- go to hosting and click on website, then click on gmail to get username and password. –If website not here then it does not have a google account yet. Use this username and password to log into google account, and go to API access, switch on google maps and get key."http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=ABQIAAAA5ZoIwCkeqKfkSzAbUA-LkxRXRHDzVIiff420URISRJiGylKO3BQUVWwcGqNTwvwhG7Ru05eLx3QMDA" type="text/javascript"></script>Add j script(In this script we have table with logo and address)var html = "<table width=234 border=0 cellpadding=0 cellspacing=0><tr><td colspan=2><img src=images/logo.jpg width=66 height=48 align=left></td><td width=10></td><td width=152 align=left nowrap style=color:#000000;><b>Tintean Theatre<br /></b><span class=PrivacyNotes>Hillview Close<br/>Ballybunnion <br />Kerry<br />Ireland</span><br></td></tr></table>";Then in page add Div – with size of map<div id="map" style="width: 670px; height: 378px; *width: 650px;margin: 20px 20px; "></div>

If getting error message when linking to next page, look to see what the URL says the page is, as it may be going to the wrong link, then do a find through code for that name.

7

PHP Notes

Dates in formsBelow is an example of how to add way of selecting dates on a form:-taken from Ballybunion guest house – enquiry.php

<div id="moreoptions"><div> <label>Date Of Play:- First Choice</label><br /> <select name="day1"> <option value="">Select Day </option> <option value=""> ---- </option> <?php for ($i = 1; $i <= 31; $i++) { echo '<option value="' . $i . '">' . $i . '</option>'; } ?> </select>

Above displays a box to select a day 1-31

<select name="month1"> <option value="">Select Month</option> <option value=""> ---- </option> <?php $array = array( '1' => 'Jan', '2' => 'Feb', '3' => 'Mar', '4' => 'Apr', '5' => 'May', '6' => 'Jun', '7' => 'Jul', '8' => 'Aug', '9' => 'Sep', '10' => 'Oct', '11' => 'Nov', '12' => 'Dec'); for ($i = 1; $i <= count($array); $i++) { echo '<option value="' . $array[$i] . '">' . $array[$i] . '</option>'; } ?> </select>

Above displays box to select month

<select name="year1"> <option value="">Select Year</option><option value=""> ---- </option> <?php $array = array( '1' => '2012', '2' => '2013', '3' => '2014', '4' => '2015', '5' => '2016', '6' => '2017', '7' => '2018', '8' => '2019', '9' => '2020'); for ($i = 1; $i <= count($array); $i++) { echo '<option value="' . $array[$i] . '">' . $array[$i] . '</option>'; } ?></select></div>

Above displays box to select year

8

PHP Notes

Databases

Design view – when creating tablesFields:-URL always text as can be very long, text is set to length 0,Hide always int length 1, not allowed to be NULL,ID always int length 11,Text area is always textNames, titles etc. varchar length 255Ids in table –default 0 (Ids shared with other tables)Parent_id int, length 11, default 0Level int, length 11, default 0Images varchar 255

If else statementIf display all this bypasses per_page (number of items on page) and goes to total count (shows all) else will display per_page

$per_page = $_GET['display'] ? $total_count : $per_page; If condition true false

Longer way of this below

if($_GET['display']){$per_page = $total_count;

}else{$per_page=$per_page;

}

9

PHP Notes

Adding sub categoriesFor pages that have sub pages, enter the fields: - parent_id, level into table.Both fields are integer, length 11, set default 0All products/ services etc are added to the one table, with the parent_id being the id of the parent product/service. If does not have a parent then parent_id will be 0, the level is the number of levels down it goes starting with 0.Change code in admin e.g. services / products so that $list -> article_link = “services.php” instead of “servicesupdate.php”. This is so that when the product is selected in admin it does not go to form for update but allows a sub category of that to be added.(look at Marcs code change for SScommunication.com)

Example code for displaying different pages on different levels (from sscommunication)<?php echo $service->display_content();

$serv_count = 1; foreach (services::find_by_parent_id($service->id) as $service2) { $page .=($serv_count % 2) ? '<div class="product-left">' : '<div class="product-

right">'; $page .= '<div class="product-title">';$page .= '<h3>'.$service2->name.'</h3>';$page .= '</div>';$page .='<div class="product-img"><a href="'. $settings['siteDir'] .'services/'.

$service2->url .'.html"><img src="'. $settings['siteDir'] .'uploads/'.$service2->image.'"alt="'.$service2->name.'" /></a></div>';

$page .= '<div class="product-desc">';$page .= '<p class="intro">'.$service2->description1.'</p>';$page .= '</div>';$page .= '<div class="product-more-details"><a href="'.

$settings['siteDir'].'services/'. $service2->url .'.html"><img src="'. $settings['siteDir'] .'images/more-blue.jpg" alt="More Information" /></a></div>';

$page .= '</div> <!-- end of class product-left -->';$serv_count++;

}echo $page;

?>

Displays content of services then for each record that has a parent id the same as id, set as service2, display info for that parent id. What content to be displayed in display_content is listed in the class as public function:–

public function display_content() { global $settings; $output = ($this->title) ? '<h1>' . $this->title . '</h1>' . PHP_EOL : null;

10

PHP Notes

$output .= $this->description1 . PHP_EOL; $output .= ( $this->title2) ? "<h2>" . $this->title2 . "</h2>" . PHP_EOL : null; $output .= $this->description2 . PHP_EOL; $output .= ( $this->title3) ? "<h3>" . $this->title3 . "</h3>" . PHP_EOL : null; $output .= $this->description3 . PHP_EOL; $output .= ( $this->title4) ? "<h4>" . $this->title4 . "</h4>" . PHP_EOL : null; $output .= $this->description4 . PHP_EOL; $output .= ( $this->title5) ? "<h5>" . $this->title5 . "</h5>" . PHP_EOL : null; $output .= $this->description5 . PHP_EOL; return $output; }

This function checks if there is title etc, display title else null.

Java scriptFound this by doing Google search for -js back and looked in a forum for JavaScript.javascript: history.go(-1)This script allows you to go back to the page before when going down levels on website, enter this instead of link.

To see databaseGo to Northern web technologies, look at servers select blackNight and then take username & password to use in blacknight, sign into blacknight using username and password from Northern web technologies, go to database find database go to access host, create new host and enter IP address (get this from copying from my IP address in Google search).To Backup databaseGo to database in navicat, click backup along top and then new backup – give backup a name.To create new databaseGo to blacknight and databases and create new database, enter database name, and click on generate passwaord. Add database as above so can see it in navicat.Update system class with database details, you can view these in blacknight by hitting users tab in that database and click on database.Connecting to database – use external host name

To Upload changesGo to start - filezilla – file – site manager fill in host, username and password then press connect( get this from Northern web technologies – click on servers and then blacknight e.g of what to use is under notes in CRM - Notesftp.d1014227.cp.blacknight.comusername: f107677password: q7H0_u3sP9r1!glA

) use the host, username and password from blacknight server. Once in filezilla the left-hand side is local, right hand side is were to upload to. Go to webspace, http docs and then find file were changes made, click each doc that was changed and drag over to right. Make sure upload side also shows the correct file by going again through webspace, http docs and

11

PHP Notes

file. Make sure when dragging over to place in exact same place. E.g. if change in admin/includes make sure dragged to admin/includes on right-hand side.

To add code to test.newrywebdesign.com

Add code to system class

if ($_SERVER['DOCUMENT_ROOT'] == "D:/nwtnetwork/development/websites") { // System variables $settings['siteDir'] = 'http://192.168.1.1/tintean.com/'; $settings['dbhost'] = 'mysql1246.cp.blacknight.com';

} elseif ($_SERVER['DOCUMENT_ROOT'] == "/usr/local/pem/vhosts/107677/webspace/httpdocs/test.newrywebdesign.com") { // System variables $settings['siteDir'] = 'http://www.test.newrywebdesign.com/tintean.com/';

// Database variables $settings['dbhost'] = 'mysql1246int.cp.blacknight.com';

$settings['email'] = '[email protected]';

Then upload in filezilla to test folder

ArrangeTo be able to arrange order of things in admin, so that they appear in a different order up front e.g. testimonials or pics of products etc.First go to admin and create a sort page e.g. theatrical costume hire/admin/pagessort or theatrical costume hire/admin/gallerysort. – make sure there is an orderid field in table. Also look at example in sheepbridge, content.Below checks if post then set orderid so that it adds one (orderid starts at 0)Header code moves back to testimonials page.if ($_POST) {

// Get array of product in orderforeach ($_POST['rows'] as $order_id => $rows_id): $page_sort = testimonials::find_by_id($rows_id); $page_sort->setOrderid( $order_id + 1 ); // Add 1 as array starts at zero. $page_sort->save();endforeach;

header('Location: testimonials.php?orderid=' .$orderid);}

Do a print_r($_post)inside if post and comment out the header so that it doesn’t return to testimonials to test that orderid is being updated.

12

PHP Notes

Make sure to have jquery stuff in jquery folder e.g. src="js/jquery/jquery-ui-1.8.2.custom.min.js" & src="js/jquery/jquery.js".

//Get All Fields

$allRecords = testimonials::find_all("orderid","","");

if ($allRecords) { $content_output = '<form method="post" action="' . $_SERVER['PHP_SELF'] . '">' . PHP_EOL; $content_output .= '<input type="image" src="images/btn_save.jpg" title="Save" alt="Save" style="width:136px; height:50px; float:right;" />' . PHP_EOL; // displays save button with styling $content_output .= '<ul id="sort_rows" class="menu_select">' . PHP_EOL;

//Make sure “sort_rows” styling is in style sheet

foreach ($allRecords as $record):

$content_output .= '<li><input type="hidden" name="rows[]" value="' . $record->getId() . '" />' . $record->getCompany() . '<br /> //displays company info<img src="images/icon_move.png" alt="move" /></li>' . PHP_EOL;

//displays move iconendforeach;

$content_output .= "</ul>" . PHP_EOL; $content_output .= '<input type="image" src="images/btn_save.jpg" title="Save" alt="Save" style="width:136px; height:50px; float:right;" />'. PHP_EOL; ; $content_output .= "</form>" . PHP_EOL;}else { $content_output = "<p>Please add products before beginning</p>";}

// Build Page

echo $content_output;

?><?php include_once("includes/footer.php") ?>

Update admin/testimonials so that we are linking to sort page<?php $content = $page_message . '<a href="pagessort.php"><img src="images/icon_arrange.png" alt="Arrange" title="Arrange" border="0" /></a>'. PHP_EOL;

Once admin is working, update front end so that displays by orderd.e.g.testimonials

13

PHP Notes

$allRecords = testimonials::find_by_sql("SELECT * FROM testimonials WHERE hide=0 AND comment<>'' ORDER BY orderid");e.g. gallery-productions$allRecords = galleryimages::find_by_sql("SELECT galleryimages.orderid, galleryimages.name, galleryimages.image FROM galleryimages LEFT JOIN galleryproductions ON galleryproductions.id=galleryimages.catid WHERE galleryproductions.url = '$urlname'ORDER BY orderid"); //ORDER BY orderid

14

PHP Notes

HTML Comment<!-- This is an HTML Comment -->

ClassBasic class definitions begin with the keyword class, followed by a class name, followed by a pair of curly brackets which enclose the definitions of the properties and methods belonging to the class. The class name can be any valid label which is a not a PHP reserved word. A valid class name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*. A class may contain its own constants, variables (called "properties"), and functions (called "methods"). Example #1 Simple Class definition<?phpclass SimpleClass{    // property declaration    public $var = 'a default value';

    // method declaration    public function displayVar() {        echo $this->var;    }}?> Example 2// class definitionclass Bear {    // define properties    public $name;    public $weight;    public $age;    public $sex;    public $colour;

    // constructor    public function __construct() {        $this->age = 0;        $this->weight = 100;    }

    // define methods    public function eat($units) {        echo $this->name." is eating ".$units." units of food... ";        $this->weight += $units;    }

    public function run() {        echo $this->name." is running... ";    }

15

PHP Notes

    public function kill() {        echo $this->name." is killing prey... ";    }

    public function sleep() {        echo $this->name." is sleeping... ";    }}

// extended class definitionclass PolarBear extends Bear {

    // constructor    public function __construct() {        parent::__construct();        $this->colour = "white";        $this->weight = 600;    }

    // define methods    public function swim() {        echo $this->name." is swimming... ";    }}

mysql_fetch_array()expects parameter 1This error message means that there is a problem reading from database, go to dao and uncomment – echo query below //*** Function: query, Purpose: Execute a database query *** public static function query($query) { // echo $query; return mysql_query($query); }– This will show where error is coming from e.g.

SELECT * FROM admin WHERE name = 'admin' AND pass = '66351c50e51508df463fa91b5dee2277' AND enabled = 0SELECT COUNT(*) FROM contentSELECT * FROM content ORDER BY orderid Asc LIMIT 20ORDERBY order id when no order id in table

JS scripts should go above headerIf you can’t position above header put JS script in functions and call the function above where header is called.

$fileThis is an array that holds all info.

16

PHP Notes

Htaccess

[QSA] added to the end of each line to grab extra querys on end of URL e.g. lynchroofing.com/projects.html?location=Galway&type=0&architect=0&search.x=40&search.y=7[L] – added to end of line so that stops at that line and doesn’t continue to lines of code below

Crtl ‘ – lets you find end of {

Search Box – Drop down formExample is in Lynchroofing.com – for projectsUpdate projects form in includes/search

<form action="<?php echo $settings['siteDir'];?>projects.html" method="get" name="projectform" class="projectform" > <label for="location" class="projectlabel">Location</label> <select id="location" name="location" class="drop-down"> <option value="0">All</option> <?php echo projects::getLocationOptions($_GET['location']); ?> </select> <br /> <label for="type" class="projectlabel">Type</label> <select id="type" name="type" class="drop-down"> <option value="0">All</option> <?php echo projects::getTypeOptions($_GET['type']); ?> </select> <br /> Create getLocationOptions functions in project class

public function getLocationOptions($val=null) { $sql = "SELECT DISTINCT location FROM " . self::$table_name. " ORDER

BY location"; $locations = self::find_by_sql($sql); if($locations){ foreach($locations as $location){

$output .= '<option '.selected($location->location,$val).'>'.$location->location.'</option>'.PHP_EOL;

} return $output; }

}

Selects all the distinct locations from the table for each location sets selected location and displays locations. Select is a function in functions.

Then when goes to projects page it gets location $location = $_GET['location']; and then finds all active – update find_all_active function –

public static function find_all_active($type=null, $architect=null, $location=null) {

17

PHP Notes

$sql = "SELECT * FROM " . self::$table_name . " WHERE hide=0 ";$sql .= ($type) ? " AND type ='".$type."'" : null;$sql .= ($location) ? " AND location ='".$location."'" : null;$sql .= ($architect) ? " AND architect ='".$architect."'" :

null;$sql .= " ORDER BY name";

return self::find_by_sql($sql); }

Project Map

Example of this in Lynch Roofing –Use J script and then add a foreach to the script to pull all projects from database. When working with maps make sure to always have initialize and then use this again to load

<script type="text/javascript">window.onload = initialize();</script>

$page_js = '<script src="http://maps.googleapis.com/maps/api/js?

key=AIzaSyAIhPYqrNJ9VlR_OKbhzUHoR_Ta9RumCFU&amp;sensor=false" type="text/javascript"></script>

<script type="text/javascript"> function initialize() { var myOptions = { center: new google.maps.LatLng(53.54683559190011,-7.921142578125), zoom: 7, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("projects-map"),myOptions);

var infowindow = new google.maps.InfoWindow();

// Home markerget_marker(53.902543,-8.581573,"Lynch

Roofing","images/logo.jpg","about.html","Ballaghadereen");';

foreach ($projects as $project):$default_image = projectgallery::get_default_image($project-

>id);$map_image = ($default_image) ? "uploads/thumbs/".

$default_image : "images/map_thumb.jpg";$page_js .='get_marker( '.$project->map_coords.', "'.$project-

>name.'", "'.$map_image.'", "projects/'.$project->url.'.html","' . $project->location . '" );';

endforeach;

$page_js .= '

function get_marker(lat,long,title,image,url,location){

18

PHP Notes

var marker = new google.maps.Marker({position: new google.maps.LatLng(lat,long),map: map,icon: "images/mapicon.png"

});

var contentString = "<div class=\"map_popup\"><img src="+image+" />"+title+ "<br />"+location+"<br /><a href=\"'.$settings['siteDir'].'"+url+"\">Click to view</a></div>";

google.maps.event.addListener(marker, "click",

(function(marker) {return function() {infowindow.setContent(contentString);infowindow.open(map, marker);}})(marker));

} }

</script>';

url sub pages

Example of code from sscommunication /project-details to allow parent and child subpages to be displayed in url - sscommunication.com/products/bluetooth-car-kits/parrot-ck3100-lcd.html

$pages = getUrl();if(count(getUrl()) > 4){

$pages = (array_slice($pages, 0, -1));$pagestring = implode($pages, '/');$previous = strrchr($pagestring, '/');

}else{$previous = null;

}

Sql min function

SELECT MIN(column_name) FROM table_name

SELECT MIN(OrderPrice) AS SmallestOrderPrice FROM Orders

Function with a foreach inside

public function getLocationOptions($val=null) { $sql = "SELECT DISTINCT location FROM " . self::$table_name. " ORDER

BY location"; $locations = self::find_by_sql($sql); if($locations){ foreach($locations as $location){

19

PHP Notes

$output .= '<option '.selected($location->location,$val).'>'.$location->location.'</option>'.PHP_EOL;

} return $output; }

}

Images not uploading

If images are not uploading on live site to uploads folder but are on local site, then go to filezilla and right click uploads on live side, click on file permissions and click on write for all permissions then click on recusrse into sub directories and OK

Sample listener to receive info from paypal

// read the post from PayPal system and add 'cmd'$req = 'cmd=' . urlencode('_notify-validate'); foreach ($_POST as $key => $value) {

$value = urlencode(stripslashes($value));$req .= "&$key=$value";

}  $ch = curl_init();curl_setopt($ch, CURLOPT_URL, 'https://www.paypal.com/cgi-bin/webscr');curl_setopt($ch, CURLOPT_HEADER, 0);curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);curl_setopt($ch, CURLOPT_POSTFIELDS, $req);curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);curl_setopt($ch, CURLOPT_HTTPHEADER, array('Host: www.paypal.com'));$res = curl_exec($ch);curl_close($ch);  // assign posted variables to local variables$item_name = $_POST['item_name'];$item_number = $_POST['item_number'];$payment_status = $_POST['payment_status'];$payment_amount = $_POST['mc_gross'];$payment_currency = $_POST['mc_currency'];$txn_id = $_POST['txn_id'];$receiver_email = $_POST['receiver_email'];$payer_email = $_POST['payer_email'];  if (strcmp ($res, "VERIFIED") == 0) {

// check the payment_status is Completed// check that txn_id has not been previously processed// check that receiver_email is your Primary PayPal email// check that payment_amount/payment_currency are correct// process payment

}else if (strcmp ($res, "INVALID") == 0) {

// log for manual investigation}

20

PHP Notes

Sandbox

https://developer.paypal.com/

url to test ipn simulator in paypal sandbox

http://test.newrywebdesign.com/paypal_listener/listener.php

website explaining how to grey out form field

http://www.sitepoint.com/forums/showthread.php?61823-Form-Field-Inaccessable-quot-Greyed-Out-quot-until-checkbox-clicked

Reload page onclick in a form

<input type="checkbox" id="radio" name="radio" value = "diffaddress" onClick = "javascript:window.location.reload()"/>

How to replace space with +Use string replace$search = str_replace(" ", "+", $popularsearch->name);

SQLTo update all fields in a row-update table price_currency to set currency id = 2

UPDATE `price_currency` SET `currency_id`='2'

To insert data from one table to antoher where ids math use update

UPDATE suppliers

SET supplier_name =

( SELECT customers.nameFROM customersWHERE customers.customer_id = suppliers.supplier_id)

Reload form to same page

<?php echo $PHP_SELF; ?>

Sql

UPDATE productsLEFT JOINproducts_oldON products.id = products_old.idSET products.weblink10desc = products_old.weblink10desc

21

PHP Notes

INSERT INTO subcategories (id, cat_id, name, url, hide, range, catcode, parentcode) SELECT id, cat_id, name, url, hide, range, catcode, parentcode FROM subcategories_old;

Searching for fields within a foreach loop – taken from fallers.ie/admin/products

if ($allProducts) {//Array to list records$listvalues = array();foreach ($allProducts as $record) : $listvalues[] = array("ID" => $record->product_id, "Values" => array(products::get_code($record->product_id), products::get_name($record->product_id)), "Hide" => $record->hide);

endforeach;}

22


Recommended