473,770 Members | 6,133 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Smarter way to extract data from FORM and save to DB?

Hello

Out of curiosity, is there a smarter, easier way to read data sent by
a form, and save them into a database? I have about 20 fields, and
it'd be easier if I could just use a loop to go through an array and
generate the SQL query in a couple of lines:

======
//If 'id' set -update; Otherwise -insert
if($_POST['id'])
$sql = sprintf("UPDATE $table SET name='%s', tel='%s' WHERE
id=%s",$_POST['name'],$_POST['tel'],$_POST['id']);
else
$sql = sprintf("INSERT INTO $table (id,name,tel) VALUES
(NULL,'%s','%s' )",$_POST['name'],$_POST['tel']);
======

Thank you.
Feb 8 '08 #1
10 2559
Sure. You can do a lot with foreach, str_replace, array_map, etc.

Gilles Ganault wrote:
Hello

Out of curiosity, is there a smarter, easier way to read data sent by
a form, and save them into a database? I have about 20 fields, and
it'd be easier if I could just use a loop to go through an array and
generate the SQL query in a couple of lines:

======
//If 'id' set -update; Otherwise -insert
if($_POST['id'])
$sql = sprintf("UPDATE $table SET name='%s', tel='%s' WHERE
id=%s",$_POST['name'],$_POST['tel'],$_POST['id']);
else
$sql = sprintf("INSERT INTO $table (id,name,tel) VALUES
(NULL,'%s','%s' )",$_POST['name'],$_POST['tel']);
======

Thank you.
Good luck,
--
Willem Bogaerts

Application smith
Kratz B.V.
http://www.kratz.nl/
Feb 8 '08 #2
rf

"Gilles Ganault" <no****@nospam. comwrote in message
news:q5******** *************** *********@4ax.c om...
Hello

Out of curiosity, is there a smarter, easier way to read data sent by
a form, and save them into a database? I have about 20 fields, and
it'd be easier if I could just use a loop to go through an array and
generate the SQL query in a couple of lines:

======
//If 'id' set -update; Otherwise -insert
if($_POST['id'])
$sql = sprintf("UPDATE $table SET name='%s', tel='%s' WHERE
id=%s",$_POST['name'],$_POST['tel'],$_POST['id']);
else
$sql = sprintf("INSERT INTO $table (id,name,tel) VALUES
(NULL,'%s','%s' )",$_POST['name'],$_POST['tel']);
======
Never heard of sql injection then?

With the above I could drop your entire database :-)

--
Richard.
Feb 8 '08 #3
On Feb 8, 3:57 am, Gilles Ganault <nos...@nospam. comwrote:
Hello

Out of curiosity, is there a smarter, easier way to read data sent by
a form, and save them into a database? I have about 20 fields, and
it'd be easier if I could just use a loop to go through an array and
generate the SQL query in a couple of lines:

======
//If 'id' set -update; Otherwise -insert
if($_POST['id'])
$sql = sprintf("UPDATE $table SET name='%s', tel='%s' WHERE
id=%s",$_POST['name'],$_POST['tel'],$_POST['id']);
else
$sql = sprintf("INSERT INTO $table (id,name,tel) VALUES
(NULL,'%s','%s' )",$_POST['name'],$_POST['tel']);
======

Thank you.
Check out Zend Framework 1.5 (currently a 'preview release', but
coming out soon). Specifically, check out Zend_Form and Zend_Db.
There are other similar solutions out there to make the task of
mundane form creation and CRUD operations easier, but in my opinion,
Zend Framework will give you a better payoff from your investment in
learning it since it is a glue-type framework and doesn't require you
to initialize a large framework just to you parts and pieces.

Enjoy,
Steve
Feb 8 '08 #4
On Fri, 08 Feb 2008 10:04:48 +0100, Willem Bogaerts
<w.********@kra tz.maardanzonde rditstuk.nlwrot e:
>Sure. You can do a lot with foreach, str_replace, array_map, etc.
If someone has some working code handy, I'm interested. I'm not clear
on how to go from an array filled in a form, and then extracting each
key/value into an SQL query.

Thanks.
Feb 8 '08 #5
"rf" <rf@invalid.com wrote in message
news:hl******** ***********@new s-server.bigpond. net.au...
>
Never heard of sql injection then?
Not before you mentioned it. Thanks - that looks like some nasty stuff. I
quess I have some more work to do
>
With the above I could drop your entire database :-)
Ouch!!!
>
--
Richard.


Feb 8 '08 #6
"Gilles Ganault" <no****@nospam. comwrote in message
news:q5******** *************** *********@4ax.c om...
Hello

Out of curiosity, is there a smarter, easier way to read data sent by
a form, and save them into a database? I have about 20 fields, and
it'd be easier if I could just use a loop to go through an array and
generate the SQL query in a couple of lines:
here's one way...certainly not the only way. however, this demonstrates what
you ask...sorry for the text-wrapping:

<?
$date = strtotime('now' );
$date = date('m', $date) . '/01/' . date('Y', $date);
$date = $_REQUEST['date'] ? $_REQUEST['date'] : $date;
$date = strtotime($date );
$dealer = 'someFacility';

// define updateable fields and default their values
$financials = array(
'Center' =$dealer
,
'Name' =$dealerName
,
'Month' =date('m', $date)
,
'Year' =date('Y', $date)
,
'pbsMaterialInv entory' =0 ,
'bcsAdvertising ' =0
);

// used to create dynamic db update statements
function createUpdateSta tement(&$value, $key)
{
$value = $key . " = '" . $value . "'";
return $value;
}

// used to format field values
function formatValue(&$v alue, $key = '', $request = array())
{
if (!is_array($req uest)){ $request = array($request) ; }
if (in_array($key, array('Center', 'Name', 'Month', 'Year'))){ return; }
if ($request){ $value = $request[$key]; }
$value = number_format(g etInteger($valu e));
return $value;
}

// whatever $value is, format it as an integer regarless of locale...
// inval may truncate commas...we're just forcing correct truncation
function getInteger(&$va lue, $key = '', $request = array())
{
if (!is_array($req uest)){ $request = array($request) ; }
if (in_array($key, array('Center', 'Name', 'Month', 'Year'))){ return; }
if ($request){ $value = $request[$key]; }
$locale = localeconv();
$decimal = $locale['decimal_point'] . $locale['mon_decimal_po int'];
$negative = $locale['negative_sign'];
$value = intval(preg_rep lace('/[^0-9' . $decimal . $negative . ']/',
'', $value));
return $value;
}

// update $financials with values provided by user submit
array_walk($fin ancials, 'getInteger', $_REQUEST);

// sledge-hammer db update
$sql = "
DELETE
FROM financials
WHERE Center = '" . $dealer . "'
AND STR_TO_DATE(CON CAT(Year, '-', Month, '-01'), '%Y-%m-%d')
=
STR_TO_DATE('" . date('Y-m-d', $date) . "', '%Y-%m-%d')
";
db::execute($sq l);
$sql = "
INSERT INTO
financials
(
" . implode(",\r\n ", array_keys($fin ancials)) . "
)
VALUES
(
'" . implode("',\r\n '", $financials) . "'
)
";
db::execute($sq l);

// more gentle update where we have determined a record exists alread
array_walk($fin ancials, 'createUpdateSt atement');
$sql = "
UPDATE financials
SET
" . implode(",\r\n ", $supplement) . "
WHERE Center = '" . $dealer . "'
";
db::execute($sq l);

// now, verify in debug that data made it into the db
// having used either sledge-hammer or gentle upate
$sql = "
SELECT " . implode(",\r\n ",
array_keys($fin ancials)) . "
FROM financials
WHERE Center = '" . $dealer .
"'
AND STR_TO_DATE(CON CAT(Year, '-', Month, '-01'),
'%Y-%m-%d') =
STR_TO_DATE('" . date('Y-m-d', $date) . "',
'%Y-%m-%d')
";
$records = db::execute($sq l);
$financials = $records[0];
array_walk($fin ancials, 'formatValue');
echo '<pre style="font:10p x;">' . print_r($financ ials, true) . '</pre>';
?>
Feb 8 '08 #7
..oO(Steve)
>"rf" <rf@invalid.com wrote in message
>Given the original post, correct.

But please tell me where the OP is going to use this variable? Is the OP
going to feed this to mysql (or whatever) or just let it sitting around
waiting for garbage collection? I suspect the former.

This *is* a snippit of code. We do not know what comes next.

but i believe your claim was "with the above, i could drop your entire
database". that was made regarding the original post. the claim is
incorrect.
Hairsplitting.
>as for what comes next, who knows.
It's correct that the posted code alone can't be used for injection, but
it's quite obvious that the next step will _most likely_ be a query call
to the DB. There's not much else that would make sense. And since there
is no use of prepared statements either, the posted code is vulnerable
and can _most likely_ be abused for SQL injection and should be fixed.

Micha
Feb 8 '08 #8
On Fri, 08 Feb 2008 09:33:01 GMT, "rf" <rf@invalid.com wrote:
>Never heard of sql injection then?
With the above I could drop your entire database :-)
I did hear, but wasn't paying attention because I first have to get
this CRUD thingie running ;-) Besides, although the web server will be
accessible from the Net, 1) it won't be published, meaning that if you
don't know the URL, there's no way to know it's there, and 2) I'll add
an .htaccess to prompt users for a login before they have access to
it.

But I'll read up on SQL injections because it looks nasty enough.
Thanks for pointing it out.
Feb 9 '08 #9
On Fri, 08 Feb 2008 09:57:04 +0100, Gilles Ganault <no****@nospam. com
wrote:
Hello

Out of curiosity, is there a smarter, easier way to read data sent by
a form, and save them into a database? I have about 20 fields, and
it'd be easier if I could just use a loop to go through an array and
generate the SQL query in a couple of lines:

======
//If 'id' set -update; Otherwise -insert
if($_POST['id'])
$sql = sprintf("UPDATE $table SET name='%s', tel='%s' WHERE
id=%s",$_POST['name'],$_POST['tel'],$_POST['id']);
else
$sql = sprintf("INSERT INTO $table (id,name,tel) VALUES
(NULL,'%s','%s' )",$_POST['name'],$_POST['tel']);
======
A safer way would be prepared statements. This code is, seeing to the use
of sprintf(), very easily altered to use those.

--
Rik Wasmus
Feb 9 '08 #10

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

Similar topics

0
1279
by: Shakil Khan | last post by:
Hi there ... My question is about Meta Data which is automatically saved with files. For example,when an MS Office Documents is saved, it automaticaly save some extra information with the file such as Author, Title, Description. Whenever we see the list of files in normal windows explorer, it will show you the meta data as well without even opening that file. Similarly when you Right-Click on a zip file to check its file properties , It...
0
1568
by: Shakil Khan | last post by:
Hi there ... My question is about Meta Data which is automatically saved with some files. For example,when an MS Office Documents is saved, it automaticaly save some extra information with the file such as Author, Title, Description. Whenever we see the list of files in normal windows explorer, it will show you the meta data as well without even opening that file. Similarly when you Right-Click on a zip file to check its file properties...
27
2742
by: Mark A. Gibbs | last post by:
i have been toying with the idea of making my enums smarter - ie, more in line with the rest of the language. i haven't tested it yet, but what i came up with is a template like this: template <typename Enum> class smart_enum { public: typedef Enum enum_type;
32
3228
by: Neil Ginsberg | last post by:
We're using SQL Server 7 with an Access 2000 MDB as a front end with ODBC linked tables. I recently created a new set of tables for the app, and users are complaining that unsaved data is being lost when they move to a new record. This seems to be the case when there are multiple users. When there is a single user using it, we don't seem to have that problem. It seems that we had this problem when we first converted from an MDB back end...
2
24226
by: deko | last post by:
I have a table that contains a bunch of pictures. When the user selects a particular image in a form, I need a way to extract the selected bitmap image (stored in an OLE Object table field) to the file system so the user can do stuff with "somePicture.bmp", for example. Is there an easy way to do this? Thanks in advance.
1
5336
by: Chris | last post by:
If this is not the right place to post, please someone direct me to the correct place. I'm having problems extracting the binary data that's included in an xml response back from a server. It's an embedded PDF file that's been base64 encoded. I've got it narrowed down to to a single node using Msxml2.DOMDocument.4.0 and selectSingleNode but how do I get the data from there to a PDF file and get the browser to display it. Can someone...
3
2658
by: adimangla | last post by:
Hi :-) I am creating a software that will save the present state of all the applications running on the desktop (WinXP). Can anyone point out the method to extract the filenames from the handles (or otherwise) of the files that are being accessed by processes and programs ? For example : If I have opened xyz.docx in MS Word 2007 then I want to find out the name of the file ("xyz.docx") and its complete path
3
5727
by: maylee21 | last post by:
hi, anyone can help me figure out how to read data from a text file like this: 10980012907200228082002 and extract the data according to this kind of format: Record type 1 TY-RECORD PIC (1). ID-PARTICIPANT PIC (6).
5
5764
by: Steve | last post by:
Hi all Does anybody please know a way to extract an Image from a pdf file and save it as a TIFF? I have used a scanner to scan documents which are then placed on a server, but I need to extract the image of the document (just the first page if there are multiple pages) and save it as a TIFF so I can then use the Tesseract OCR to get the text in the image.
0
9425
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
10231
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
10005
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,...
0
9871
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8887
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7416
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
5313
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5452
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.