PHP: Heredoc

Heredoc is an easy way to echo html and Javascript content without having to worry about “‘s or adding ?> <?php all over the place. A simple example is as follows:-

<?php

// Lots of PHP code goes here

$id=57;  // Store the passenger number

$string=<<<END
<span class="blah">Heading</span>
<span>
<select name="project" class="moreBlah" onchange="DoSomething($id);">
END;
echo $string;

// Lots more PHP code goes here

?>

$string will store everything until it gets to the ‘END;’. The ‘END;’ MUST be on a line on its own and must be the first thing on the line.
Also, worth noting that you can just add php variables in place without any additional formatting (see above, just stick a $id in the middle of a Heredoc and it’ll come out as the correct value)
Advertisement

JavaScript: Post content to a php page

So, you’re working in JavaScript and you need to pass content to a php page. On the JavaScript side, you do this: –

var formData=new FormData();
formData.append('myString', myString);

var url="./accessMyString.php";

xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST", url, true);
xmlhttp.send(formData);

This will store the string (or anything else you need to pass) into ‘myString’ in the FormData and will trigger “./accessMyString.php” passing the data as a POST.

In “accessMyString.php”, you’ll read content from the POST using the usual: –

$myString = $_POST['myString'];

 

 

 

PHP: Connect to a MySQL database, run a query and read a field

Quick reference for how to read a single field from a MySQL database in PHP: –

// Connect to the database
$mysqli = new mysqli(my.server.com', 'schemaName', 'password', 'databaseName') or die ('<b>Could not connect: </b>' . mysql_error());

// Query the database for the info we need
$results = $mysqli->query("SELECT * FROM myData WHERE id='$id'") or die($mysqli->error);

$content = $results->fetch_assoc();
$field = $content['fieldName'];

 

 

Using AJAX to handle updates to a specific entry in a list

Bit clunky as I’m in a hurry, but this is really just to remind me how to set this up when I do it next time.

So, imagine you have a list of div’s. Each div contains a visual representation of a task or a database entry that you’re showing to a user. You want to dynamically update content within each div depending on the selection made in a pulldown: –

JavaScript

The ‘onchange’ of the pulldown (select element) calls OnChange in the code below and triggers and update for the given index. sel is the select element and idIn is the index in the list of “div’s” (the 0 or 1 in “id=’div_0′”, “id=’div_1′” etc)

// ==========================================================================
// Use ajax to populate a div based on selection in a select element
// ==========================================================================
function OnChange(sel, idIn)
{
    xmlhttp = newXMLHttpRequest();
    xmlhttp.onreadystatechange = SubFunction(idIn); // Use a sub-function to handle the parameter passing

    // Pass in the selected index so we know which 'div' to replace
    var selected = sel.options[sel.selectedIndex].value;
    xmlhttp.open("GET", "./populate.php?s=" + selected, true);
    xmlhttp.send();
}

// ==========================================================================
// Handle the ajax callback
// ==========================================================================
function SubFunction(idIn)
{
    return function()
    {
        if (this.readyState == 4 && this.status == 200)
        {
            var el = document.getElementById("div_" + idIn);
            el.innerHTML = this.responseText;
        }
    };
}
PHP
<!-- populate.php would be something like... -->
<?php

// Build content based as required here. This will be inserted into the innerHTML of the appropriate div

$id = $_GET['s'];
echo "here's some content: ".$id;
?>
HTML
…and the HTML is set up quite simply as: –
$string=<<<END
    <select onchange='OnChange(this, $id)'>
        <option value="0">Option 1</option>
        <option value="1">Option 2</option>
        <option value="2">Option 3</option>
    </select>
END;
echo $string;

The $id is the id of the current row in the div list (matches the div element id)

 

 

 

Clamping dates in PHP

Needed to clamp a unix timestamp in PHP so I could use it for a database lookup. Quick source dump as follows: –

$time = date_create()->getTimeStamp(); // Get the initial timestamp
$mysqlDateTime = date("Y-m-d H:i:s", $time);
echo "Before: " . $mysqlDateTime . "<br />";

// Clamp to Minutes
$time = floor($time / 60) * 60;
$mysqlDateTime = date("Y-m-d H:i:s", $time);
echo "Clamp to Minutes: " . $mysqlDateTime . "<br />";

// Clamp to Hours
$time = floor($time / 3600) * 3600;
$mysqlDateTime = date("Y-m-d H:i:s", $time);
echo "Clamp to Hours: " . $mysqlDateTime . "<br />";

// Clamp to Days
$time = floor($time / 86400) * 86400;
$mysqlDateTime = date("Y-m-d H:i:s", $time);
echo "Clamp to Days: " . $mysqlDateTime . "<br />";

This gives the output: –

Before: 2018-02-03 23:45:24
Clamp to Minutes: 2018-02-03 23:45:00
Clamp to Hours: 2018-02-03 23:00:00
Clamp to Days: 2018-02-03 00:00:00

 

 

 

 

Constructor and Destructor in PHP

Example of constructor and destructor in PHP. Pretty simple syntax. Two preceding underscores.

<?php
class MyDestructableClass {
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
       print "Destroying " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();
?>

Auto-Loading classes in PHP

Back to getting up to speed on PHP. This is a quick snippet of code that’ll probably come in handy: –

<?php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>

This will auto-load a php file with the class name requested when the class is used. Assuming the naming standard is followed correctly this will be a handy little shortcut