Creating a MySQL quoter
By Nilesh - May 7th, 2008
Tagged:
Well, many times we have to quote field names and table names in SELECT, INSERT, and other MySQL queries via PHP using backticks ` . This is a big trouble inserting backticks in each SQL query especially when you are using the traditional MySQL extension instead of MySQLi which has a prepare() method. Well, I have created a simple PHP function (rather a snippet :D) in which you just have to specify the field names to be quoted (it can also be table names). So, here's my snippet -
(read at the end what it does)
function quote($f = NULL,$quote="`") {
if($f == NULL):
return false;
endif;
$f = explode(',',$f);
foreach($f as $k => $v) {
$sql_fields .= $quote.$v.$quote.",";
}
$sql_fields = strrev($sql_fields);
$sql_fields_exp = explode(',',$sql_fields);
end(array_reverse($sql_fields_exp));
array_shift(&$sql_fields_exp);
$sql_fields = array_reverse($sql_fields_exp);
$while_init=0;
$while_count=count($sql_fields);
while($while_init != $while_count) {
$sql_fields[$while_init] = strrev(&$sql_fields[$while_init]);
$while_init++;
}
$sql_fields = implode(',',$sql_fields);
return $sql_fields;
}
Description of what it does -
- By default if no input is given to the function, it will set $f to NULL and $quote to a backtick.
- Next, it checks if $f is NULL or not.
- Now, the input $f is split into an array by removing the commas between the input string.
- Each field into the split array $f, is appended as a string to $sql_fields with a comma on the end which results in an unwanted comma at the end of the string.
- The string $sql_fields is reversed.
- And again the fields are exploded by removing a comma preserving the backtick on each field name.
- Now we reverse the array as obtained in the previous step and set the array's internal pointer to the end.
- Now, the last element is empty eariler was a comma is deleted from the array.
- We create a new array which contains the reversed array obtained in the previous step.
- As you know, explode() splits a string into numerical array (or an array with numeric indices).
- So, we have a while loop which brings back the order of fields (it matters a lot in inserts).
- Now, imploding the new string with a comma gets us the final result!
I have tested this code with single value and multiple value -- it works!
If you have any suggestions, questions, please comment else spread the link to everyone!
Trackback URL for this post:
http://www.itech7.com/trackback/43












Comments
You can know test the snippet at http://www.itech7.com/cgi-bin/mysql_quoter.php
-----
Nilesh Govindrajan
Site & Server Administrator
India Technologies
Nilesh Govindrajan
Site & Server Administrator
iTech7
Post new comment