Yes, I'm new to PHP coding.
I am trying to write php code to collect data from an HTML form
and then insert it into a mySQL db. However, whenever the user
inputs a single quote (as in: foobar's), the SQL statement is rejected.
I think that's because the variables that are sent over to mySQL do
so in single quotes and the single quote looks like the end of that
particular field assignment. mySQL then has a hiccup when it runs into that.
But, if users put backslashes in front of
the single quotes (in the HTML form), it works great and record in inserted/updated fine.
However, if I can find a way for PHP to automatically input a backslash into the array generated by the user's actions where ever there is a single quote,
then the user won't have to worry about it.
My broken code is below.
Questions:
1) What am I doing wrong (other than trying to be a programmer ;-)?
2) What would you do?
3) Do you know of any other characters I should either: backslash due to possible errors like this
or strip out for security reasons? How would you recommend
I do this. I imagine I should probably backslash the backslash
character, just to be safe, but are there others too?
I have tried creating a function (see below) that accepts an array
as a parameter and then passes the "fixed" array back. But
it doesn't seem to be working.
Help!!!! I owe you one if you can offer any insight.
My unworking code:
function backslash_add ($array) {
for ($array_key = 0; $array[$array_key]; $array_key++) {
$cleaned_field = ereg("\\","\\\\",$array[$array_key]);
$cleaned_field = ereg("\'","\\'",$array[$array_key]);
// The echo below is just for debugging purposes
echo $array[$array_key];
}
return($array);
}
// Then the function is called when an insert into the mySQL db
// is needed. The $arr_request array holds the key/value pairs
// from the HTTP post or get (whichever is used). This processing
// has already occurred by this point.
if ($arr_request['action'] == 'insert') {
// Add backslashes via the backslash_add
// function
$arr_request = backslash_add ($arr_request);
// after this the $arr_request array is sent to mySQL
// and so on......
}