Insert into MySQL datetime column from PHP

16
Jun/09
2

You can use this simple function to convert a unix timestamp (like the one obtained from time()) to MySQL datetime format:

function mysql_datetime($timestamp = null) {
    if(!isset($timestamp)) $timestamp = time();
    return date('Y-m-d H:i:s', $timestamp);
}

I’m using this instead of MySQL’s NOW() function because my MySQL server isn’t localized to my timezone, but my PHP is by usage of date_default_timezone_set.

Edit: And you can use this function to convert back the other way (you can do this directly in the SQL too, but just in case)

function datetime_to_unix($datetime) {
    list($date, $time) = explode(' ', $datetime);
    list($year, $month, $day) = explode('-', $date);
    list($hour, $minute, $second) = explode(':', $time);
    return mktime($hour, $minute, $second, $month, $day, $year);
}

Human-readable file size in JavaScript

10
Jun/09
0

“size” is in bytes, the rest you should be able to figure out.

function readableFileSize(size) {
    var units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    var i = 0;
    while(size >= 1024) {
        size /= 1024;
        ++i;
    }
    return size.toFixed(1) + ' ' + units[i];
}
Filed under: JavaScript

PHP code for handling recursive categories/hierarchical data

9
Jun/09
0

I’m just going to paste the code I wrote here… you can read some other tutorial to understand what it’s doing, but for some reason they have really incomplete examples, so here’s the whole shabang. It will even keep your nodes in alphabetical order. It has a function for displaying a drop down list too; wrap it in <select> tags.

<?php
class Category {
    function getParent($id) {
        return mysql_safe_query('SELECT parent.* FROM categories AS child, categories AS parent WHERE parent.id = child.parent_id AND child.id = %s LIMIT 1', $id);
    }

    function getChildren($id, $direct = false) {
        if($direct) {
            return mysql_safe_query('SELECT * FROM categories WHERE parent_id = %s ORDER BY left_val ASC', $id);
        } else {
            return mysql_safe_query('SELECT child.* FROM categories AS child, categories AS parent WHERE child.left_val >= parent.left_val AND child.right_val <= parent.right_val AND parent.id = %s ORDER BY child.left_val ASC', $id);
        }
    }

    function insert($name, $parent_id) {
        $result = mysql_safe_query('SELECT * FROM categories WHERE parent_id <=> %s AND name < %s ORDER BY name DESC LIMIT 1', $parent_id, $name);
        if(mysql_num_rows($result) > 0) {
            // insert between children
            $row = mysql_fetch_assoc($result);
            mysql_safe_query('UPDATE categories SET left_val = left_val + 2 WHERE left_val > %s', $row['right_val']);
            mysql_safe_query('UPDATE categories SET right_val = right_val + 2 WHERE right_val > %s', $row['right_val']);
            mysql_safe_query('INSERT INTO categories (parent_id, left_val, right_val, name) VALUES (%s, %s, %s, %s)',
                $parent_id, $row['right_val'] + 1, $row['right_val'] + 2, $name);
        } else {
            $result = mysql_safe_query('SELECT * FROM categories WHERE id <=> %s LIMIT 1', $parent_id);
            if(mysql_num_rows($result) > 0) {
                // insert first child
                $row = mysql_fetch_assoc($result);
                mysql_safe_query('UPDATE categories SET left_val = left_val + 2 WHERE left_val > %s', $row['left_val']);
                mysql_safe_query('UPDATE categories SET right_val = right_val + 2 WHERE right_val > %s', $row['left_val']);
                mysql_safe_query('INSERT INTO categories (parent_id, left_val, right_val, name) VALUES (%s, %s, %s, %s)',
                    $parent_id, $row['left_val'] + 1, $row['left_val'] + 2, $name);
            } else {
                // insert at beginning of tree
                mysql_safe_query('UPDATE categories SET left_val = left_val + 2, right_val = right_val + 2');
                mysql_safe_query('INSERT INTO categories (parent_id, left_val, right_val, name) VALUES (%s, %s, %s, %s)',
                    null, 1, 2, $name);
            }
        }
    }

    function delete($id) {
        $result = mysql_safe_query('SELECT * FROM categories WHERE id = %s LIMIT 1', $id);
        $row = mysql_fetch_assoc($result);
        mysql_safe_query('DELETE FROM categories WHERE id = %s LIMIT 1', $id);
        mysql_safe_query('UPDATE categories SET parent_id = %s WHERE categories.parent_id = %s', $row['parent_id'], $id); // relink parent
        mysql_safe_query('UPDATE categories SET left_val = left_val - 1, right_val = right_val - 1 WHERE left_val > %s AND right_val < %s', $row['left_val'], $row['right_val']); // update children
        mysql_safe_query('UPDATE categories SET left_val = left_val - 2 WHERE left_val > %s', $row['right_val']); // update left values of nodes to right
        mysql_safe_query('UPDATE categories SET right_val = right_val - 2 WHERE right_val > %s', $row['right_val']); // update right values of encompassing nodes and nodes to right
    }

    function incPostCount($id, $amount=1) {
        $result = mysql_safe_query('SELECT * FROM categories WHERE id = %s', $id);
        $row = mysql_fetch_assoc($result);
        return mysql_safe_query('UPDATE categories SET num_posts = num_posts + %s WHERE left_val <= %s AND right_val >= %s',
            $amount, $row['left_val'], $row['right_val']);
    }

    function decPostCount($id, $amount=1) {
        return self::incPostCount($id, -$amount);
    }

    function getPath($id) {
        $result = mysql_safe_query('SELECT * FROM categories WHERE id = %s', $id);
        $row = mysql_fetch_assoc($result);
        return mysql_safe_query('SELECT * FROM categories WHERE left_val <= %s AND right_val >= %s ORDER BY left_val ASC',
            $row['left_val'], $row['right_val']);
    }

    function printOptions($selected=null, $format=null, $mult=null, $add=null) {
        if(!isset($format)) $format = '<option value="%s" style="padding-left:%spx"%s>%s</option>';
        if(!isset($mult))   $mult = 15;
        if(!isset($add))    $add = 3;
        $depth = 0;
        $result = mysql_safe_query('SELECT * FROM categories ORDER BY categories.left_val ASC');
        while($row = mysql_fetch_assoc($result)) {
            if(isset($last)) {
                if($row['left_val'] == $last['left_val'] + 1) {
                    ++$depth;
                    $next_right = $last_right + 1;
                } elseif($row['left_val'] > $last['right_val'] + 1) {
                    $levels = $row['left_val'] - $last['right_val'] - 1;
                    $depth -= $levels;
                }
            }
            $last = $row;
            if($row['id'] == $selected) $selected_str = ' selected="selected"';
            else $selected_str = '';
            echo sprintf($format, $row['id'], $depth*$mult+$add, $selected_str, $row['name'], $row['num_posts'], $depth);
        }
    }

    function printTree($format=null) {
        if(!isset($format)) $format = '<li><a href="index.php?cat=%s">%s</a> (%s)';
        $depth = 0;
        $result = mysql_safe_query('SELECT * FROM categories ORDER BY categories.left_val ASC');
        echo '<ul>';
        while($row = mysql_fetch_assoc($result)) {
            if(isset($last)) {
                if($row['left_val'] == $last['left_val'] + 1) {
                    echo '<ul>';
                    ++$depth;
                    $next_right = $last_right + 1;
                } elseif($row['left_val'] > $last['right_val'] + 1) {
                    $levels = $row['left_val'] - $last['right_val'] - 1;
                    echo str_repeat('</li></ul></li>', $levels);
                    $depth -= $levels;
                } else {
                    echo '</li>';
                }
            }
            $last = $row;
            echo sprintf($format, $row['id'], $row['name'], $row['num_posts'], $depth);
        }
        echo str_repeat('</li></ul>', $depth+1);
    }

    function printAdminTree() {
        self::printTree('<li><a href="index.php?cat=%s">%s</a> (<a href="category_delete.php?id=%1$s">Delete</a>)');
    }
}

Please, please, please leave a comment if you’re actually reading this and not a bot scraping my content for your own blog… if that’s what you’re doing, this tutorial was found on ProgramAndDesign.com you jerk.

Filed under: PHP

Flash Player 10 on Ubuntu 64-bit

2
Jun/09
0

There’s a wad of tutorials out there on how to to install this plugin, but I’ve found they either don’t work, or over complicate things.

If you haven’t already found it, download the Flash Player 10 64-bit plugin for linux. Then,

tar xvzf libflashplayer-10.0.22.87.linux-x86_64.so
sudo cp libflashplayer.so /usr/lib/firefox-3.0.10/plugins

You might be running a different version of Firefox by the time you read this tutorial, so bust a “locate firefox | grep plugins” to find the appropriate folder.

Filed under: Ubuntu

Hash/unhash HTML

8
May/09
0

Here’s a little class I wrote that lets you hash HTML and other things so that you can do some processing on just the text, and then unhash the HTML again.

class ht
{
        static $hashes = array();

        # hashes everything that matches $pattern and saves matches for later unhashing
       function hash($text, $pattern) {
                return preg_replace_callback($pattern, array(self,'push'), $text);
        }

        # hashes all html tags and saves them
       function hash_html($html) {
                return self::hash($html, '`<[^>]+>`');
        }

        # hashes and saves $value, returns key
       function push($value) {
                if(is_array($value)) $value = $value[0];
                static $i = 0;
                $key = "\x05".++$i."\x06";
                self::$hashes[$key] = $value;
                return $key;
        }

        # unhashes all saved values found in $text
       function unhash($text) {
                return str_replace(array_keys(self::$hashes), self::$hashes, $text);
        }

        function get($key) {
                return self::$hashes[$key];
        }

        function clear() {
                self::$hashes = array();
        }
}
Filed under: PHP

PHP string ends with

8
May/09
0

There’s a hundred ways to do this, but here’s the one I came up with. It doesn’t use regex’s so it should be pretty quick.

function ends_with($str, $suffix) {
    return substr($str, -strlen($suffix)) == $suffix;
}

function starts_with($str, $prefix) {
    return substr($str, 0, strlen($prefix)) == $prefix;
}

For completeness, I added the corresponding starts_with function.

Filed under: PHP

Random String

8
May/09
0

Just some functions for generating random strings in PHP.

function randstr($len=8, $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {
    $i = 0;
    $str = '';
    $randmax = strlen($chars)-1;

    for($i=0; $i<$len; ++$i) {
        $str .= $chars[mt_rand(0,$randmax)];
    }

    return $str;
}

function randkey($len=32) {
    return randstr($len, '`1234567890-=qwertyuiop[]\\asdfghjkl;\'zxcvbnm,./ ~!@#$%^&*()_+{}|:"<>?');
}

randkey is good for generating salt strings and such, randstr is good for stuff like short URLs. Of course, you can pass in whatever characters you want.

Filed under: PHP

Encode Array as String

8
May/09
0

I wanted to store an array in a cookie, so I wrote these two functions:

function encode_arr($data) {
    return base64_encode(serialize($data));
}

function decode_arr($data) {
    return unserialize(base64_decode($data));
}
Filed under: PHP

jQuery Select Text Range

8
May/09
0

Here’s a jQuery function I wrote which you can use to select a range of text in an input field.

$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if(this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};
Tagged as:

Simple Rounded Corners with CSS

26
Apr/09
0

I know there are umpteen billion tutorials on rounded corners out there, but here’s an easy way that I like to do it. Requires only one image, and allows you to nudge your text as close to the corners are you like.

If you want a 3px radius corner, have a black background, and white foreground, you need to create a 6×6 (i.e. radius*2) image of a white circle on a black background. This method won’t support transparency unfortunately.

The HTML:

<div id="content">
    <div id="tl"></div><div id="tr"></div><div id="bl"></div><div id="br"></div>
    Your content here.
</div>

The CSS:

#content {
    position:relative;
    background-color: #fff;
    width:600px;
    height:300px;
}

#tl,#tr,#bl,#br{
    background: #000 url(images/circle.gif);
    width:3px;
    height:3px;
    position:absolute;
}

#tl{top:0;left:0}
#tr{top:0;right:0;background-position:3px 0}
#bl{bottom:0;left:0;background-position:0 3px}
#br{bottom:0;right:0;background-position:3px 3px}

Adjust all the “3px”s to match your radius, and modify the background attribute to meet your needs, and style content however you want. You probably want to put some padding on there. The important thing is that #content has position:relative so that the corners are aligned to the content box rather than the page.

I used this technique on my personal site, mnbayazit.com.