473,748 Members | 4,065 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Scrubbing MySQL Values and CSVtoArray()

I have a function that passes a csv string to mysql to use as values:

<?php
function fnINSERT ($csvValues) {
$sSQL = "INSERT INTO mytable (
field_a, field_b, field_b, field_c
) VALUES {
$csvValues);
return mysql_query($sS QL);
}

//note the SQL Injection attack in the 2nd parameter
$csvValues = "1, "'1' OR ''='"
$oResult = fnINSERT($csvVa lues);
?>

$csvValues is already scrubbed for some business logic, but (obviously)
it needs to have that mysql_real_esca pe function run on each of those
csv values, as well.

For architectural reasons, I can't do the scrubbing before the function
is called, but instead have to do it when it comes to me as this csv SLOB.

My First Question:
Can I run the real escape function on $csvValues as a whole, to
successfully scrub each parameter - or will I experience undesirable
results that way?

My Second Question:
I can convert an array to csv pretty easily, but going the other way
screws me up (because of quoted commas). So, my "architectu ral reasons"
(for this and some other stuff, too) would evaporate if someone could
help me write a function like this:

function CSVtoArray($sCS V) {
$aryRetVal = array();
$aryRetVal = foo($sCSV);
return $aryRetVal;
}
Aug 17 '07 #1
10 1968
Rik
On Fri, 17 Aug 2007 02:46:55 +0200, Sanders Kaufman <bu***@kaufman. net
wrote:
I have a function that passes a csv string to mysql to use as values:

<?php
function fnINSERT ($csvValues) {
$sSQL = "INSERT INTO mytable (
field_a, field_b, field_b, field_c
) VALUES {
$csvValues);
return mysql_query($sS QL);
}

//note the SQL Injection attack in the 2nd parameter
$csvValues = "1, "'1' OR ''='"
$oResult = fnINSERT($csvVa lues);
?>

$csvValues is already scrubbed for some business logic, but (obviously)
it needs to have that mysql_real_esca pe function run on each of those
csv values, as well.

For architectural reasons, I can't do the scrubbing before the function
is called, but instead have to do it when it comes to me as this csv
SLOB.
Which shouldn't be the case...
My First Question:
Can I run the real escape function on $csvValues as a whole, to
successfully scrub each parameter - or will I experience undesirable
results that way?
If there are strings in it: yes, you'll have undesired results.
My Second Question:
I can convert an array to csv pretty easily, but going the other way
screws me up (because of quoted commas). So, my "architectu ral reasons"
(for this and some other stuff, too) would evaporate if someone could
help me write a function like this:

function CSVtoArray($sCS V) {
$aryRetVal = array();
$aryRetVal = foo($sCSV);
return $aryRetVal;
}

Well, there's one in the making or something:
<http://nl3.php.net/manual/en/function.str-getcsv.php>, it's not in my PHP
though.

You could define a stream to a variable to get fgetcsv() to work for you,
might be some overkill.

In <http://www.php.net/manual/en/function.split. phpthere are some
efforts to get it right, which one you choose depends on the exact needs..
--
Rik Wasmus
Aug 17 '07 #2
Rik
On Fri, 17 Aug 2007 03:00:50 +0200, Rik <lu************ @hotmail.comwro te:
>My Second Question:
I can convert an array to csv pretty easily, but going the other way
screws me up (because of quoted commas). So, my "architectu ral
reasons" (for this and some other stuff, too) would evaporate if
someone could help me write a function like this:

function CSVtoArray($sCS V) {
$aryRetVal = array();
$aryRetVal = foo($sCSV);
return $aryRetVal;
}


Well, there's one in the making or something:
<http://nl3.php.net/manual/en/function.str-getcsv.php>, it's not in my
PHP though.

You could define a stream to a variable to get fgetcsv() to work for
you, might be some overkill.
Hmmmz, someone posted an interesting solution:

function parseCSV($str, $delimiter = ',', $enclosure = '"', $len =0)
{
$fh = fopen('php://memory', 'w+');
fwrite($fh, $str);
rewind($fh);
$result = fgetcsv( $fh, $len, $delimiter, $enclosure );
fclose($fh);
return $result;
}
var_dump(parseC SV('"foo","bar\ "",234,324,"boz "'));
--
Rik Wasmus
Aug 17 '07 #3
Rik wrote:
On Fri, 17 Aug 2007 02:46:55 +0200, Sanders Kaufman <bu***@kaufman. net>
>For architectural reasons, I can't do the scrubbing before the
function is called, but instead have to do it when it comes to me as
this csv SLOB.

Which shouldn't be the case...
Should, shmould. In this case, I absolutely must keep the business
logic separate from the database logic.

I have a database.php file that does *all* of the database work, and
then a base class that does the business logic. But if I have to put
the mysql-specific scrubbing function in the business logic base class -
it defeats the purpose of putting ALL of the database work in database.php.

The idea is that I can just replace the mysql-specific database.php file
with a Postgre or file system or whatever else database, to support
whatever db I happen to be using at the time.

>My First Question:
Can I run the real escape function on $csvValues as a whole, to
successfully scrub each parameter - or will I experience undesirable
results that way?

If there are strings in it: yes, you'll have undesired results.
I figured - but I had to ask.

>My Second Question:
I can convert an array to csv pretty easily, but going the other way
screws me up (because of quoted commas). So, my "architectu ral
reasons" (for this and some other stuff, too) would evaporate if
someone could help me write a function like this:

function CSVtoArray($sCS V) {
$aryRetVal = array();
$aryRetVal = foo($sCSV);
return $aryRetVal;
}


Well, there's one in the making or something:
<http://nl3.php.net/manual/en/function.str-getcsv.php>, it's not in my
PHP though.

You could define a stream to a variable to get fgetcsv() to work for
you, might be some overkill.
"Define a stream"? Wassat?

>
In <http://www.php.net/manual/en/function.split. phpthere are some
efforts to get it right, which one you choose depends on the exact needs.
Wow. This is a *much* bigger deal than I thought.

Fortunately, it looks like I found a fix - by just structuring my code
better.

I was trying to convert an array into a csv, pass it to another
function, and then break it back out into an array. Too many
unnecessary levels of abstraction pretty much guarantees failure, don't it?

My problem solves itself if I just keep it as an array until
*immediately* before composing my sql statement - and THEN scrub the
elements as I do so.

Still - a nice CSCtoArray() function would be cool.
Aug 17 '07 #4
Rik wrote:
Hmmmz, someone posted an interesting solution:

function parseCSV($str, $delimiter = ',', $enclosure = '"', $len = 0)
{
$fh = fopen('php://memory', 'w+');
fwrite($fh, $str);
rewind($fh);
$result = fgetcsv( $fh, $len, $delimiter, $enclosure );
fclose($fh);
return $result;
}
var_dump(parseC SV('"foo","bar\ "",234,324,"boz "'));
Weird. I've never seen "php://memory" before. The rest is pretty wild,
too. It looks like I've got some book-learning to do.
Aug 17 '07 #5
Rik wrote:
Hmmmz, someone posted an interesting solution:

function parseCSV($str, $delimiter = ',', $enclosure = '"', $len = 0)
{
$fh = fopen('php://memory', 'w+');
fwrite($fh, $str);
rewind($fh);
$result = fgetcsv( $fh, $len, $delimiter, $enclosure );
fclose($fh);
return $result;
}
var_dump(parseC SV('"foo","bar\ "",234,324,"boz "'));
Oh, I get it! PHP can parse a CSV *file*, but not a CSV *string*. So,
to parse the string, he just created a file in memory, and parsed that.

That's cool. I'll bet there are other cool ways to make use of that
technique.
Aug 17 '07 #6
Rik
On Fri, 17 Aug 2007 03:56:22 +0200, Sanders Kaufman <bu***@kaufman. net
wrote:
Rik wrote:
>On Fri, 17 Aug 2007 02:46:55 +0200, Sanders Kaufman <bu***@kaufman. net>
>>For architectural reasons, I can't do the scrubbing before the
function is called, but instead have to do it when it comes to me as
this csv SLOB.
Which shouldn't be the case...

Should, shmould. In this case, I absolutely must keep the business
logic separate from the database logic.
Well, that's OK. Why the hell it's a CSV string instead of the raw data is
another question :P
I have a database.php file that does *all* of the database work, and
then a base class that does the business logic. But if I have to put
the mysql-specific scrubbing function in the business logic base class-
it defeats the purpose of putting ALL of the database work in
database.php.

The idea is that I can just replace the mysql-specific database.php file
with a Postgre or file system or whatever else database, to support
whatever db I happen to be using at the time.
And that's the point where it might be turned into a CVS string if needed,
not in your business logic.
>>My Second Question:
I can convert an array to csv pretty easily, but going the other way
screws me up (because of quoted commas). So, my "architectu ral
reasons" (for this and some other stuff, too) would evaporate if
someone could help me write a function like this:

function CSVtoArray($sCS V) {
$aryRetVal = array();
$aryRetVal = foo($sCSV);
return $aryRetVal;
}
Well, there's one in the making or something:
<http://nl3.php.net/manual/en/function.str-getcsv.php>, it's not in my
PHP though.
You could define a stream to a variable to get fgetcsv() to work for
you, might be some overkill.

"Define a stream"? Wassat?
Streams: <http://nl3.php.net/manual/en/wrappers.php>
Stream-functions: <http://nl3.php.net/manual/en/ref.stream.php>
Making your own:
<http://nl3.php.net/manual/en/function.stream-wrapper-register.php>

Just forgot about the ability to abuse php://memory instead of going
through the pain of writing a whole wrapper for a single scalar variable..
> In <http://www.php.net/manual/en/function.split. phpthere are some
efforts to get it right, which one you choose depends on the exact
needs.

Wow. This is a *much* bigger deal than I thought.
I'm equally amazed PHP still hasn't got simple built-in functionality for
this. It's not like CVS is rare...
Fortunately, it looks like I found a fix - by just structuring my code
better.

I was trying to convert an array into a csv, pass it to another
function, and then break it back out into an array. Too many
unnecessary levels of abstraction pretty much guarantees failure, don't
it?

My problem solves itself if I just keep it as an array until
*immediately* before composing my sql statement - and THEN scrub the
elements as I do so.
Yup, that's what I was trying to say with the first 'Which shouldn't be
the case' :)
Still - a nice CSVtoArray() function would be cool.
Indeed.
--
Rik Wasmus
Aug 17 '07 #7
Rik
On Fri, 17 Aug 2007 04:06:46 +0200, Sanders Kaufman <bu***@kaufman. net
wrote:
Rik wrote:
>Hmmmz, someone posted an interesting solution:
function parseCSV($str, $delimiter = ',', $enclosure = '"', $len= 0)
{
$fh = fopen('php://memory', 'w+');
fwrite($fh, $str);
rewind($fh);
$result = fgetcsv( $fh, $len, $delimiter, $enclosure );
fclose($fh);
return $result;
}
var_dump(parse CSV('"foo","bar \"",234,324,"bo z"'));

Oh, I get it! PHP can parse a CSV *file*, but not a CSV *string*. So,
to parse the string, he just created a file in memory, and parsed that..

That's cool. I'll bet there are other cool ways to make use of that
technique.

Yup, one of the main advantages is 'directing' output. Say for instance I
have a logger class. I can set the output where to log in a single string,
making it quite versatile. Log to the screen, a systemfile, a file on a
ftpserver, to some socket; hell, even a database if I define a wrapper for
it, all possible with giving it a single target, and the same code logs to
it without any problems.
--
Rik Wasmus
Aug 17 '07 #8
Sanders Kaufman wrote:
I have a database.php file that does *all* of the database work, and
then a base class that does the business logic. But if I have to put
the mysql-specific scrubbing function in the business logic base class -
it defeats the purpose of putting ALL of the database work in database.php.
The solution is not to put the MySQL-scrubbing into the business logic
class, but to have the business logic class return an array (or,
even better: object) instead of a CSV string. Then the database class can
easily perform database-specific scrubbing mechanisms on the data before
inserting it into the database.

--
Toby A Inkster BSc (Hons) ARCS
[Geek of HTML/SQL/Perl/PHP/Python/Apache/Linux]
[OS: Linux 2.6.12-12mdksmp, up 57 days, 14:16.]

Elvis
http://tobyinkster.co.uk/blog/2007/08/16/elvis/
Aug 17 '07 #9
..oO(Rik)
>On Fri, 17 Aug 2007 03:00:50 +0200, Rik <lu************ @hotmail.comwro te:
>>
Well, there's one in the making or something:
<http://nl3.php.net/manual/en/function.str-getcsv.php>, it's not in my
PHP though.
It's already in CVS (since 8 months or so), but obviously not in the
current branches. One could use function_exists () to check for it and
implement a custom str-getcsv() function if necessary, using one of the
ways described below.
>You could define a stream to a variable to get fgetcsv() to work for
you, might be some overkill.
The manual for stream_wrapper_ register() contains a little example class
"VariableStream " to access global variables. This could be useful here
(should even work with PHP 4).
>Hmmmz, someone posted an interesting solution:

function parseCSV($str, $delimiter = ',', $enclosure = '"', $len = 0)
{
$fh = fopen('php://memory', 'w+');
fwrite($fh, $str);
rewind($fh);
$result = fgetcsv( $fh, $len, $delimiter, $enclosure );
fclose($fh);
return $result;
}
var_dump(parse CSV('"foo","bar \"",234,324,"bo z"'));
Clever. Ugly, but clever. ;)

Micha
Aug 17 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3946
by: Simon | last post by:
Hi, I am having a little problem with my PHP - MySQl code, I have two tables (shown below) and I am trying populate a template page with data from both. <disclaimer>Now I would like to say my skills, especially with MySQL are rudimentary</disclaimer> However my code (link below) fails, the nested database call does not return any data and this has me stumped. Any help will be much appreciated. Many thanks in advance
1
3052
by: Marcus | last post by:
Hello, quick question about MySQL storing NULL values... Say I have a textbox called $_POST and a variable $var. if(empty($_POST)) $var = NULL; else $var = $_POST; Disregarding filtering/formatting the data, upon inserting $var into
0
2139
by: Neculai Macarie | last post by:
Hi! Using Union and Order By gives strange behaviour in the following test-case: drop table if exists gallery; drop table if exists gallery_categ; # create test tables create table gallery (d_image_small char(100), d_image_big char(100)); create table gallery_categ (d_image char(100)); # insert test data
0
3946
by: Mike Chirico | last post by:
Interesting Things to Know about MySQL Mike Chirico (mchirico@users.sourceforge.net) Copyright (GPU Free Documentation License) 2004 Last Updated: Mon Jun 7 10:37:28 EDT 2004 The latest version of this document can be found at: http://prdownloads.sourceforge.net/souptonuts/README_mysql.txt?download
1
3025
by: Saqib Ali | last post by:
I have created 2 tables in my MySQL database. A_TAB and B_TAB. They have auto-incrementing integer primary keys respectively named A_ID & B_ID. When I created B_TAB, I declared a field named A_ID which references A_TAB.AID. I insert valid data into both tables. However, the foreign key constraint is NOT being enforced. The database allows be to enter any integer into B_TAB.AID regardless of weather that value exists anywhere in the...
1
2557
by: Steve | last post by:
I have a million record mainframe flat file that I BULK INSERT into a SQL table with CHAR(fieldlength) deined for every column to prevent import errors. Once imported I "INSERT INTO ... SELECT dbo.MyScrubFunction(columnN),..." My scrub functions will take for example a char(8) YYYYMMDD date field and return either a valid datetime variable or a NULL for 8-spaces or 8-zeros....or return a MONEY datatype by dividing by 100.
34
5067
by: Karam Chand | last post by:
Hello I have been working with Access and MySQL for pretty long time. Very simple and able to perform their jobs. I dont need to start a flame anymore :) I have to work with PGSQL for my companies current project. I have been able to setup postgresql in my rh box and
4
3332
by: Dan Lewis | last post by:
I've imported a ms access database into a table in a mysql database. The access database contains a field that holds date/time values in 'general date' format. These all show up at 01/01/1970 in the mysql database. I believe the field in mysql is wanting UTC and shows numbers when looked at from the sql command line (i.e. March 13, 2006, 5:31 pm is shown as 1142289086). How do I get the access data into that format so it will import...
6
38516
Atli
by: Atli | last post by:
This is an easy to digest 12 step guide on basics of using MySQL. It's a great refresher for those who need it and it work's great for first time MySQL users. Anyone should be able to get through this without much trouble. Programming knowledge is not required. Index What is SQL? Why MySQL? Installing MySQL. Using the MySQL command line interface
0
8987
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8826
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9534
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9316
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3303
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2211
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.