Function to create Dynamic MySQL Queries
Posted: Sat Feb 25, 2006 6:40 pm
I wrote this function to be used as the sole method for a large web site to create select queries from a database. It makes writing queries a lot faster because I can call it with something like:
I figure it will make pagination very easy and will speed up development since the queries will be easier to write. I also figure it will be very secure since everything is escaped by mysql_real_escape_string.
One question I have though, is that when I pass the Parameters through, would there be a way for me to add a third value to the array so that I can specify the operand? As is this only supports the = operand. Also, any tips on how to make it better would be appreciated.
Thank you.
Code: Select all
$Records = GetMySQLData("name phone address balance", "tablename", $Parameters, "20, 20");One question I have though, is that when I pass the Parameters through, would there be a way for me to add a third value to the array so that I can specify the operand? As is this only supports the = operand. Also, any tips on how to make it better would be appreciated.
Thank you.
Code: Select all
function GetMySQLData($Fields, $Table, $Parameters = null, $Limit = "0, 1") {
Global $Connect; // link id
$Query = "select ";
$Fields = explode(" ", $Fields);
$FieldCount = count($Fields) - 1;
for ($CreateField = 0; $CreateField <= $FieldCount; $CreateField++) {
$Fields[$CreateField] = mysql_real_escape_string($Fields[$CreateField]);
$Query .= "`" . $Fields[$CreateField] . "`, ";
}
$Query = substr($Query, 0, -2) . " from `" . $Table . "` ";
if (isset($Parameters)) {
$Query .= "where ";
while (list($Field, $Value) = each($Parameters)) {
$Query .= "`" . mysql_real_escape_string($Field) . "`='" . mysql_real_escape_string($Value) . "' and ";
}
$Query = substr($Query, 0, -4);
}
$Query .= "limit " . $Limit;
if (!$Resource = @mysql_query($Query,$Connect)) {
// call error handler
} else {
$Record = 0;
while ($Data = mysql_fetch_assoc($Resource)) {
$Records[$Record] = $Data;
$Record++;
}
}
return $Records;
}