Reusig same code like this?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ianhull
Forum Contributor
Posts: 310
Joined: Tue Jun 14, 2005 10:04 am
Location: Hull England UK

Reusig same code like this?

Post by ianhull »

Hi Guys,

does any of you reuse your code or make it like global like this.

Code: Select all


<?php

$tableName = $_REQUEST['formName'];

include_once("connection.php");

foreach ( $_POST as $varName => $postData ) 
mysql_query("INSERT INTO $tableName ({$varName}) VALUES ({$postData})");

?>

I am wondering whether to start doing it this way, do you think it would be good practice?

Any help/advice very welcome.
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Post by Mordred »

When are you supposed to need this?

It is an extremely bad practice, accepting whatever the user gave you, including the table name, and then writing all this data to the database. This functionality is
1. a security [s]hall[/s] hole bigger than a barn
2. inefficient, instead of one query, it does many
3. not needed

Print this code and write with red all over it: "Do not do this!"

Edit: security hole, duh.
Last edited by Mordred on Mon Feb 19, 2007 4:23 am, edited 1 time in total.
ianhull
Forum Contributor
Posts: 310
Joined: Tue Jun 14, 2005 10:04 am
Location: Hull England UK

Post by ianhull »

Well... thanks for that,

Is there any other way of doing it without doing so many queries?

Thanks
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Take a look at the extended insert query syntax.
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Post by Mordred »

ianhull wrote:Is there any other way of doing it without doing so many queries?
If you're asking how to do it - RTFM as feyd said.
If you're asking if it is good to have general logic for inserting whatever you want in a database - the answer is yes and no. Certainly it is not good to leave the control over what is to be written to the client, this is a definite no-no. Otherwise, you could possibly write code that generates SQL statements instead of writing them by hand. In general though, writing the statements according to the circumstances you need them in works perfectly. It is wise to implement them in a layered API of sorts - all queries to be hidden behind API functions which your application would use, instead of inlining the queries in your code.
Post Reply