Updated example with a little snippet using in memory database :)
P.S: the XSS protection in this example is not needed at all because I check the input as boolean value. To see results in reverse order you specify order?desc
<?php
/* XSS-protection. */
$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$array = array(
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
);
function createTable($db) {
$db->exec("CREATE TABLE IF NOT EXISTS tags (id INTEGER PRIMARY KEY, tag TEXT NOT NULL UNIQUE)");
}
function insertData($db, $array) {
$db->beginTransaction();
foreach($array as $elm) {
try {
$stmt = $db->prepare("INSERT INTO tags (tag) VALUES (:tag)");
$stmt->execute(array(
":tag" => $elm
));
} catch(PDOException $e) {
/*** roll back the transaction if we fail ***/
$db->rollback();
/*** echo the sql statement and error message ***/
echo $sql . '<br />' . $e->getMessage();
}
}
$db->commit();
}
$db = new PDO('sqlite::memory:');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
//
createTable($db);
insertData($db, $array);
$order = "ASC";
if (strtoupper($_GET['order']) == "DESC") {
$order = "DESC";
}
$stmt = $db->prepare("SELECT * FROM tags ORDER BY tag $order");
$stmt->execute();
$data = array();
while($row = $stmt->fetch()) {
$data[] = array($row['tag']);
}
echo json_encode($data);
Hope you understand what im trying to
achieve(if not just ask). Any help on
this with ideas, approaches or
examples would be great.
First I have a couple of questions you are saying that you are using PHP5. How do you retrieve your data(RDBMS)? If not, PHP5 has SQLite enabled by default. I think you should be using at least a RDBMS(SQLite/etc) to do the heavy lifting for you.
When you learn SQL you don't have to any sorting in PHP. I think this PDO tutorial while give you insides how to use SQL while doing it safely. SQL is vulnerable to SQL-injections but thanks to PDO's prepared statements you don't have to worry about that anymore.
I have a set of results which are
pulled from a multi dimensional array.
Currently the array key is the price
of a product whilst the item contains
another array which contains all the
product details.
Use ORDER BY to order. I would use a datatable to do the sorting client-side. Also safes you to do work on the server(PHP). You could for example look at YUI2's datatable.