Jan 20

Multi-Dimensional Array Sort Function

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// mdasort(&$array, $sort_by_key, $direction = SORT_ASC)
// ----------------------------------------------------------------------------------
// returns true/false
//
// &$array = array to be sorted
// $sort_by_key = the key of the array element to sort by. This element is an element
// of the second-dimension array
// $direction = SORT_ASC or SORT_DESC
function mdasort(&$array, $sort_by_key, $direction = SORT_ASC)
{
try
{
$comparisons = array();
foreach($array as $comp)
{
$comparisons[] = $comp[$sort_by_key];
}
array_multisort($comparisons, $direction, $array);
return true;
}
catch (Exception $e)
{
echo $e;
return false;
}
}

Here is an example of its useage…

PHP
1
2
3
4
5
6
7
8
9
10
$arr = array(
array('lemon'),
array('apple'),
array('watermelon'),
array('grape')
);
mdasort($arr, 0, SORT_DESC);
print_r($arr);

Will look like…

Array
(
    [0] => Array
        (
            [0] => watermelon
        )

    [1] => Array
        (
            [0] => lemon
        )

    [2] => Array
        (
            [0] => grape
        )

    [3] => Array
        (
            [0] => apple
        )

)

Jan 16

Smarty date_diff Function

This is a function-type plugin for the Smarty template engine to calculate the difference between two dates in days (default), weeks, or years.

Download: Click here and extract the file to your Smarty "plugins/" folder.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<?php
/*
* Smarty plugin
* -------------------------------------------------------------
* Type: function
* Name: date_diff
* Version: 2.0
* Date: June 22, 2008
* Author: Matt DeKok
* Purpose: factor difference between two dates in days, weeks,
* or years
* Input: date1 = "mm/dd/yyyy" or "yyyy/mm/dd" or "yyyy-mm-dd"
* date2 = "mm/dd/yyyy" or "yyyy/mm/dd" or "yyyy-mm-dd" or $smarty.now
* assign = name of variable to assign difference to
* interval = "days" (default), "weeks", "years"
* Examples: {date_diff date1="5/12/2003" date2=$smarty.now interval="weeks"}
* {date_diff date1="5/12/2003" date2="5/10/2008" assign="diff"}{$diff}
* -------------------------------------------------------------
*/
function smarty_function_date_diff($params, &$smarty)
{
$date1 = mktime(0,0,0,1,1,2000);
$date2 = mktime(0,0,0,date("m"),date("d"),date("Y"));
$assign = null;
$interval = "days";
extract($params);
$i = 1/60/60/24;
if($interval == "weeks")
{
$i = $i/7;
}
elseif($interval == "years")
{
$i = $i/365.25;
}
$date1 = is_string($date1) ? strtotime($date1) : $date1;
$date2 = is_string($date2) ? strtotime($date2) : $date2;
if($assign != null)
{
$smarty->assign($assign,floor(($date2 - $date1)*$i));
}
else
{
return floor(($date2 - $date1)*$i);
}
}
?>

Jan 16

MySQL Database Class

This MySQL database class is probably one of the simplest database objects/classes to use for PHP. The number of lines of code that you need to use for any query is just 1-2! Any query at all can be called and return a result whether it be data or true/false. The query uses the secure PDO object to prepare input.

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class database
{
public $db; //PDO Object
const GET_RECORDSET = 0;
const GET_RECORD = 1;
const GET_VALUE = 2;
function __construct($host, $username, $password, $database_name)
{
$dsn = "mysql:host=$host;dbname=$database_name";
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
try
{
@$db = new PDO($dsn, $username, $password, $options);
}
catch (PDOException $e)
{
$error = $e->getMessage();
echo '<div class="error"><strong>PDO Error:</strong><br />' . $error . '</div>';
exit;
}
$this->db = $db;
}
function query($sql_statement, $bind_values = array(), $return_type = self::GET_RECORDSET)
{
$query = $this->db->prepare($sql_statement);
//bind dynamic values to the query string
foreach($bind_values as $key => $value)
{
$dt = PDO::PARAM_STR; //value is a string
if(is_int($value)) $dt = PDO::PARAM_INT; //value is an integer
elseif(is_bool($value)) $dt = PDO::PARAM_BOOL; //value is a boolean
$query->bindValue(":$key", $value, $dt);
}
//catch errors during execution and return an error message
try
{
$result = $query->execute();
}
catch (PDOException $e)
{
$error = $e->getMessage();
echo '<div class="error"><strong>SQL Error:</strong> <code>' . $sql_statement . '</code><br />' . $error . '</div>';
return false;
}
try
{
if($return_type == self::GET_RECORDSET) //returns a 2-dimensional array
{
$data = $query->fetchAll();
}
elseif($return_type == self::GET_RECORD) //returns a 1-dimensional array
{
$data = $query->fetch();
}
else //returns a value
{
$data = $query->fetchColumn();
}
}
catch (PDOException $e)
{
if(is_bool($result)) // If the result is a boolean, return true/false
{
$data = $result;
}
else
{
$error = $e->getMessage();
echo '<div class="error"><strong>PDO Error:</strong><br />' . $error . '</div>';
exit;
}
}
//Closes the cursor, enabling the statement to be executed again.
$query->closeCursor();
return $data;
}
}

Calling the object is done like the following:

PHP
1
2
3
4
5
define('DB_HOST','localhost');
define('DB_USER','username');
define('DB_PASS','password');
define('DB_NAME','database name');
$dbase = new database(DB_HOST, DB_USER, DB_PASS, DB_NAME);

Executing a query that does not return data results in a true or false value. When inserting user input into the SQL string use the following method to prepare the variables so as to prevent SQL injection.

PHP
1
2
3
4
5
6
$values = array(
'input1' => $_POST['input1'],
'name' => $_POST['name']
);
$result = $dbase->query("INSERT INTO table (input1, name) VALUES(:input1, :name);", $values);

There are a few ways to return data. The first is a record set, which is returned into a mult-dimensional array. The first dimension is the record, and the second dimension is the fields of that record. This is the default. The next type is an individual record. It is returned into a single-dimensional array. The last type is a single value (no array).

PHP
1
2
3
4
5
6
7
// a record
$values = array('user_id' => $_SESSION['user_id']);
$user = $dbase->query("SELECT * FROM users WHERE user_id = :user_id;", $values, database::GET_RECORD);
// a value
$values = array('user_id' => $_SESSION['user_id']);
$user_level = $dbase->query("SELECT user_level FROM users WHERE user_id = :user_id;", $values, database::GET_VALUE);