waltery.com/PHP_Notes.php


String Functions


strlen() 
substr(string, start, length)0 based 
str_replace(find, replace, string, count) This function is case-sensitive.
Use str_ireplace() to perform a case-insensitive search.
"Hello Peter!" = str_replace("world","Peter","Hello world!")
Count: Optional. A variable that counts the number of replacements
  
strpos($haystack, $needle, [offset])funtion to find location of needle in haystack
  
trim(), ltrim(), rtrim()
strtolower()"test" = strtolower("TesT")
strtoupper()"TEST" = strtolower("TesT")
ucfirst()first character of a string to uppercase
"Hello world" = ucfirst("hello world")
ucwords()first character of each word to uppercase
"Hello World" = ucwords("hello world")
  
number_format()1,000,000.00 = number_format("1000000",2)
str_pad(string, length, pad_string, pad_type)$str = "Hello World";
str_pad($str,20,".") = Hello World.........
str_pad($str,20,".",STR_PAD_LEFT) = .........Hello World
str_pad($str,20,".:",STR_PAD_BOTH) = .:.:Hello World.:.:.
addslashes()backslashes in front of single quote ('), double quote (")
, backslash (\), NULL
bin2hex()"48656c6c6f20776f726c6421" = bin2hex("Hello world!")
htmlentities()function converts characters (>) to HTML entities (>).
strcmp()compares two strings. returns 0 equal, < s1 < s2, > s1 > s2
explode(delimeter, string)breaks the string into array on the basis of delimiter passed.
implode(delimeter, array)join array elements with a string on the basis of delimiter passed.
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
Output: "Hello World! Beautiful Day!"
  

  $val = $_GET['cname'];

  if (strlen($val) > 0) {
    print "Color Group: $val";
  } else {
    $val = '';
  }

    $first = substr($tile, 17, 4);


<  >
    if ($first == $val) {
      print '<a href="bgtiles.php?fname='. $tile .'">';
      print '<div class="cblock" style="background-image:url('.$tile.');background-repeat: repeat">';
      print "<span>$cnt - $tile - $first </span><br /><br />\n";
      print '</div></a>';
    }
      

Date, Time


  time() - Returns a current Unix timestamp

  date() - formats a timestamp into a string

  date_create() - Returns a new DateTime object
  	$date = date_create("2016-09-15");

  date_format(object,format) - Returns a formatted string 
  	echo date_format($date,"Y/m/d H:i:s");

  $date1=date_create("2013-03-15");
  $date2=date_create("2013-12-12");
  $diff=date_diff($date1,$date2);  	- Returns the difference between two DateTime objects
  	- Returns a DateInterval object 
  	// %a outputs the total number of days
	echo $diff->format("Total number of days: %a.");

  strtotime() - Parses an English textual date or time into a Unix timestamp

  function mysqldate() {
    $timestamp = time();
    return date( 'Y-m-d H:i:s', $timestamp );
  } // End of mysqldate
  -------------------------------
  date_sunrise() - sunrise for a given day / location

  date_sunset() - sunset for a given day / location

  $sun_info = date_sun_info(time(), $lat, $lon);
  
  echo 'Date_sunrise ' . date_sunrise(time(), SUNFUNCS_RET_STRING, 61.21, -149.52) . '
';

Astronomical Twilight: 07:17
Nautical Twilight: 08:10
Civilian Twilight: 09:10
Sunrise: 10:15
  
Sunset: 15:43
Civilian Twilight: 16:48
Nautical Twilight: 17:48
Astronomical Twilight: 18:41

Date Format Codes

$mysqldate = date( 'Y-m-d H:i:s', $timestamp );

CodeDescription
YFour digit year
yTwo digit year
  
mMonth number, leading zeros (01 to 12)
MMonth abbreviation (three letters)
FFull month name (January through December)
nMonth number, without leading zeros (1 to 12)
  
dDay of the month (01 to 31)
DDay abbreviation (three letters)
jDay of the month without leading zeros (1 to 31)
lFull Day Name (lowercase 'L')
SSuffix for the day (2 chars: st, nd, rd or th. Works well with j)
wDay number (0 for Sunday through 6 for Saturday)
  
HHour 24-hour format (00 to 23)
iMinutes with leading zeros (00 to 59)
sSeconds, with leading zeros (00 to 59)
GHour 24-hour format (0 to 23)
  
g12-hour hour format (1 to 12)
h12-hour hour format (01 to 12)
aLowercase am or pm
AUppercase AM or PM
  
NDay number (1 for Monday through 7 for Sunday)
tThe number of days in the given month
zThe day of the year (0 through 365)
WThe ISO-8601 week number of year (weeks starting on Monday)
LWhether it's a leap year (1 if it is a leap year, 0 otherwise)
oThe ISO-8601 year number
eThe timezone identifier (Examples: UTC, Atlantic/Azores)
I(capital i)Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise)
ODifference to Greenwich time (GMT) in hours (Example: +0100)
TTimezone setting of the PHP machine (Examples: EST, MDT)
ZTimezone offset in seconds. The offset west of UTC is negative, and the offset east of UTC is positive (-43200 to 43200)
BSwatch Internet time (000 to 999)
cThe ISO-8601 date (e.g. 2004-02-12T15:19:21+00:00)
rThe RFC 2822 formatted date (e.g. Thu, 21 Dec 2000 16:01:07 +0200)
UThe seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)


Head


include('includes/head.php');

<?php include($_SERVER['DOCUMENT_ROOT'].'/includes/l_menu.php'); ?>

<link rel="stylesheet" type="text/css" media="screen" href="css/datePicker.css">
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="./css/member.css">

<style type="text/css">
/* -------------------------------------------------------------- */

table.edittab  {
  border:1px solid grey;
  border-collapse: collapse;
  width: 775px;
  background: #000 url(images/common/blue_grad_2012_11_09.jpg) repeat;
/*  background-color:#E0FFFF;   */
  }
/* -------------------------------------------------------------- */
</style>


<script type="text/javascript" src="scripts/jquery.validate.js" ></script>

<script type="text/javascript" charset="utf-8">
$(document).ready(function() {

  $( "#menu" ).menu();

  $( "#datepicker" ).datepicker({
      changeMonth: true,
      changeYear: true
  });

});
</script>


PDO


require '../../dbcred.php';

try {
  $dbh = new PDO($dsn, $user, $password);

  $sql = "Select disclaimertext from disclaimer WHERE id in ( :key ) ";

  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $stmt = $dbh->prepare($sql);
  $stmt->bindParam(':key', $key, PDO::PARAM_STR);

  $stmt->execute();

  /* Count the number of columns in the result set */
  $colcount = $sth->columnCount();
  print("After execute(), result set has $colcount columns \n");

  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo $row['disclaimertext']."
"; } } catch (PDOException $e) { echo 'PDO Exception Caught. '; echo 'Error with the database: <br />'; echo 'SQL Query: ', $sql; echo 'Error: ' . $e->getMessage(); } PDO::PARAM_BOOL boolean PDO::PARAM_NULL SQL NULL PDO::PARAM_INT SQL Integer PDO::PARAM_STR SQL CHAR, VARCHAR PDO::PARAM_LOB SQL large object data type PDO::PARAM_INPUT_OUTPUT Specifies that the parameter is an INOUT parameter for a stored procedure. You must bitwise-OR this value with an explicit PDO::PARAM_* data type.

PDO Bind Columns

Binding columns in the result set to PHP variables is an effective way to make the data contained in each row immediately available to your application. The following example demonstrates how PDO allows you to bind and retrieve columns with a variety of options and with intelligent defaults.


function readData($dbh) {
  $sql = 'SELECT name, colour, calories FROM fruit';
  try {
    $stmt = $dbh->prepare($sql);
    $stmt->execute();

    /* Bind by column number */
    $stmt->bindColumn(1, $name);
    $stmt->bindColumn(2, $colour);

    /* Bind by column name */
    $stmt->bindColumn('calories', $cals);

    while ($row = $stmt->fetch(PDO::FETCH_BOUND)) {
      $data = $name . "\t" . $colour . "\t" . $cals . "\n";
      print $data;
    }
  }
  catch (PDOException $e) {
    print $e->getMessage();
  }
}
readData($dbh);

The above example will output:

apple   red     150
banana  yellow  175
kiwi    green   75
orange  orange  150
mango   red     200
strawberry      red     25

PDO fetch

PDOStatement::fetch - Fetches the next row from a result set


$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Exercise PDOStatement::fetch styles */
print("PDO::FETCH_ASSOC: ");
print("Return next row as an array indexed by column name\n");
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
print("\n");

print("PDO::FETCH_BOTH: ");
print("Return next row as an array indexed by both column name and number\n");
$result = $sth->fetch(PDO::FETCH_BOTH);
print_r($result);
print("\n");

print("PDO::FETCH_LAZY: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_LAZY);
print_r($result);
print("\n");

print("PDO::FETCH_OBJ: ");
print("Return next row as an anonymous object with column names as properties\n");
$result = $sth->fetch(PDO::FETCH_OBJ);
print $result->NAME;
print("\n");

PDO fetchAll

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name.


Example #1 Fetch all remaining rows in a result set

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);

The above example will output something similar to:

Fetch all of the remaining rows in the result set:
Array
(
    [0] => Array
        (
            [NAME] => pear
            [0] => pear
            [COLOUR] => green
            [1] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [0] => watermelon
            [COLOUR] => pink
            [1] => pink
        )

)

-----------------------------------------------------------------------------
Example #2 Grouping all values by a single column

The following example demonstrates how to return an associative array grouped
by the values of the specified column in the result set. The array contains
three keys: values apple and pear are returned as arrays that contain
two different colours, while watermelon is returned as an array that contains only one colour.

$insert = $dbh->prepare("INSERT INTO fruit(name, colour) VALUES (?, ?)");
$insert->execute(array('apple', 'green'));
$insert->execute(array('pear', 'yellow'));

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Group values by the first column */
var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP));

The above example will output something similar to:

array(3) {
  ["apple"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(3) "red"
  }
  ["pear"]=>
  array(2) {
    [0]=>
    string(5) "green"
    [1]=>
    string(6) "yellow"
  }
  ["watermelon"]=>
  array(1) {
    [0]=>
    string(5) "green"
  }
}

-----------------------------------------------------------------------------
Example #4 Instantiating a class for each result

The following example demonstrates the behaviour of the PDO::FETCH_CLASS fetch style.

class fruit {
    public $name;
    public $colour;
}

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit");
var_dump($result);

The above example will output something similar to:

array(3) {
  [0]=>
  object(fruit)#1 (2) {
    ["name"]=>
    string(5) "apple"
    ["colour"]=>
    string(5) "green"
  }
  [1]=>
  object(fruit)#2 (2) {
    ["name"]=>
    string(4) "pear"
    ["colour"]=>
    string(6) "yellow"
  }
  [2]=>
  object(fruit)#3 (2) {
    ["name"]=>
    string(10) "watermelon"
    ["colour"]=>
    string(4) "pink"
  }
}

Loops


for (init; condition; increment)
  {
  code to be executed;
  }

for ($i = 1; $i < = 5; $i++)
  {
  echo "The number is " . $i . "<br />";
  }

/* -------------------------------------------------------- */

while($i<=5)
  {
  echo "The number is " . $i . "<br />";
  $i++;
  }

/* -------------------------------------------------------- */
The do...while statement will always execute the block of code once.

do
  {
  code to be executed;
  }
while (condition);

/* -------------------------------------------------------- */

foreach ($x as $value)
  {
  echo $value . "<br />";
  }

/* -------------------------------------------------------- */

Other


  switch (strtoupper($membtype)) {
    case 'C':
      $class= 'contact';
      break;
    case 'S':
      $class= 'sponsor';
      break;
    case 'X':
      $class= 'exmember';
      break;
    default:
      return '';
  }
/* -------------------------------------------------------- */

Operators


x % ymodulus Remainder of x divided by y
a .= ba = a . b Concatenate two strings
++ xPre-increment Increments x by one, then returns x
x == yEqual
x != yNot equal
x >= yGreater than or equal to
x <= yLess than or equal to
x And y&& And
x Or yX || Y Or
! xNot X


Entities

     
 &nbsp;
<&lt;
>&gt;
'&apos;
"&quot;
&&amp;
©&copy;
°&deg;
«&laquo;
»&raquo;
×&times;
÷&divide;
¼&frac14;
½&frac12;
¾&frac34;
±&plusmn;
¢&cent;


OOP


  include ('class/events.inc.php');
  $events = new cevents();
  print $events->Page_Div('Future Events');
  print $events->Show_Events('future', $us_first_name);

/* -------------------------------------------------------- */

Misc

--- Mobile_Detect ---

MobileDetect - Big Screen.

IP Address: 3.129.194.30

Rande
This is Where the caption goes, Donec sollicitudin mi sit amet mauris. Nam elementum quam

Current File: /shortcuts/php_notes.php

Updated on : 1969/12/31 14:00

Directory



$handle = opendir('docs/newsletters');
if ($handle) {
  while (false !== ($file = readdir($handle))) {

    $first3 = substr($file, 0, 3);
    if ($first3 == "EAA") {
      $newsltrs[] = 'docs/newsletters/'.$file;
    }
  }
}

arsort($newsltrs);

$lastyear="NEW";

foreach($newsltrs as $news) {

  $year = substr($news, 20, 2);
  $mon = substr($news, 23, 2);

  if ($year <> $lastyear) {

    if ($lastyear !== "NEW") {
      print "</ul>\n";
    }
    print "<h3>20$year</h3>\n";
    print "<ul>\n";
  }
  $fsraw = filesize($news);
  $fs = $fsraw / 1048576;
  print "<li><a href='$news'>" . flong_month( $mon ). "</a> - (" . number_format ($fs, 1) . " mb pdf)" . "</li>\n";
//  readfile($news);
  $lastyear = $year;
}
print "</ul>\n";

/* -------------------------------------------------------- */

Files


The rename() function renames a file or directory - returns TRUE on success, or FALSE on failure.

  rename(oldname,newname);    rename("images","pictures");

  copy(file,to_file);         copy("source.txt","target.txt");

          If the destination file already exists, it will be overwritten.

  is_dir(file)  - is directory
  is_file(file) - is file

  if (file_exists($fileName)) {


/* -------------------------------------------------------- */

Disclaimer

PDO Exception Caught. Error with the database:
SQL Query: Error: SQLSTATE[HY000] [1045] Access denied for user 'waltery_waltall'@'localhost' (using password: YES)

-----------------------------------------------------------------------------