1

I've got a shop where users can purchase virtual items, such as one time power-up's and permanent changes to the users account. These purchases potentially alter different fields in different tables, and there's the possibility for a lot of items so i don't want to code a new addition to a PHP file every time i want to add a new product.

I'm thinking of saving the query as a string into a MySQL database, then when an item is purchased i can fetch the string from the database and run it like that.

For example: A table items would contain a field query_to_run which would contain the string UPDATE power_ups SET test = test WHERE test = 1 to be run when a user purchases an item.

Is this ever used or is there a better way to do this?

4

4 回答 4

2

Storing queries in your database may be safer than you think. If the only way to insert the queries is through your own code, then you won't really be at risk of injection attacks (assuming that you write all the code yourself and you aren't including things like nasty where ID=$POST[...] in them.

So, on that note, yes, it is safe to keep SQL in your database.

Here's the but though.

But, I think you would be MUCH better off writing a simple object to handle these sorts of requests. You can very easily create a safe and secure object that takes a UserID and sends it in a query to the database - without the need for any stored SQL in the database (it seems like the only thing that will be changing is the user ID for example?

于 2012-08-12T13:07:09.133 回答
1

If I were to tackle this problem myself I would use OOP PHP to define a power-up class with different types of power-up categorised by the type of database edits they must make.

What I think you are looking for is something that is quicker, and your solution is this (in the short-term) however what happens when you update the database structure or realise your old model doesn't fit when you wish to make improvements?

Because your SQL queries are hard-coded you will have to rewrite each and every one, and each new power up takes longer than if you built a soft-coded framework around them.

So yes your method would work in practice as long as you don't mind sacrificing the extensibility and flexibility of your application in the future.

于 2012-08-12T13:06:34.053 回答
0

I'd rather you do it through php since it's more efficient and less vulnerable.

于 2012-08-12T12:58:20.857 回答
0

Your current method is not flexible at all. For example, when you add a new item, are you going to add a new table as well to store the information about the new item you have just added? If you have 10k different items, are you going to create 10k different tables? There are several other issues with this approach as well.

You should take a look at Fundamentals of Relational Database Design to create a design that takes all the advantage of a relational database.

于 2012-08-12T13:13:47.077 回答