yasuhiro dot public at gmail dot com (2011-02-28 15:36:57)
This is an example to create SQL query commands automatically by setting options.
<?php
// Set required parameters here.
// The order of setting determines the order of constructing options.
$options = array(
"SELECT" => array('item1', "item2"),
"FROM" => 'table',
"WHERE" => array("visible = 1", 'param > 3'),
"LIMIT" => array(2, 5)
);
// Each command can have different separator strings.
// default: " " (white space)
// for example : [ WHERE visible = 1 param > 3 ] to [ WHERE visible = 1 AND param > 3 ]
$separators = array(
"AND" => "WHERE",
"," => array("SELECT", 'LIMIT')
);
echo "<pre>";
echo queryGenerate($options, $separators);
echo "</pre>";
// output:
// SELECT item1 , item2 FROM table WHERE visible = 1 AND param > 3 LIMIT 2 , 5
function queryGenerate($options = array(), $separators = array())
{
$sql = "";
if(is_array($options) && is_array($separators))
{
foreach ($options as $command => $param)
{
if(is_array($param))
{
$separateCode = null;
foreach ($separators as $separator => $words)
{
if(is_array($words))
{
for ($i = 0, $count = count($words); $i < $count; $i++)
{
if(stripos($words[$i], $command) !== false)
{
$separateCode = $separator;
}
}
}
else
{
if(stripos($words, $command) !== false)
{
$separateCode = $separator;
}
}
}
$sql .= "{$command} ";
for ($i = 0, $count = count($param); $i < $count; $i++)
{
if($i > 0)
{
$sql .= ($separateCode === null) ? " " : " {$separateCode} ";
}
$sql .= "{$param[$i]}";
}
$sql .= " ";
}
else
{
$sql .= "{$command} {$param} ";
}
}
}
return $sql;
}
?>