PHP-CLi basic functions

PHP-CLi basic functions

The following functions can help you quickly get going with a CLi project.

#!/usr/bin/env php
<?php
 
// Clear the terminal screen.
// Using the passthru function to fun the local system's clear command
// returns none
function clearTerm()
{
        passthru('clear');
}
 
// Short wrapper for fwrite
// Permits easier explicit writing to STDOUT
// returns none
function toSTDOUT($string)
{
        fwrite(STDOUT,$string);
}
 
// Output with default prefix and suffix
function sendOutput($output = '> ',$NL=PHP_EOL)
{
        toSTDOUT($output.$NL);
}
 
// New exit allowing simple debugging via var_dump()
// Otherwise exits normally
// returns none
function nuExit($str=0)
{
        clearTerm();
        if(is_array($str))
        {
                var_dump($str);
                exit(0);
        }
        exit($str.PHP_EOL);
}
 
// get a trimmed string from STDIN
// returns a string
function getSTDIN()
{
        return trim(fgets(STDIN));
}
 
// get input with a prompt
// built in quit catching
// returns a string or nothing
function getInput($prompt = "> ", $silent = FALSE)
{
        if( ! $silent) { sendOutput($prompt); }
        $var = getSTDIN();
 
        if('quit' == $var) nuExit('Quit entered at prompt.');
 
        return $var;
}
 
// Check input with regex
// returns boolean
function checkMatch($needle,$haystack)
{
        if(preg_match('/^'.$needle.'$/i',$haystack)) return TRUE;
        return FALSE;
}

Now that we have those in place, something like the following is easy enough.

#!/usr/bin/env php
<?php
 
// include the functions here
include "functions.file.php";
 
clearTerm();
sendOutput('Hi there, welcome to a simple CLi functions tutorials.');
$response = getInput('Have you done this before?');
if( checkMatch('([Yy][Ee]?(?:[Ss]|[Aa])?)',$response) )
{
        nuExit('Okay, bye!');
}
else
{
        sendOutput('Welcome to PHP-CLi.');
        nuExit();
}

That’s it.

By Mike on December 18, 2014 | PHP, Tutorials
Tags: , , , ,

PHP Tutorial: Ternary Logic, (?:) shorthand if/else

So you may have been looking through a PHP script you downloaded and seen a bit of logic that you didn’t even know was possible. What you probably saw was Ternary Logic, it had a question mark and a colon (?:) in use, making it more confusing for you. Well not any more, here comes the clarifier. The easiest way to do this is take a long hand if/else and then create a ternary logic statement to match it. So let’s try that.

<?php
/* we'll set a $gender variable, typically you will already
 have your variable set elsewhere */
$gender = 'male';
 
/* so we'll create a basic if/else */
if ( $gender == 'male' ) {
    $title = 'Mr';
} else {
    $title = 'Mrs';
}
echo $title;
/* that makes sense right? */
/* we can shorten that easily, using ternary logic */
$title = ($gender == 'male' ? 'Mr' : 'Mrs');
echo $title;
/* Also instead of putting our result into a variable, we can just
as easily put it in-line with our code, if we want to */
echo  "Hello " .($gender == 'male' ? 'Mr' : 'Mrs'). ". Smith, how are you?";
/* in our case this will output: "Hello Mr. smith, how are you?" */
 
?>

So as you can see the ternary logic form, if you were to read it as english, would read something like “$title gets the value of ‘Mr’ if $gender is equal to male, and ‘Mrs’ if $gender is not male.”

“Ok, that’s fine, but what if I want to return a true or false value?” Well that’s even easier! Let’s try it:

<?php
/* explicitly tell PHP to return a true or false */
$result = (1+1==2 ? true : false);
 
/* or imply that you want a true or false like so: */
$result = (1+1==2);
echo ($result ? '$result is true' : '$result is false');
 
?>

The above second example $result will set $result to have the return value of the expression (1+1==2) which, as far as I know is true.

And there we go, a very basic example of ternary logic, practice makes you better, so practice lots. I hope you found this helpful.

By Mike on April 1, 2011 | PHP, Tutorials
Tags: , , , ,

MySQLi Tutorial: Debugging with MySQLi

There will be times when you run into problems with your MySQL statements or connections, there are ways to help you sort out what went wrong, I’ll cover that in this tutorial.

If you ever get an error like these:
Access denied for user ‘username’@’localhost’ (using password: YES)
Unknown database ‘phpmysqlitutorial’

They can be easily solved by double checking your connection details and verifying your database name using a tool such as phpMyAdmin or if your hosting provides it, the MySQL administration tools in CPanel.

I’ll start with showing you how to check for errors on your connection. You’ll need two functions:

mysqli_connect_errno() - Returns an error code
and
mysqli_connect_error() - Returns a string description of the last error
                         produced by your connection
<?php
/* make our connection */
$sql = new mysqli('localhost','username','password','database');
 
/* check for an error code */
if ( mysqli_connect_errno() ) {
    /* oh no! there was an error code, what's the problem?! */
    echo 'There was an error with your connection: '.mysqli_connect_error();
}
 
/* close up */
$sql->close();
?>

If for some reason your queries don’t seem to be inserting, updating, deleting or selecting, you can find out how by using MySQLi’s error properties. You will need:

->errno - Returns the error code of the last error.
and
->error - Returns a string description of that error.
<?php
/* make our connection */
$sql = new mysqli('localhost','username','password','database');
 
/* make a purposely erroneous query, notice there is a missing ' at the end */
$query = "SELECT * FROM `people` WHERE `name`='Mike;";
 
/* try and run this query */
if ( !$sql->query($query) ) {
    echo "Error code ({$sql->errno}): {$sql->error}";
} else {
    echo 'Query was sucessful, proceed.';
}
 
/* alternatively you could shorten that to: */
$result = $sql->query($query) or exit("Error code ({$sql->errno}): {$sql->error}");
 
/* close up */
$sql->close();
?>

And there you have it, two ways to check and make sure your MySQL details and queries run smoothly. So just remember, if you find yourself pulling your hair out because your queries aren’t working, or you connection is failing, print out some errors that can really help you figure out what you might have missed.

By Mike on March 31, 2011 | MySQLi, Tutorials
Tags: , ,