Mark’s PHP Snippets

These are just a few PHP snippets/functions I have written over the years and have found to be quite useful.

mysql_connect('localhost','USERNAME','PASSWORD');
mysql_select_db('DATABASE');

This one really isn’t anything special, but it makes its way into every single one of my pages, so it’s worth mentioning in case you forget the syntax or are new to PHP. It simply connects to a mysql database.

function mysql_safe_string($value) {
    if(empty($value))           return 'NULL';
    elseif(is_string($value))   return '\''.mysql_real_escape_string(trim($value)).'\'';
    elseif(is_numeric($value))  return $value;
    elseif(is_array($value))    return implode(',',array_map('mysql_safe_string',$value));
    else                        return false;
}

function mysql_safe_query($format) {
    $args = array_slice(func_get_args(),1);
    $args = array_map('mysql_safe_string',$args);
    $query = vsprintf($format,$args);
    return mysql_query($query);
}

These are my favorite two functions that I can’t live without. They make writing mysql queries so much easier.

// compare something like this
mysql_query(sprintf('INSERT INTO users (name, age) VALUES (%s, %d)', mysql_real_escape_string($_POST['name']), (is_numeric($_POST['age'])?$_POST['age']:'NULL')));
// to this
mysql_safe_query('INSERT INTO users (name, age) VALUES (%s, %s)', $_POST['name'], $_POST['age']);
// it even handles arrays nicely
$arr = array(1,2,3,4,5);
mysql_safe_query('SELECT * FROM posts WHERE cat_id IN (%s) ORDER BY date DESC', $arr);

These next two are quite simple, but still very handy.

function redirect($uri) {
    header('location:'.$uri);
    exit;
}

function pr($arr) {
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
}

pr() is great for debugging, and redirect() helps keep your code clean and meaningful.

This next function is still in its infancy, so it may be refined over time.

function smart_excerpt($text, $maxLen=500) {
    if(preg_match('`.*?<!--\s*more\s*-->`is', $text, $matches))
        return $matches[0];
    if(strlen($text) > $maxLen) {
        $minLen = round($maxLen/2);
        if(preg_match('`.{'.$minLen.','.$maxLen.'}[.!?]`s', $text, $matches))
            return rtrim($matches[0]);
        return rtrim(substr($text, 0, $maxLen),' \t\n\r\0\x0B.!?').'...';
    }
    return false;
}

It accepts a body of text, and searches for the text “<!–more–>”. If it finds it, it returns everything before that. Otherwise, if it doesn’t, and it’s longer than $maxLen, it trims the text down to the first punctuation character (.!?) before $maxLen. That way your text doesn’t get cropped mid-sentence/word. If it can’t find any punctuation (because you’re a terrible writer?), it will crop at exactly $maxLen. It returns false if the text doesn’t need cropping. This way you can decide if you want to print a “view more” link or not.

// example usage
if($excerpt = smart_excerpt($post['body']))
    echo nl2br($excerpt).' <a href="post_view.php?id='.$post['id'].'">More &raquo;</a>';
else
    echo nl2br($post['body']);

Well, that’s all for now. I’ll post up some more if I find any other tasty tidbits lying around.

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *